@gangfun/cli 0.12.0 → 0.14.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/launch.js ADDED
@@ -0,0 +1,297 @@
1
+ import { createHash, randomBytes } from 'node:crypto'
2
+ import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
3
+ import { dirname, join } from 'node:path'
4
+ import { createPublicClient, http, parseAbi, formatUnits, encodeFunctionData, isAddress, zeroAddress } from 'viem'
5
+ import { DIR } from './notes.js'
6
+ import { padNets, NOT_ON_MAINNET } from './gangpad.js'
7
+ import { bondAddress, BOND_ABI } from './bond.js'
8
+ import { walletFor } from './fair.js'
9
+ import { parseAmount, parseIntIn, step } from './steps.js'
10
+ import { buybackBpsOf, FACTORY_ABI, notDeployed, simulateCall, SPLITTER_ABI, splitterFactoryAddress, splitterOf } from './buyback.js'
11
+
12
+ /**
13
+ * One command for a launch: `gang create … [--buyback <pct>] [--dev-buy <quote> [--bond <quote> [--bond-hold <tokens|N%|all>]
14
+ * --bond-days <7-90>]]` (V3) and `gang fair create … [--shares <n>] --bond <quote> [--bond-hold …] --bond-days <7-90>` (打新: the dev buys its
15
+ * shares in the create itself). Each run builds the next tx, as every other multi-step command does (wrap / approve
16
+ * steps in between): run it, execute, run the same command again.
17
+ *
18
+ * Progress comes from the chain, not from what was executed: a plan file keeps the wallet, the name / symbol and the
19
+ * pad's token count before the create, and each run looks for a token this wallet created with that symbol since then
20
+ * (none yet → the create; found and the dev holds none → the V3 dev buy; holds some and no bond → the bond; else done).
21
+ * The plan is written only once the create preview succeeds, and a run that finds no token never builds a second
22
+ * create on its own (the first may still be landing): `--restart` does. The plan keeps the token once found (no rescan
23
+ * on later runs) and is marked done at the end: a done launch only reports, even if the dev's balance or the bond
24
+ * changed since (no second buy, bond or create) — for 7 days, then the plan expires.
25
+ * --buyback (V3, taxed): before the create, GangBuybackSplitterFactory clones the dev's splitter at
26
+ * predict(dev, salt), with a fresh salt per plan kept in it (so the address is known before the clone and never another
27
+ * launch's), the create names it as the recipient, and a bind step follows the create. A launch keeps the mode it began
28
+ * with: adding --buyback after the create (or dropping it before) is refused rather than starting over.
29
+ * --buyback-to <addr> names where the dev's part goes (default: the dev); the dev can change it later at once.
30
+ */
31
+
32
+ const LAUNCH_DIR = process.env.GANG_LAUNCH_DIR || join(dirname(DIR), 'launch')
33
+ const TTL_MS = 7 * 24 * 3600_000
34
+ const PAD_ABI = parseAbi([
35
+ 'function tokenCount() view returns (uint256)',
36
+ 'function allTokens(uint256) view returns (address)',
37
+ 'function kindOf(address token) view returns (uint8)',
38
+ '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)',
39
+ 'function sales(address token) view returns (address creator, uint64 progressAt, uint16 capShares, uint16 holdBps, address quote, uint16 sold, bool launched, uint16 mintFeeBps, uint16 exitFeeBps, address gate, uint128 sharePrice, address pair, address refPool, uint16 markSold)',
40
+ ])
41
+ const ERC20_ABI = parseAbi(['function balanceOf(address) view returns (uint256)', 'function symbol() view returns (string)'])
42
+ /** Flags only the chain reads; everything else goes to the step's own command. */
43
+ export const LAUNCH_FLAGS = ['dev-buy', 'bond', 'bond-hold', 'bond-days', 'buyback', 'buyback-to', 'restart']
44
+ const NOTE_FLAGS = ['note', 'conf', 'reveal-after']
45
+ /** `gang fair create --dev-buy`, with or without --bond (index.js stops the lone flag, runLaunch the chained one). */
46
+ export const FAIR_DEV_BUY = 'a 打新 dev buys its shares in the create itself: use --shares <n> (not --dev-buy)'
47
+
48
+ /** The run asks for a chained launch (`kind` 'v3' | 'fair'). */
49
+ export const isLaunch = (kind, flag) => flag('bond') || flag('buyback') || (kind === 'v3' && flag('dev-buy'))
50
+
51
+ const planPath = (key) => join(LAUNCH_DIR, `${createHash('sha256').update(key).digest('hex').slice(0, 32)}.json`)
52
+
53
+ function readPlan(key) {
54
+ try {
55
+ const p = JSON.parse(readFileSync(planPath(key), 'utf8'))
56
+ return p.createdAt > Date.now() - TTL_MS ? p : null
57
+ } catch { return null }
58
+ }
59
+
60
+ function writePlan(key, plan) {
61
+ mkdirSync(LAUNCH_DIR, { recursive: true, mode: 0o700 })
62
+ for (const name of readdirSync(LAUNCH_DIR)) {
63
+ const f = join(LAUNCH_DIR, name)
64
+ try { if (Date.now() - statSync(f).mtimeMs > TTL_MS) unlinkSync(f) } catch { /* gone */ }
65
+ }
66
+ const p = planPath(key)
67
+ writeFileSync(`${p}.${process.pid}.tmp`, JSON.stringify({ ...plan, createdAt: Date.now() }), { mode: 0o600 })
68
+ renameSync(`${p}.${process.pid}.tmp`, p)
69
+ }
70
+
71
+ /** An argv reader over `base` (the real one) with `over` replacing / adding flags; a value of undefined drops one. */
72
+ function argsWith(base, over, drop = []) {
73
+ const has = (n) => (n in over ? over[n] !== undefined : !drop.includes(n) && base.flag(n))
74
+ return {
75
+ flag: has,
76
+ opt: (n, def) => (n in over ? (over[n] === undefined ? def : String(over[n])) : drop.includes(n) ? def : base.opt(n, def)),
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Entry. `kind` 'v3' | 'fair'. deps: { io (index.js PAD_IO: opt, flag, out, fail, …), runV3, runFair, runBond, padNotes }.
82
+ */
83
+ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes }) {
84
+ const { opt, flag, out, fail } = io
85
+ const testnet = flag('testnet')
86
+ const net = padNets(kind)[testnet ? 'testnet' : 'mainnet']
87
+ if (!net.pad) return fail(NOT_ON_MAINNET)
88
+ const name = opt('name'), symbol = opt('symbol')
89
+ if (!name || !symbol) fail('--name and --symbol are required')
90
+ if (flag('follow')) fail('--follow does not apply to a launch')
91
+ if (kind === 'fair' && flag('dev-buy')) fail(FAIR_DEV_BUY)
92
+ if (kind === 'fair' && flag('buyback')) fail('--buyback is for V3 tokens: it makes the tax recipient a buy-back splitter, and a 打新 token has no recipient')
93
+
94
+ // everything checked before the create, so a launch never stops half way on a bad flag
95
+ const devBuy = kind === 'v3' && flag('dev-buy') ? parseAmount(fail, 'dev-buy', opt('dev-buy')) : null
96
+ const bonding = flag('bond')
97
+ if (!bonding && (flag('bond-hold') || flag('bond-days'))) fail('--bond-hold / --bond-days go with --bond <quote>')
98
+ let bond = null
99
+ if (bonding) {
100
+ if (flag('cover')) fail('--cover needs the PancakeSwap pair: a launch bonds before it, so give --bond <quote>')
101
+ if (kind === 'v3' && !devBuy) fail('a V3 launch with --bond needs --dev-buy <quote>: the creator holds nothing until it buys on the curve')
102
+ if (!bondAddress(testnet)) fail(`GangBond is not deployed on ${testnet ? 'the BSC testnet' : 'BSC mainnet'} in this CLI version: drop --bond (and --bond-hold / --bond-days), or add --testnet`)
103
+ const hold = String(opt('bond-hold', 'all')).trim()
104
+ if (!(hold === 'all' || /^(\d+(\.\d*)?|\.\d+)%?$/.test(hold)) || /^0*(\.0*)?%?$/.test(hold)) {
105
+ fail('--bond-hold must be all (everything the dev holds), a token amount, or N% of the supply', { got: opt('bond-hold') })
106
+ }
107
+ bond = { amount: parseAmount(fail, 'bond', opt('bond')), hold, days: parseIntIn(fail, 'bond-days', opt('bond-days'), 7, 90) }
108
+ }
109
+
110
+ // --buyback: a taxed V3 token whose recipient (the part left after holders) is the dev's splitter
111
+ let buyback = null
112
+ if (flag('buyback-to') && !flag('buyback')) fail('--buyback-to <addr> goes with --buyback <pct>: it names where the part not bought back goes')
113
+ if (flag('buyback')) {
114
+ const zero = (f) => /^0+(\.0+)?$/.test(opt(f) ?? '')
115
+ if (!flag('buy-tax') || !flag('sell-tax') || (zero('buy-tax') && zero('sell-tax'))) {
116
+ fail('--buyback needs a taxed token: add --buy-tax and --sell-tax (each 1–5, in %); the buy-back is paid from the tax')
117
+ }
118
+ if (flag('recipient')) fail('--buyback makes the recipient your buy-back splitter: leave --recipient out')
119
+ if (/^0*100(\.0+)?$/.test(opt('dividend', '0'))) fail('--dividend 100 leaves nothing for the recipient, so nothing to buy back: lower it or drop --buyback')
120
+ const factory = splitterFactoryAddress(testnet)
121
+ if (!factory) fail(notDeployed(testnet))
122
+ let payee = null
123
+ if (flag('buyback-to')) {
124
+ payee = opt('buyback-to')
125
+ if (!isAddress(payee ?? '') || payee === zeroAddress) fail('--buyback-to must be a 0x address, checksummed or all lowercase (where the part not bought back goes; leave it out for your own wallet)', { got: payee ?? null })
126
+ }
127
+ buyback = { bps: buybackBpsOf(fail, opt('buyback')), factory, payee }
128
+ }
129
+
130
+ const client = createPublicClient({ chain: net.chain, transport: http(net.rpc) })
131
+ const read = (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args })
132
+ const me = walletFor({ chainId: net.chainId }, opt('from'))
133
+ const key = [net.chainId, net.pad, me.toLowerCase(), kind, name, symbol].join('|')
134
+ const steps = [...(buyback ? ['buyback-splitter'] : []), kind === 'v3' ? 'create' : 'create (dev shares included)', ...(buyback ? ['bind'] : []),
135
+ ...(devBuy ? ['dev-buy'] : []), ...(bond ? ['bond'] : [])]
136
+ const rerun = 're-run this same command after executing it'
137
+ const tag = (stage, extra = {}) => ({ launch: { stage, steps, ...extra } })
138
+ const withTag = (stage, extra) => (o) => out({ ...o, ...tag(stage, extra) })
139
+
140
+ let plan = flag('restart') ? null : readPlan(key)
141
+ const base = { kind, name, symbol, me, chainId: net.chainId, pad: net.pad }
142
+
143
+ // ---- a launch keeps the mode it began with (the create, once built, is never redone by a changed flag)
144
+ const created = plan?.startCount !== undefined
145
+ if (buyback && created && !plan.splitter) {
146
+ return fail('this launch was created without --buyback (its recipient is fixed): run it again without --buyback, or add --restart for a new token')
147
+ }
148
+ if (!buyback && !created && plan?.salt) {
149
+ return fail('this launch began with --buyback (its splitter is cloned or on the way): run it again with --buyback, or add --restart without it')
150
+ }
151
+
152
+ // ---- buy-back splitter: cloned for the dev before the create, at predict(dev, plan.salt)
153
+ if (buyback && !created) {
154
+ if (!plan?.salt) {
155
+ const salt = `0x${randomBytes(32).toString('hex')}`
156
+ const at = await read(buyback.factory, FACTORY_ABI, 'predict', [me, salt])
157
+ const args = [buyback.bps, salt, buyback.payee ?? zeroAddress]
158
+ const sim = await simulateCall(client, me, buyback.factory, FACTORY_ABI, 'create', args)
159
+ if (sim.failed) return out({ success: false, step: 'buyback-splitter', ...tag('buyback-splitter'), ...sim.failed })
160
+ writePlan(key, { ...base, salt, splitter: at, factory: buyback.factory })
161
+ const data = encodeFunctionData({ abi: FACTORY_ABI, functionName: 'create', args })
162
+ return out({
163
+ ...step({ chainId: net.chainId }, { from: me, to: buyback.factory, data }, {
164
+ step: 'buyback-splitter', chainId: Number(net.chainId), factory: buyback.factory, buybackPct: buyback.bps / 100,
165
+ splitter: at, payee: buyback.payee ?? me,
166
+ note: `clones your buy-back splitter (listed as a tax recipient in the same tx): ${buyback.bps / 100}% of the recipient's part is bought back and burned, the rest goes to ${buyback.payee ? `${buyback.payee} (--buyback-to)` : 'you'}. Later a raise applies at once, a cut only after a 3-day notice; the payee can be changed at once (gang buyback set-payee)`,
167
+ }, flag('calldata'), io.summarize),
168
+ ...tag('buyback-splitter', { splitter: at, next: `${rerun}: it then builds the create with the splitter as the recipient` }),
169
+ })
170
+ }
171
+ if ((await client.getCode({ address: plan.splitter }) ?? '0x') === '0x') {
172
+ return out({
173
+ success: false, ...tag('buyback-splitter', { splitter: plan.splitter }), error: 'the buy-back splitter is not on chain yet',
174
+ hint: `if the clone was executed, wait for it to land and ${rerun.replace(' after executing it', '')}; if it was not, add --restart to build it again`,
175
+ })
176
+ }
177
+ const s = await splitterOf(read, plan.splitter)
178
+ if (!s || s.dev.toLowerCase() !== me.toLowerCase() || s.token) {
179
+ return fail('the splitter at this launch\'s address is not an unbound buy-back splitter of this wallet: add --restart', { splitter: plan.splitter })
180
+ }
181
+ if (s.buybackBps !== buyback.bps) {
182
+ return fail(`this launch's splitter buys back ${s.buybackPct}%, not ${buyback.bps / 100}%: run it again with --buyback ${s.buybackPct}, or add --restart for a new splitter (gang buyback set changes it after the create)`, { splitter: plan.splitter })
183
+ }
184
+ const wantPayee = (buyback.payee ?? me).toLowerCase()
185
+ if (s.payee.toLowerCase() !== wantPayee) {
186
+ const was = s.payee.toLowerCase() === me.toLowerCase() ? 'leave --buyback-to out' : `--buyback-to ${s.payee}`
187
+ return fail(`this launch's splitter pays ${s.payee}, not ${buyback.payee ?? me}: run it again with ${was}, or add --restart for a new splitter (gang buyback set-payee changes it after the create)`, { splitter: plan.splitter })
188
+ }
189
+ }
190
+
191
+ // ---- create
192
+ if (!created) {
193
+ const startCount = (await read(net.pad, PAD_ABI, 'tokenCount')).toString()
194
+ const createIo = {
195
+ ...io,
196
+ ...argsWith(io, plan?.splitter ? { recipient: plan.splitter } : {}, LAUNCH_FLAGS),
197
+ out: (o) => {
198
+ // the plan starts with the create tx itself: a wrap / approve step before it (or a failed preview) leaves none,
199
+ // so the next run builds the create again
200
+ const built = o.success && o.step === 'create'
201
+ if (built) writePlan(key, { ...base, ...(plan?.splitter && { salt: plan.salt, splitter: plan.splitter, factory: plan.factory }), startCount })
202
+ const after = steps[steps.indexOf(kind === 'v3' ? 'create' : 'create (dev shares included)') + 1]
203
+ return out({
204
+ ...o,
205
+ ...tag('create', built ? { next: `${rerun}: it finds the new token and continues with ${after ?? 'nothing'}` } : o.success ? { next: `${rerun}: it then builds the create` } : {}),
206
+ })
207
+ },
208
+ }
209
+ if (kind === 'v3') return runV3('create', { ...createIo, notes: padNotes('v3', 'create') })
210
+ return runFair('create', { ...createIo, notes: padNotes('fair', 'create') })
211
+ }
212
+
213
+ // ---- the token this plan created: kept in the plan once found, else looked up from the pad's list since the plan
214
+ let token = plan.token ?? null
215
+ if (!token) {
216
+ const count = Number(await read(net.pad, PAD_ABI, 'tokenCount'))
217
+ for (let i = Number(plan.startCount); i < count && !token; i++) {
218
+ const t = await read(net.pad, PAD_ABI, 'allTokens', [BigInt(i)])
219
+ const k = Number(await read(net.pad, PAD_ABI, 'kindOf', [t]))
220
+ const creator = k === 1 ? (await read(net.pad, PAD_ABI, 'curves', [t]))[0] : k === 2 ? (await read(net.pad, PAD_ABI, 'sales', [t]))[0] : zeroAddress
221
+ if (creator.toLowerCase() !== me.toLowerCase()) continue
222
+ if ((await read(t, ERC20_ABI, 'symbol')) === symbol) token = t
223
+ }
224
+ if (token) {
225
+ plan = { ...plan, token }
226
+ writePlan(key, plan)
227
+ }
228
+ }
229
+ if (!token) {
230
+ return out({
231
+ success: false, ...tag('create'), error: 'no token from this launch yet',
232
+ hint: `if the create was executed, wait for it to land and ${rerun.replace(' after executing it', '')}; if it was not (or its preview failed), add --restart to build the create again`,
233
+ })
234
+ }
235
+
236
+ // later steps carry no note (it went on the create) and take the token from the plan
237
+ const stepIo = (over) => ({ ...io, ...argsWith(io, { ...over, token }, [...LAUNCH_FLAGS, ...NOTE_FLAGS, 'name', 'symbol']) })
238
+ const bal = await read(token, ERC20_ABI, 'balanceOf', [me])
239
+ const buybackState = () => (plan.splitter ? splitterOf(read, plan.splitter) : null)
240
+
241
+ // ---- done: the report only, whatever happened to the balance or the bond since
242
+ const report = async () => {
243
+ const done = {
244
+ success: true, ...tag('done', { token, again: 'this launch is done; running the command again only reports it. Another token with the same name / symbol: add --restart' }),
245
+ token, name, symbol, devBalance: formatUnits(bal, 18), chainId: Number(net.chainId),
246
+ }
247
+ const bb = await buybackState()
248
+ if (bb) done.buyback = bb
249
+ if (!bond) return out({ ...done, note: `launched: gang ${kind} info --token ${token}${testnet ? ' --testnet' : ''}` })
250
+ return runBond('status', { ...stepIo({}), out: (o) => out({ ...done, bondStatus: o, note: `launched and bonded: gang bond status --token ${token}${testnet ? ' --testnet' : ''}` }) })
251
+ }
252
+ if (plan.done) return report()
253
+
254
+ // ---- bind the splitter to the token (anyone may; the launch does it right after the create)
255
+ if (plan.splitter) {
256
+ const bound = await read(plan.splitter, SPLITTER_ABI, 'token')
257
+ if (bound === zeroAddress) {
258
+ const sim = await simulateCall(client, me, plan.splitter, SPLITTER_ABI, 'bind', [token])
259
+ if (sim.failed) return out({ success: false, step: 'bind', ...tag('bind', { token }), ...sim.failed })
260
+ const data = encodeFunctionData({ abi: SPLITTER_ABI, functionName: 'bind', args: [token] })
261
+ return out({
262
+ ...step({ chainId: net.chainId }, { from: me, to: plan.splitter, data }, {
263
+ step: 'bind', chainId: Number(net.chainId), token, splitter: plan.splitter,
264
+ note: 'ties the splitter to this token for good (what it buys back and burns)',
265
+ }, flag('calldata'), io.summarize),
266
+ ...tag('bind', { token, next: `${rerun}${devBuy ? ': it continues with the dev buy' : bond ? ': it continues with the bond' : ': the launch is then done'}` }),
267
+ })
268
+ }
269
+ if (bound.toLowerCase() !== token.toLowerCase()) {
270
+ return out({ success: false, ...tag('bind', { token }), error: 'the splitter is bound to another token', splitter: plan.splitter, boundTo: bound })
271
+ }
272
+ }
273
+
274
+ // ---- V3 dev buy (a 打新 dev already holds its shares' tokens)
275
+ if (devBuy && bal === 0n) {
276
+ return runV3('buy', {
277
+ ...stepIo({ amount: devBuy }), out: withTag('dev-buy', { token, next: `${rerun}${bond ? ': it continues with the bond' : ': the launch is then done'}` }),
278
+ notes: padNotes('v3', 'buy', { note: null }),
279
+ })
280
+ }
281
+
282
+ // ---- bond
283
+ if (bond) {
284
+ const b = await read(bondAddress(testnet), BOND_ABI, 'bondOf', [token])
285
+ if (Number(b.round) === 0) {
286
+ const hold = bond.hold === 'all' ? formatUnits(bal, 18) : bond.hold
287
+ return runBond('post', {
288
+ ...stepIo({ amount: bond.amount, hold, days: bond.days, cover: undefined }),
289
+ out: withTag('bond', { token, next: `${rerun}: it reports the launch` }),
290
+ })
291
+ }
292
+ }
293
+
294
+ // ---- every step done: mark the plan, so later runs only report (never a second buy, bond or create)
295
+ writePlan(key, { ...plan, done: true })
296
+ return report()
297
+ }
package/src/pool.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { parseAbi, encodeFunctionData, formatUnits, parseUnits, zeroAddress } from 'viem'
2
2
  import { decimalsOf, isMissingFunction, poolSellQuote, ROUTER_ABI, routerDeadline, step, units, GAS_RESERVE } from './steps.js'
