@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/v3.js CHANGED
@@ -3,7 +3,8 @@ import { decimalsOf, defaultRefPool, dividendOf, VAULT_ABI, fundingStep as fund,
3
3
  import { API } from './discover.js'
4
4
  import { UA } from './version.js'
5
5
  import { walletFor } from './fair.js'
6
- import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets, rpcTransport } from './gangpad.js'
6
+ import { atTokenPad, CREATOR_FEE_ABI, GRAD_TARGET_ABI, gradTargetBnbOf, gradTiersOf, KIND_UNREAD, MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets, rpcTransport } from './gangpad.js'
7
+ import { createNote, curveCreatorFee } from './creatorfee.js'
7
8
  import { poolPayBnb, poolTrade } from './pool.js'
8
9
  import { bondGuard } from './bond.js'
9
10
  import { splitterOf } from './buyback.js'
@@ -23,6 +24,7 @@ export const V3_NETS = padNets('v3')
23
24
  const TAX = '(uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address recipient)'
24
25
  const PAD_ABI = parseAbi([
25
26
  `function create(string name, string symbol, string logoURI, string metaURI, address quote, address refPool, ${TAX} tax) returns (address)`,
27
+ `function createWithGradTarget(string name, string symbol, string logoURI, string metaURI, address quote, address refPool, ${TAX} tax, uint256 gradBnb) returns (address)`,
26
28
  'function buy(address token, uint256 quoteIn, uint256 minTokensOut) returns (uint256)',
27
29
  'function sell(address token, uint256 tokensIn, uint256 minQuoteOut) returns (uint256)',
28
30
  `function checkTaxConfig(${TAX} tax) view returns (bool ok, string reason)`,
@@ -74,6 +76,7 @@ const HINTS = {
74
76
  BadTaxConfig: 'a tax setting is out of bounds, or the recipient is neither you nor on the whitelist: see reason',
75
77
  NotAgent: 'this wallet holds no Agent ID; V3 create and curve trades are Agent-only',
76
78
  WalletCapReached: 'this wallet already holds the per-wallet cap (1% of supply)',
79
+ BadGradTarget: 'the graduation target (--grad) must be one of the pad\'s GRAD_BNB_TIERS: 6 / 9 / 12 / 15 BNB raised',
77
80
  AlreadyGraduated: 'the token graduated: re-run gang buy / gang sell, which now trade it in the PancakeSwap pool',
78
81
  Slippage: 'the price moved past --slippage; re-run to re-quote',
79
82
  RefPoolRequired: 'a non-WBNB --quote needs --ref-pool: a Pancake V2 pair or V3 pool that holds the quote token',
@@ -95,8 +98,8 @@ const HINTS = {
95
98
  VaultFloorTooHigh: 'the platform\'s dividend vault requires a larger holding than V3 dividends allow (10,000 tokens), so a dividend token can\'t be created right now; --dividend 0 still works, or ask gang to fix the vault setting',
96
99
  }
97
100
 
98
- /** What `gang tx` decodes a V3 trade's logs with (the pad, the tax router, the dividend vault). */
99
- export const V3_EVENT_ABIS = [PAD_ABI, TAX_ROUTER_ABI, VAULT_ABI]
101
+ /** What `gang tx` decodes a V3 trade's logs with (the pad and its 2.0 creator fee, the tax router, the dividend vault). */
102
+ export const V3_EVENT_ABIS = [PAD_ABI, CREATOR_FEE_ABI, GRAD_TARGET_ABI, TAX_ROUTER_ABI, VAULT_ABI]
100
103
 
101
104
  export function v3Ctx(testnet) {
102
105
  const net = V3_NETS[testnet ? 'testnet' : 'mainnet']
@@ -107,11 +110,19 @@ export function v3Ctx(testnet) {
107
110
 
108
111
  const symbolOf = async (ctx, token) => { try { return await ctx.read(token, ERC20_ABI, 'symbol') } catch { return null } }
109
112
  const pct = (bps) => Number(bps) / 100
113
+ const bnbOf = (wei) => Number(wei / 10n ** 15n) / 1000
114
+ /**
115
+ * The graduation target in words. A non-WBNB quote fixes the amount in the quote at create (`inQuote`, e.g. "1234.5
116
+ * USDT"): the BNB figure is what that was worth then, a nominal target whose BNB worth moves with the quote's price.
117
+ */
118
+ const gradLine = (bnb, inQuote) => (inQuote
119
+ ? `the curve graduates into PancakeSwap once ${inQuote} is raised: ${bnb} BNB priced in the quote at create, fixed in the quote, so what it is worth in BNB moves with the quote's price (market cap at graduation ≈ 5× the target)`
120
+ : `the curve graduates into PancakeSwap once ${bnb} BNB is raised (market cap then ≈ ${bnb * 5} BNB)`)
110
121
  const VIRTUAL_TOKEN = 1_066_666_666_666_666_666_666_666_667n
111
122
  const ceilDiv = (a, b) => (a + b - 1n) / b
112
123
 
113
124
  /** Revert name (+ BadTaxConfig reason) of a failed call, or null when it was the RPC. */
114
- const revertOf = (e) => revertIn(e, [PAD_ABI, TAX_ROUTER_ABI, GANG_ROUTER_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
125
+ const revertOf = (e) => revertIn(e, [PAD_ABI, CREATOR_FEE_ABI, GRAD_TARGET_ABI, TAX_ROUTER_ABI, GANG_ROUTER_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
115
126
 
116
127
  /** eth_call `data` from `from`: { result } when it passes, { failed } with the revert (or RPC error) otherwise. */
117
128
  async function simulate(ctx, from, to, abi, functionName, args, value = 0n) {
@@ -159,9 +170,11 @@ export async function curveOf(ctx, token) {
159
170
  const [creator, quote, realQuote, sold, gradAmt, virtualQuote, graduated, buyTaxBps, sellTaxBps, dividendBps, pair] = c
160
171
  if (creator === zeroAddress) return null
161
172
  // the recipient is not in curves(): it lives on the tax handler's route, read back through taxConfigOf
162
- const [{ handler, router, registry }, remaining, tax] = await Promise.all([
173
+ const [{ handler, router, registry }, remaining, tax, targetBnb] = await Promise.all([
163
174
  taxContracts(ctx),
164
175
  ctx.read(ctx.pad, PAD_ABI, 'graduationRemaining', [token]), ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token]),
176
+ // the target in BNB raised (2.0: the creator's pick); graduationAt below is the same target in the quote
177
+ gradTargetBnbOf(ctx, token).catch(() => null),
165
178
  ])
166
179
  const recipient = tax[3] === zeroAddress ? null : tax[3]
167
180
  // §22: the creator may be its own recipient without a listing; say so, the platform did not review it
@@ -184,23 +197,28 @@ export async function curveOf(ctx, token) {
184
197
  buyTaxPct: pct(buyTaxBps), sellTaxPct: pct(sellTaxBps), dividendPct: pct(dividendBps), recipient, recipientLabel: label,
185
198
  ...(recipientIsCreator && { recipientIsCreator: true, recipientNote: 'the recipient is the creator itself, not reviewed by the platform' }),
186
199
  raised: await units(ctx, quote, graduated ? gradAmt : realQuote), graduationAt: await units(ctx, quote, gradAmt),
187
- toGraduation: await units(ctx, quote, remaining),
200
+ graduationTargetBnb: targetBnb, toGraduation: await units(ctx, quote, remaining),
188
201
  progressPct: graduated ? 100 : gradAmt > 0n ? Number((realQuote * 10_000n) / gradAmt) / 100 : 0,
189
202
  priceQuote: await units(ctx, quote, price), priceFrom: graduated ? 'pool' : 'curve', priceRaw: price,
190
- owedToRecipient: await units(ctx, quote, owed), owedRaw: owed, reserveTokenRaw, curveRaw: { realQuote, sold, virtualQuote },
203
+ owedToRecipient: await units(ctx, quote, owed), owedRaw: owed, reserveTokenRaw, curveRaw: { realQuote, sold, virtualQuote, remaining },
191
204
  }
192
205
  }
193
206
 
194
207
  /**
195
- * What a curve buy of `quoteIn` that gets `tokensOut` spends, the fee included (CurveLogic _quoteInFor + _recomputeFee):
196
- * less than quoteIn when the wallet cap or the graduation cut trimmed it and the rest is refunded.
208
+ * What a curve buy of `quoteIn` that gets `tokensOut` spends, the fee included, as CurveLogic trims it: first to the
209
+ * token's own graduation amount (what is still to raise), then to the wallet cap (`room`, _quoteInFor), each followed by
210
+ * _recomputeFee. { spent, cut: null | 'graduation' | 'wallet cap' }: the rest of quoteIn is refunded.
197
211
  */
198
- async function spentFor(ctx, c, quoteIn, tokensOut) {
199
- const { realQuote, sold, virtualQuote } = c.curveRaw
200
- const net = ceilDiv(virtualQuote * VIRTUAL_TOKEN, VIRTUAL_TOKEN - sold - tokensOut) - (virtualQuote + realQuote)
212
+ async function spentFor(ctx, c, quoteIn, tokensOut, room) {
213
+ const { realQuote, sold, virtualQuote, remaining } = c.curveRaw
201
214
  const feeBps = BigInt(Math.round((await feesOf(ctx)).curveFeePct * 100))
202
- const gross = ceilDiv(net * 10_000n, 10_000n - feeBps)
203
- return gross < quoteIn ? gross : quoteIn
215
+ const gross = (net) => { const g = ceilDiv(net * 10_000n, 10_000n - feeBps); return g < quoteIn ? g : quoteIn }
216
+ if (room !== undefined && tokensOut === room) {
217
+ const net = ceilDiv(virtualQuote * VIRTUAL_TOKEN, VIRTUAL_TOKEN - sold - tokensOut) - (virtualQuote + realQuote)
218
+ return { spent: gross(net), cut: 'wallet cap' }
219
+ }
220
+ if (quoteIn - (quoteIn * feeBps) / 10_000n > remaining) return { spent: gross(remaining), cut: 'graduation' }
221
+ return { spent: quoteIn, cut: null }
204
222
  }
205
223
 
206
224
  /** `token` funding for `need` toward the pad (wrap BNB, then approve): a step object, or null when ready. */
@@ -256,12 +274,17 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
256
274
  return out({ success: true, status, items: (r.items || []).map((x) => ({
257
275
  token: x.address, symbol: x.symbol, buyTaxPct: pct(x.buyTaxBps), sellTaxPct: pct(x.sellTaxBps), dividendPct: pct(x.dividendBps),
258
276
  recipient: x.recipient, recipientLabel: x.recipientLabel, quote: x.quoteSymbol, progressPct: x.progressPct, graduated: x.graduated,
277
+ // the target per token (2.0: the creator's pick), never a fixed 15 BNB: in the quote from gradAmt, in BNB when gang.fun sends it
278
+ ...(x.gradAmt != null && { graduationAt: f(x.gradAmt, x.quoteDecimals) }),
279
+ ...(x.gradTargetBnb != null && { graduationTargetBnb: Number(x.gradTargetBnb) }),
259
280
  chainId: x.chainId, link: `https://gang.fun/token/${x.address}`,
260
281
  })) })
261
282
  }
262
283
 
263
284
  let ctx
264
285
  try { ctx = v3Ctx(testnet) } catch (e) { return fail(e.message) }
286
+ // a token is served by the GangLaunchpad generation that has it (its pad, router, GangBond); a create goes to the newest
287
+ if (sub !== 'create' && sub !== 'tx' && (await atTokenPad(ctx, opt('token'))) === null) return fail(KIND_UNREAD.error, { token: opt('token'), retry: KIND_UNREAD.retry })
265
288
  // not a curve on this pad: on the merged pad it may be a 打新 token (kindOf), so point at `gang fair`
266
289
  const notV3 = async (token) => {
267
290
  const { error, kind } = await notThisKind(ctx, token, 'v3', net)
@@ -295,8 +318,13 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
295
318
  ? { 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
296
319
  const splitWarn = split && split.token && split.token.toLowerCase() !== token.toLowerCase()
297
320
  ? { 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
321
+ // 2.0: the creator's part of the curve fee, waiting on the pad
322
+ const gen = await curveCreatorFee(ctx, token, c, net)
323
+ const nonWbnb = c.quote.toLowerCase() !== String(ctx.wbnb).toLowerCase()
324
+ const graduationNote = c.graduationTargetBnb != null && !c.graduated
325
+ ? gradLine(c.graduationTargetBnb, nonWbnb ? `${c.graduationAt} ${c.quoteSymbol || 'of the quote'}` : null) : null
298
326
  return out({
299
- success: true, chainId: Number(ctx.chainId), ...fees, ...pub, taxNote, ...(swapBack && { swapBack }), ...(buyback && { buyback }),
327
+ success: true, chainId: Number(ctx.chainId), ...fees, ...pub, ...gen, ...(graduationNote && { graduationNote }), taxNote, ...(swapBack && { swapBack }), ...(buyback && { buyback }),
300
328
  ...(split && { split: { ...split, ...splitWarn } }), ...(lp && { lp: { ...lp, ...lpWarn } }),
301
329
  ...(combo && { combo: { ...combo, ...(comboWarning && { warning: comboWarning }) } }),
302
330
  })
@@ -312,9 +340,12 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
312
340
  const { claimableRaw: _r, ...dividend } = c.dividendPct > 0 ? await dividendOf(ctx, vault, token, me, c.quote, c.priceRaw) : {}
313
341
  // graduated: what selling the whole balance into the pool pays now (sell tax and the chunk sold first included)
314
342
  const q = c.graduated && c.pair && bal > 0n ? await poolSellQuote(ctx, c.taxHandler, token, bal) : null
343
+ // the creator's own view also shows its creator fee (2.0)
344
+ const { creatorFee } = me.toLowerCase() === c.creator.toLowerCase() ? await curveCreatorFee(ctx, token, c, net) : {}
315
345
  return out({
316
346
  success: true, chainId: Number(ctx.chainId), wallet: me, token, quote: c.quoteSymbol, graduated: c.graduated,
317
- balance: formatUnits(bal, 18), dividendPct: c.dividendPct,
347
+ balance: formatUnits(bal, 18), dividendPct: c.dividendPct, ...(creatorFee && { creatorFee }),
348
+ graduationTargetBnb: c.graduationTargetBnb, graduationAt: c.graduationAt, progressPct: c.progressPct,
318
349
  ...(q && {
319
350
  poolSellAll: {
320
351
  expectOut: await units(ctx, c.quote, q.out), minOut: await units(ctx, c.quote, minOf(q.out, slippage)), slippagePct: slippage,
@@ -367,6 +398,9 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
367
398
  if (!(n >= 1 && n <= 5)) fail(`--${f} must be a number between 1 and 5 (in %); for an untaxed token leave out both tax flags (or give both as 0)`, { got: opt(f) ?? null })
368
399
  return n
369
400
  }
401
+ // --grad: the graduation target in BNB raised, one of the pad's GRAD_BNB_TIERS (2.0); left out: the pad's default
402
+ const grad = flag('grad') ? Number(opt('grad')) : null
403
+ if (grad !== null && !(grad > 0)) fail('--grad must be the graduation target in BNB raised: 6, 9, 12 or 15', { got: opt('grad') ?? null })
370
404
  const buyTax = taxed ? taxOf('buy-tax') : 0
371
405
  const sellTax = taxed ? taxOf('sell-tax') : 0
372
406
  const dividend = taxed ? parseNum(fail, 'dividend', opt('dividend', '0'), 0, 100) : 0
@@ -379,6 +413,12 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
379
413
  const refPool = flag('ref-pool') ? opt('ref-pool') : (defaultRefPool(ctx.chainId, quote) ?? zeroAddress)
380
414
  if (!isAddress(quote ?? '') || !isAddress(refPool ?? '')) fail('--quote / --ref-pool must be 0x addresses')
381
415
  const tax = { buyTaxBps: Math.round(buyTax * 100), sellTaxBps: Math.round(sellTax * 100), dividendBps: Math.round(dividend * 100), recipient }
416
+ // --grad first: a pad without the pick (1.0) refuses it whatever else the create would say
417
+ const tiers = await gradTiersOf(ctx)
418
+ if (grad !== null && !tiers) {
419
+ fail(`--grad: this GangLaunchpad${ctx.gen ? ` (${ctx.gen})` : ''} has no graduation target to pick; every curve graduates at ${bnbOf(await ctx.read(ctx.pad, GRAD_TARGET_ABI, 'TARGET_GRAD_BNB'))} BNB raised: leave --grad out`)
420
+ }
421
+ if (grad !== null && !tiers.includes(grad)) fail(`--grad must be one of ${tiers.join(' / ')} (BNB raised)`, { got: opt('grad') })
382
422
  // the recipient may be the creator itself: checkTaxConfigFor knows who creates (a pad without it: checkTaxConfig)
383
423
  const [ok, reason] = await ctx.read(ctx.pad, PAD_ABI, 'checkTaxConfigFor', [me, tax]).catch((e) => {
384
424
  if (!noSuchFunction(e)) throw e
@@ -386,15 +426,22 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
386
426
  })
387
427
  if (!ok) fail(`tax setting refused: ${reason}`, { hint: HINTS.BadTaxConfig, tax: { buyTax, sellTax, dividend, recipient } })
388
428
  if (!(await ctx.read(ctx.pad, PAD_ABI, 'isAgent', [me]))) fail('this wallet holds no Agent ID; V3 create is Agent-only', { wallet: me })
389
- // like LaunchpadV2: WBNB → 15 BNB; a fixed rate in QuoteRegistry; else --ref-pool prices the target
429
+ // the target: --grad (2.0, createWithGradTarget) or the pad's default (create: 9 BNB on 2.0, 15 on 1.0)
430
+ const targetBnb = grad ?? bnbOf(await ctx.read(ctx.pad, GRAD_TARGET_ABI, 'TARGET_GRAD_BNB'))
431
+ // the target in the quote: WBNB as is; a fixed rate in QuoteRegistry; else --ref-pool prices it. On 2.0 it is read
432
+ // with graduationAmountFor for the very target the create takes, so GradAmtTooSmall / QuoteAmountTooLarge show here
390
433
  let gradAmt
391
- try { gradAmt = await ctx.read(ctx.pad, PAD_ABI, 'graduationAmountOf', [quote, refPool]) } catch (e) {
434
+ try {
435
+ gradAmt = tiers ? await ctx.read(ctx.pad, GRAD_TARGET_ABI, 'graduationAmountFor', [quote, refPool, parseUnits(String(targetBnb), 18)])
436
+ : await ctx.read(ctx.pad, PAD_ABI, 'graduationAmountOf', [quote, refPool])
437
+ } catch (e) {
392
438
  return fail('cannot price the graduation target in this quote', revertOf(e) || { detail: e.shortMessage || e.message })
393
439
  }
394
- const createData = (logoURI, metaURI) =>
395
- encodeFunctionData({ abi: PAD_ABI, functionName: 'create', args: [name, symbol, logoURI, metaURI, quote, refPool, tax] })
440
+ const fn = grad !== null ? 'createWithGradTarget' : 'create'
441
+ const argsOf = (logoURI, metaURI) => [name, symbol, logoURI, metaURI, quote, refPool, tax, ...(grad !== null ? [parseUnits(String(grad), 18)] : [])]
442
+ const createData = (logoURI, metaURI) => encodeFunctionData({ abi: PAD_ABI, functionName: fn, args: argsOf(logoURI, metaURI) })
396
443
  // the logo / metadata strings never decide a revert: dry-run without them, so a create that would fail uploads nothing
397
- const dry = await simulate(ctx, me, ctx.pad, PAD_ABI, 'create', [name, symbol, '', '', quote, refPool, tax])
444
+ const dry = await simulate(ctx, me, ctx.pad, PAD_ABI, fn, argsOf('', ''))
398
445
  if (dry.failed) return out({ success: false, step: 'create', ...dry.failed })
399
446
  const logo = await resolveLogo()
400
447
  const meta = await resolveMeta({ name, symbol, logoURI: logo.logoURI })
@@ -405,10 +452,12 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
405
452
  }
406
453
  const rest = 100 - dividend
407
454
  const fees = await feesOf(ctx)
455
+ const creatorFee = await createNote(ctx, net)
408
456
  return out(notes.step(ctx, { from: me, to: ctx.pad, data: createData(logo.logoURI, meta.metaURI) }, {
409
457
  step: 'create', chainId: Number(ctx.chainId), name, symbol, logoURI: logo.logoURI, ...(logo.uploaded && { uploaded: true }),
410
458
  metaURI: meta.metaURI, metadata: meta.metadata,
411
- quote: (await symbolOf(ctx, quote)) || quote, graduationAt: await units(ctx, quote, gradAmt),
459
+ quote: (await symbolOf(ctx, quote)) || quote, graduationTargetBnb: targetBnb, graduationAt: await units(ctx, quote, gradAmt),
460
+ graduation: `${gradLine(targetBnb, quote.toLowerCase() === String(ctx.wbnb).toLowerCase() ? null : `${await units(ctx, quote, gradAmt)} ${(await symbolOf(ctx, quote)) || 'of the quote'}`)}${tiers ? `; ${grad !== null ? 'picked with --grad' : 'the default'}, --grad picks ${tiers.join(' / ')}` : ''}`,
412
461
  ...(refPool !== zeroAddress && quote.toLowerCase() !== String(ctx.wbnb).toLowerCase() && { refPool }),
413
462
  buyTaxPct: buyTax, sellTaxPct: sellTax, dividendPct: dividend,
414
463
  recipient: recipient === zeroAddress ? null : recipient, recipientLabel: selfRecipient ? 'you (the creator)' : label, tokenIfNext: dry.result,
@@ -416,6 +465,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
416
465
  ? `of each ${buyTax}% buy / ${sellTax}% sell tax in the PancakeSwap pool (after graduation; the curve charges no tax): ${fees.platformTaxPct}% of volume to the platform, then ${dividend}% of the rest to holders, ${rest}% to the recipient in the quote`
417
466
  + (dividend > 0 ? '; if no holder has 10,000+ tokens when a tax is paid, the holders\' part goes to the recipient too' : '')
418
467
  : 'untaxed: no tax in the PancakeSwap pool after graduation, no dividend, no recipient',
468
+ ...(creatorFee && { creatorFee }),
419
469
  note: `${taxed ? 'tax rates and recipient are' : 'untaxed is'} fixed at create. Curve trades pay only the ${fees.curveFeePct}% fee, no tax${taxed ? ': the tax starts in the pool after graduation' : ''}. tokenIfNext changes if another create lands first: the real address is the Created event from \`gang tx --hash …\`.`,
420
470
  }, 'create'))
421
471
  }
@@ -439,17 +489,28 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
439
489
  }
440
490
  const me = walletFor(ctx, opt('from'))
441
491
  if (!(await ctx.read(ctx.pad, PAD_ABI, 'isAgent', [me]))) fail('this wallet holds no Agent ID; curve trades are Agent-only', { wallet: me })
442
- if ((await ctx.read(ctx.pad, PAD_ABI, 'walletRoom', [token, me])) === 0n) fail(HINTS.WalletCapReached)
492
+ const room = await ctx.read(ctx.pad, PAD_ABI, 'walletRoom', [token, me])
493
+ if (room === 0n) fail(HINTS.WalletCapReached)
443
494
  if (!flag('amount') && !flag('bnb')) fail('--amount <quote to spend> required (the 1% curve fee included; no tax on the curve)')
444
495
  const raw = parseAmount(fail, flag('amount') ? 'amount' : 'bnb', opt('amount') ?? opt('bnb'))
445
496
  const quoteIn = parseUnits(raw, await decimalsOf(ctx, c.quote))
446
497
  const slippage = parseSlippage(fail, opt('slippage', '1'))
447
498
  // asked from gang.fun before any wrap / approve round, so a follow that can't count fails first
448
499
  const follow = await notes.follow(token, me)
449
- const priced = async (tokensOut) => follow && notes.priced(follow, token, await spentFor(ctx, c, quoteIn, tokensOut), await decimalsOf(ctx, c.quote))
450
- const extra = (tokensOut, minOut) => ({
500
+ const priced = async (tokensOut) => follow && notes.priced(follow, token, (await spentFor(ctx, c, quoteIn, tokensOut, room)).spent, await decimalsOf(ctx, c.quote))
501
+ // the pad trims a buy past the token's own graduation amount or the wallet cap and refunds the rest: say what it spends
502
+ const cutOf = async (tokensOut, refundAs) => {
503
+ const { spent, cut } = await spentFor(ctx, c, quoteIn, tokensOut, room)
504
+ if (!cut) return {}
505
+ const [s, r] = await Promise.all([units(ctx, c.quote, spent), units(ctx, c.quote, quoteIn - spent)])
506
+ const why = cut === 'graduation'
507
+ ? `only ${c.toGraduation} ${c.quoteSymbol} is left to raise before this token graduates at ${c.graduationAt} ${c.quoteSymbol}`
508
+ : `the 1% wallet cap leaves this wallet room for ${formatUnits(tokensOut, 18)} more tokens only`
509
+ return { spent: s, refund: r, cutBy: cut, cutNote: `${why}: the buy spends ${s} ${c.quoteSymbol} (fee included) and refunds ${r} ${refundAs}` }
510
+ }
511
+ const extra = async (tokensOut, minOut, refundAs = c.quoteSymbol) => ({
451
512
  step: 'buy', chainId: Number(ctx.chainId), token, spend: raw, quote: c.quoteSymbol, expectTokens: formatUnits(tokensOut, 18),
452
- minTokensOut: formatUnits(minOut, 18), curveTaxPct: 0, ...(c.buyTaxPct > 0 && { poolBuyTaxPct: c.buyTaxPct }),
513
+ minTokensOut: formatUnits(minOut, 18), ...(await cutOf(tokensOut, refundAs)), curveTaxPct: 0, ...(c.buyTaxPct > 0 && { poolBuyTaxPct: c.buyTaxPct }),
453
514
  })
454
515
  // WBNB-quoted: pay native BNB through the router in one tx (it wraps; tokens land in this wallet; a cap / graduation
455
516
  // refund comes back from the pad to this wallet as WBNB, not BNB)
@@ -465,7 +526,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
465
526
  const minOut = minOf(sim.result, slippage)
466
527
  const data = encodeFunctionData({ abi: GANG_ROUTER_ABI, functionName: 'v3BuyBNB', args: [token, minOut, routerDeadline()] })
467
528
  return out(notes.step(ctx, { from: me, to: ctx.router, data, value: quoteIn }, {
468
- ...extra(sim.result, minOut), via: 'router', curveFeePct: (await feesOf(ctx)).curveFeePct,
529
+ ...(await extra(sim.result, minOut, 'WBNB (not BNB)')), via: 'router', curveFeePct: (await feesOf(ctx)).curveFeePct,
469
530
  note: 'paid in BNB through GangRouter; spend includes the 1% curve fee (no tax on the curve; the buy tax applies only in the pool after graduation); at the 1% wallet cap or the graduation cut the excess comes back to this wallet as WBNB (not BNB)',
470
531
  }, 'buy', await priced(sim.result)))
471
532
  }
@@ -475,7 +536,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
475
536
  if (sim.failed) return out({ success: false, step: 'buy', ...sim.failed })
476
537
  const minOut = minOf(sim.result, slippage)
477
538
  return out(notes.step(ctx, { from: me, to: ctx.pad, data: encodeFunctionData({ abi: PAD_ABI, functionName: 'buy', args: [token, quoteIn, minOut] }) }, {
478
- ...extra(sim.result, minOut), curveFeePct: (await feesOf(ctx)).curveFeePct,
539
+ ...(await extra(sim.result, minOut)), curveFeePct: (await feesOf(ctx)).curveFeePct,
479
540
  note: 'spend includes the 1% curve fee (no tax on the curve; the buy tax applies only in the pool after graduation); at the 1% wallet cap the excess is refunded',
480
541
  }, 'buy', await priced(sim.result)))
481
542
  }
@@ -556,7 +617,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
556
617
  const r = await ctx.client.waitForTransactionReceipt({ hash, timeout: 120_000 })
557
618
  const events = []
558
619
  for (const log of r.logs) {
559
- for (const abi of [PAD_ABI, TAX_ROUTER_ABI, VAULT_ABI]) {
620
+ for (const abi of V3_EVENT_ABIS) {
560
621
  try {
561
622
  const ev = decodeEventLog({ abi, data: log.data, topics: log.topics })
562
623
  events.push({ event: ev.eventName, ...Object.fromEntries(Object.entries(ev.args).map(([k, v]) => [k, typeof v === 'bigint' ? v.toString() : v])) })