3
+ import { bondGuard } from './bond.js'
3
4
 
4
5
  /**
5
6
  * PancakeSwap (V2 pool) buys and sells of a graduated / launched token through GangRouter — V3 and 打新 tokens
@@ -12,6 +13,7 @@ import { decimalsOf, isMissingFunction, poolSellQuote, ROUTER_ABI, routerDeadlin
12
13
  * Minimums: a buy = Pancake getAmountsOut less the token's buy tax, less --slippage; a sell = the tax handler's
13
14
  * previewSellNextBlock (the sell tax and the chunk of held tax it sells first included, as of the next block), or
14
15
  * getAmountsOut less the sell tax when there is no handler quote (V2 tokens, untaxed V3), less --slippage.
16
+ * A sell with `p.bond` ({ testnet, breakBond, settleFirst }) is checked against the seller's GangBond first (bondGuard).
15
17
  */
16
18
 
17
19
  // Pancake V2 routers: a GangRouter address must never be one of these (they would take an approve and swap for anyone).
@@ -185,7 +187,7 @@ async function build(ctx, p, { rawOnly, summarize, revertOf }) {
185
187
  const quoteSymbol = (await symbolOf(ctx, quote)) || quote
186
188
  const deadline = routerDeadline()
187
189
  const taxPct = (bps) => (bps || 0) / 100
188
- let call, probe, value = 0n, pull = null, fields
190
+ let call, probe, value = 0n, pull = null, fields, guard = null
189
191
  try {
190
192
  if (side === 'buy') {
191
193
  const payBnb = !!p.payBnb
@@ -226,6 +228,12 @@ async function build(ctx, p, { rawOnly, summarize, revertOf }) {
226
228
  const amount = p.all ? bal : parseUnits(p.amount, 18)
227
229
  if (amount === 0n) throw new PoolError(`--amount ${p.amount} rounds to 0 tokens`)
228
230
  if (amount > bal) return failOut({ step: 'pool-sell', error: 'amount exceeds balance', balance: formatUnits(bal, 18) })
231
+ // the creator's own bond: refuse a sell that breaks it (unless --break-bond), settle first past the deadline
232
+ if (p.bond) {
233
+ guard = await bondGuard(ctx, { token, me, amount, ...p.bond }, rawOnly, summarize)
234
+ if (guard?.refuse) return failOut({ step: 'pool-sell', wallet: me, ...guard.refuse })
235
+ if (guard?.settleStep) return guard.settleStep
236
+ }
229
237
  const taxed = (p.sellTaxBps || 0) > 0
230
238
  let quoteOut, quotedWith
231
239
  if (taxed && p.handler) {
@@ -254,6 +262,7 @@ async function build(ctx, p, { rawOnly, summarize, revertOf }) {
254
262
  deadline: Number(deadline), quotedWith,
255
263
  ...(toBnb && !quoteWbnb && { expectQuoteBeforeBnb: await units(ctx, quote, quoteOut) }),
256
264
  gas: p.swapBackGas ? POOL_SELL_GAS_NOTE : 'let the wallet estimate gas',
265
+ ...guard?.info,
257
266
  note: quotedWith === 'getAmountsOut'
258
267
  ? `minOut = getAmountsOut of the amount less the ${taxPct(p.sellTaxBps)}% sell tax${toBnb && !quoteWbnb ? ' (then quote → WBNB)' : ''}, less --slippage (the sell reverts below it)`
259
268
  : `minOut = the tax handler's ${quotedWith} (sell tax and the chunk of held tax sold first included, as of the next block)${toBnb && !quoteWbnb ? ', then getAmountsOut quote → WBNB' : ''}, less --slippage (the sell reverts below it)`,
package/src/v3.js CHANGED
@@ -5,6 +5,8 @@ import { UA } from './version.js'
5
5
  import { walletFor } from './fair.js'
6
6
  import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets } from './gangpad.js'
7
7
  import { poolPayBnb, poolTrade } from './pool.js'
8
+ import { bondGuard } from './bond.js'
9
+ import { splitterOf } from './buyback.js'
8
10
 
9
11
  /**
10
12
  * `gang v3 …` — LaunchpadV3 (tax recipient): a token with its own buy / sell tax (1–5% each), a dividend share and a
@@ -274,7 +276,9 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
274
276
  const taxNote = c.buyTaxPct > 0 || c.sellTaxPct > 0
275
277
  ? `buy ${c.buyTaxPct}% / sell ${c.sellTaxPct}% tax only in the PancakeSwap pool after graduation (${fees.platformTaxPct}% of volume to the platform, then ${c.dividendPct}% of the rest to holders, the remainder to the recipient); curve trades pay only the ${fees.curveFeePct}% fee, no tax`
276
278
  : `untaxed; curve trades pay the ${fees.curveFeePct}% fee`
277
- return out({ success: true, chainId: Number(ctx.chainId), ...fees, ...pub, taxNote, ...(swapBack && { swapBack }) })
279
+ // a recipient that is the dev's buy-back splitter: its ratio and what waits to be bought back
280
+ const buyback = c.recipient && !c.recipientIsCreator ? await splitterOf(ctx.read, c.recipient) : null
281
+ return out({ success: true, chainId: Number(ctx.chainId), ...fees, ...pub, taxNote, ...(swapBack && { swapBack }), ...(buyback && { buyback }) })
278
282
  }
279
283
 
280
284
  if (sub === 'status') {
@@ -472,6 +476,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
472
476
  side: 'sell', token, quote: c.quote, me, amount: flag('all') ? null : parseAmount(fail, 'amount', opt('amount')), all: flag('all'),
473
477
  slippage, buyTaxBps: Math.round(c.buyTaxPct * 100), sellTaxBps: Math.round(c.sellTaxPct * 100), handler: c.taxHandler,
474
478
  swapBackGas: c.sellTaxPct > 0, toBnb: flag('to-bnb'), base: { kind: 'v3', pair: c.pair, ...notes.pool },
479
+ bond: { testnet, breakBond: flag('break-bond'), settleFirst: flag('settle-first') },
475
480
  }, { rawOnly, summarize, revertOf }))
476
481
  }
477
482
  if (flag('all')) return fail('--all needs a wallet (or --from <addr>) whose balance can be read', { pair: c.pair })
@@ -493,6 +498,9 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
493
498
  if (bal === 0n) fail('no balance to sell')
494
499
  const amount = flag('all') ? bal : parseUnits(parseAmount(fail, 'amount', opt('amount')), 18)
495
500
  if (amount > bal) fail('amount exceeds balance', { balance: formatUnits(bal, 18) })
501
+ // a bond posted on the curve already binds: a creator's curve sell below X breaks it
502
+ const guard = await bondGuard(ctx, { token, me, amount, testnet, breakBond: flag('break-bond'), settleFirst: flag('settle-first') }, rawOnly, summarize)
503
+ if (guard?.refuse) return out({ success: false, step: 'sell', wallet: me, ...guard.refuse })
496
504
  const pre = await fundingStep(ctx, me, token, amount, c.quoteSymbol, 'approve', rawOnly, summarize)
497
505
  if (pre) return out(pre.success ? { ...pre, ...notes.skipped() } : pre)
498
506
  const sim = await simulate(ctx, me, ctx.pad, PAD_ABI, 'sell', [token, amount, 0n])
@@ -502,7 +510,8 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
502
510
  step: 'sell', chainId: Number(ctx.chainId), token, amount: formatUnits(amount, 18), quote: c.quoteSymbol,
503
511
  expectOut: await units(ctx, c.quote, sim.result), minOut: await units(ctx, c.quote, minOut), curveTaxPct: 0,
504
512
  ...(c.sellTaxPct > 0 && { poolSellTaxPct: c.sellTaxPct }),
505
- curveFeePct: (await feesOf(ctx)).curveFeePct, note: 'expectOut is after the 1% curve fee only (no tax on the curve; the sell tax applies only in the pool after graduation)',
513
+ curveFeePct: (await feesOf(ctx)).curveFeePct, ...guard?.info,
514
+ note: 'expectOut is after the 1% curve fee only (no tax on the curve; the sell tax applies only in the pool after graduation)',
506
515
  }, 'sell'))
507
516
  }
508
517