@gangfun/cli 0.33.0 → 0.34.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
@@ -5,6 +5,7 @@ import { UA } from './version.js'
5
5
  import { walletFor } from './fair.js'
6
6
  import { atTokenPad, CREATOR_FEE_ABI, genFields, GRAD_TARGET_ABI, gradTargetBnbOf, gradTiersOf, KIND_UNREAD, MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, PAD3_GEN, padNets, rpcTransport, tokenVaultOf, VAULT_GEN, VAULT_NO_BOND, vaultGenOf, vaultModeOf } from './gangpad.js'
7
7
  import { createNote, curveCreatorFee } from './creatorfee.js'
8
+ import { checkPromoter, DEFAULT_WINDOW_DAYS, firstBuyWarning, isMissingRead, HINTS as PROMOTE_HINTS, parsePromote, poolFactoryAddress, poolOf, promoteField, promoteLine, PROMOTE_PAD_ABI } from './promote.js'
8
9
  import { poolPayBnb, poolTrade } from './pool.js'
9
10
  import { bondGuard } from './bond.js'
10
11
  import { splitterOf } from './buyback.js'
@@ -27,6 +28,7 @@ const PAD_ABI = parseAbi([
27
28
  `function createWithGradTarget(string name, string symbol, string logoURI, string metaURI, address quote, address refPool, ${TAX} tax, uint256 gradBnb) returns (address)`,
28
29
  // 2.0 金库版 (GangVaultLaunchpad): its only create, binding the token to a listed vault for good; 3.0 has the same once
29
30
  // an upgrade added its vault mode (vaultModeOf), beside its other creates
31
+ `function createWithPromote(string name, string symbol, string logoURI, string metaURI, address quote, address refPool, ${TAX} tax, uint256 gradBnb, uint16 shareBps, uint32 window) returns (address)`,
30
32
  `function createWithVault(string name, string symbol, string logoURI, string metaURI, address quote, address refPool, ${TAX} tax, uint256 gradBnb, address vault) returns (address)`,
31
33
  'function isVault(address vault) view returns (bool)',
32
34
  'function vaultOf(address token) view returns (address)',
@@ -156,7 +158,7 @@ const VIRTUAL_TOKEN = 1_066_666_666_666_666_666_666_666_667n
156
158
  const ceilDiv = (a, b) => (a + b - 1n) / b
157
159
 
158
160
  /** Revert name (+ BadTaxConfig reason) of a failed call, or null when it was the RPC. */
159
- 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 })
161
+ const revertOf = (e) => revertIn(e, [PAD_ABI, PROMOTE_PAD_ABI, CREATOR_FEE_ABI, GRAD_TARGET_ABI, TAX_ROUTER_ABI, GANG_ROUTER_ABI, MERGED_ERRORS_ABI], { BadPromoteTerms: PROMOTE_HINTS.BadPromoteTerms, TraderNotOrigin: PROMOTE_HINTS.TraderNotOrigin, ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
160
162
 
161
163
  /** eth_call `data` from `from`: { result } when it passes, { failed } with the revert (or RPC error) otherwise. */
162
164
  async function simulate(ctx, from, to, abi, functionName, args, value = 0n) {
@@ -298,7 +300,7 @@ const USAGE = 'usage: gang v3 <list|info|status|create|buy|sell|claim|income|rel
298
300
  * Entry for `gang v3 <sub>`. io: { opt, flag, out, fail, summarize, resolveLogo, checkMeta, resolveMeta, notes } from
299
301
  * index.js (summarize = summarizePreview, so previews look like every other command's; notes = padNotes: --note / --follow).
300
302
  */
301
- export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo, checkMeta, resolveMeta, notes }) {
303
+ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo, checkMeta, resolveMeta, notes, launchPoolModule = null }) {
302
304
  if (!SUBS.includes(sub)) return fail(USAGE, { got: sub ?? null })
303
305
  const testnet = flag('testnet')
304
306
  const net = testnet ? ' --testnet' : ''
@@ -372,13 +374,14 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
372
374
  // 2.0: the creator's part of the curve fee, waiting on the pad
373
375
  const gen = await curveCreatorFee(ctx, token, c, net)
374
376
  const vault = await vaultView(ctx, token, c, net)
377
+ const promote = await promoteField(ctx, token, { recipient: c.recipient, dividendPct: c.dividendPct, testnet })
375
378
  // 3.0: the rule set the token was created under (fixed for good; an upgrade adds rules for new tokens only)
376
379
  const tokenVersion = ctx.gen === PAD3_GEN ? await ctx.read(ctx.pad, PAD_ABI, 'tokenVersionOf', [token]).then(Number).catch(() => null) : null
377
380
  const nonWbnb = c.quote.toLowerCase() !== String(ctx.wbnb).toLowerCase()
378
381
  const graduationNote = c.graduationTargetBnb != null && !c.graduated
379
382
  ? gradLine(c.graduationTargetBnb, nonWbnb ? `${c.graduationAt} ${c.quoteSymbol || 'of the quote'}` : null) : null
380
383
  return out({
381
- success: true, chainId: Number(ctx.chainId), ...fees, ...pub, ...gen, ...(tokenVersion != null && { tokenVersion }), ...(vault && { vault }), ...(graduationNote && { graduationNote }), taxNote, ...(swapBack && { swapBack }), ...(buyback && { buyback }),
384
+ success: true, chainId: Number(ctx.chainId), ...fees, ...pub, ...gen, ...(promote && { promote }), ...(tokenVersion != null && { tokenVersion }), ...(vault && { vault }), ...(graduationNote && { graduationNote }), taxNote, ...(swapBack && { swapBack }), ...(buyback && { buyback }),
382
385
  ...(split && { split: { ...split, ...splitWarn } }), ...(lp && { lp: { ...lp, ...lpWarn } }),
383
386
  ...(combo && { combo: { ...combo, ...(comboWarning && { warning: comboWarning }) } }),
384
387
  })
@@ -396,11 +399,12 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
396
399
  const q = c.graduated && c.pair && bal > 0n ? await poolSellQuote(ctx, c.taxHandler, token, bal) : null
397
400
  // the creator's own view also shows its creator fee (2.0)
398
401
  const { creatorFee } = me.toLowerCase() === c.creator.toLowerCase() ? await curveCreatorFee(ctx, token, c, net) : {}
402
+ const promote = await promoteField(ctx, token, { recipient: c.recipient, dividendPct: c.dividendPct, testnet })
399
403
  // a token with a vault (2.0 金库版, 3.0 --vault), before graduation: what this wallet has in it, counted in its 1% cap
400
404
  const locked = !c.graduated && (await vaultOfToken(ctx, token).catch(() => null)) ? await ctx.read(ctx.pad, PAD_ABI, 'lockedOf', [token, me]) : null
401
405
  return out({
402
406
  success: true, chainId: Number(ctx.chainId), wallet: me, token, quote: c.quoteSymbol, graduated: c.graduated,
403
- balance: formatUnits(bal, 18), ...(locked !== null && { lockedInVault: formatUnits(locked, 18) }), dividendPct: c.dividendPct, ...(creatorFee && { creatorFee }),
407
+ balance: formatUnits(bal, 18), ...(locked !== null && { lockedInVault: formatUnits(locked, 18) }), dividendPct: c.dividendPct, ...(creatorFee && { creatorFee }), ...(promote && { promote }),
404
408
  graduationTargetBnb: c.graduationTargetBnb, graduationAt: c.graduationAt, progressPct: c.progressPct,
405
409
  ...(q && {
406
410
  poolSellAll: {
@@ -459,6 +463,14 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
459
463
  const vault = flag('vault') ? addrArg(opt, fail, 'vault', 'the vault gang listed for your token') : null
460
464
  // --grad: the graduation target in BNB raised, one of the pad's GRAD_BNB_TIERS (2.0); left out: the pad's default
461
465
  const grad = flag('grad') ? Number(opt('grad')) : null
466
+ // --promote: a promoter's share of the creator fee, for a window, fixed for good (createWithPromote, 3.0 once upgraded)
467
+ if (flag('promote-days') && !flag('promote')) fail('--promote-days goes with --promote <pct>')
468
+ const promote = flag('promote') ? parsePromote(opt('promote'), opt('promote-days')) : null
469
+ if (promote?.error) {
470
+ const { error, ...extra } = promote
471
+ fail(error, extra)
472
+ }
473
+ if (promote && vault) fail('--promote and --vault can\'t go together: a token is made with one or the other')
462
474
  if (grad !== null && !(grad > 0)) fail('--grad must be the graduation target in BNB raised: 6, 9, 12 or 15', { got: opt('grad') ?? null })
463
475
  const buyTax = taxed ? taxOf('buy-tax') : 0
464
476
  const sellTax = taxed ? taxOf('sell-tax') : 0
@@ -492,6 +504,13 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
492
504
  // partner, or yourself), else the creator itself
493
505
  const recipient = !taxed || (dividend === 100 && !flag('recipient')) ? zeroAddress
494
506
  : flag('recipient') ? addrArg(opt, fail, 'recipient', 'the tax recipient: your own address, or a whitelisted partner') : me
507
+ // a promoter pool module pays only when the launch that cloned it binds it, and pays its own dev: never one typed here
508
+ const typedPool = recipient !== zeroAddress && !(launchPoolModule && recipient.toLowerCase() === launchPoolModule.toLowerCase())
509
+ ? await poolOf(ctx.read, (a) => ctx.client.getCode({ address: a }), recipient, poolFactoryAddress(testnet)).catch((e) => fail('could not check --recipient (RPC error)', { detail: e.shortMessage || e.message.split('\n')[0], retry: 'same command again' }))
510
+ : null
511
+ if (typedPool) {
512
+ fail('--recipient is a promoter pool module: a token can\'t name one by hand. Leave --recipient out and add --promote: the launch clones yours and binds it', { recipient })
513
+ }
495
514
  const quote = flag('quote') ? opt('quote') : ctx.wbnb
496
515
  const refPool = flag('ref-pool') ? opt('ref-pool') : (defaultRefPool(ctx.chainId, quote) ?? zeroAddress)
497
516
  if (!isAddress(quote ?? '') || !isAddress(refPool ?? '')) fail('--quote / --ref-pool must be 0x addresses')
@@ -520,10 +539,16 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
520
539
  } catch (e) {
521
540
  return fail('cannot price the graduation target in this quote', revertOf(e) || { detail: e.shortMessage || e.message })
522
541
  }
523
- // createWithVault always takes the target (the pad's default when --grad is left out)
524
- const fn = vault ? 'createWithVault' : grad !== null ? 'createWithGradTarget' : 'create'
542
+ if (promote) {
543
+ try { await ctx.read(ctx.pad, PROMOTE_PAD_ABI, 'promoteOf', [zeroAddress]) } catch (e) {
544
+ if (!isMissingRead(e)) fail('could not check the pad for a promoter share (RPC error)', { pad: ctx.pad, retry: 'same command again' })
545
+ fail(`GangLaunchpad ${ctx.gen ?? ctx.pad} has no promoter share yet: drop --promote`, { pad: ctx.pad })
546
+ }
547
+ }
548
+ // createWithVault and createWithPromote always take the target (the pad's default when --grad is left out)
549
+ const fn = vault ? 'createWithVault' : promote ? 'createWithPromote' : grad !== null ? 'createWithGradTarget' : 'create'
525
550
  const argsOf = (logoURI, metaURI) => [name, symbol, logoURI, metaURI, quote, refPool, tax,
526
- ...(vault ? [parseUnits(String(targetBnb), 18), vault] : grad !== null ? [parseUnits(String(grad), 18)] : [])]
551
+ ...(vault ? [parseUnits(String(targetBnb), 18), vault] : promote ? [parseUnits(String(targetBnb), 18), promote.shareBps, promote.window] : grad !== null ? [parseUnits(String(grad), 18)] : [])]
527
552
  const createData = (logoURI, metaURI) => encodeFunctionData({ abi: PAD_ABI, functionName: fn, args: argsOf(logoURI, metaURI) })
528
553
  // the logo / metadata strings never decide a revert: dry-run without them, so a create that would fail uploads nothing
529
554
  const dry = await simulate(ctx, me, ctx.pad, PAD_ABI, fn, argsOf('', ''))
@@ -537,7 +562,9 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
537
562
  }
538
563
  const rest = 100 - dividend
539
564
  const fees = await feesOf(ctx)
540
- const creatorFee = await createNote(ctx, net)
565
+ const baseCreatorFee = await createNote(ctx, net)
566
+ const creatorFee = baseCreatorFee && promote ? `${baseCreatorFee} Less the ${promote.shareBps / 100}% of it you give promoters on their bound wallets' trades.` : baseCreatorFee
567
+ const poolModule = promote && !!launchPoolModule
541
568
  return out(notes.step(ctx, { from: me, to: ctx.pad, data: createData(logo.logoURI, meta.metaURI) }, {
542
569
  step: 'create', chainId: Number(ctx.chainId), name, symbol, logoURI: logo.logoURI, ...(logo.uploaded && { uploaded: true }),
543
570
  metaURI: meta.metaURI, metadata: meta.metadata,
@@ -551,6 +578,14 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
551
578
  + (dividend > 0 ? '; if no holder has 10,000+ tokens when a tax is paid, the holders\' part goes to the recipient too' : '')
552
579
  : 'untaxed: no tax in the PancakeSwap pool after graduation, no dividend, no recipient',
553
580
  ...(creatorFee && { creatorFee }),
581
+ ...(promote && {
582
+ promote: {
583
+ sharePct: promote.shareBps / 100, windowDays: promote.windowDays,
584
+ ...(!flag('promote-days') && { defaultWindow: `--promote-days left out: ${DEFAULT_WINDOW_DAYS} days` }),
585
+ poolShare: poolModule,
586
+ note: promoteLine({ shareBps: promote.shareBps, windowDays: promote.windowDays, pool: poolModule, taxed, dividendPct: dividend }),
587
+ },
588
+ }),
554
589
  ...(vault && {
555
590
  padGen: ctx.gen, pad: ctx.pad, vault,
556
591
  vaultNote: 'the token is bound to this vault for good. Until graduation the token moves only through the pad: the vault locks a holder\'s tokens (counted in that holder\'s 1% cap) and releases them through the pad, for the holder that sends the tx and holds an Agent ID; after graduation it is a plain token. This create uses up the wallet\'s naming for the vault: one token per naming. A vault-bound token takes no GangBond (gang bond post refuses it): a lock moves tokens out of the creator\'s wallet, which would forfeit a bond',
@@ -567,6 +602,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
567
602
  // graduated: buy in the PancakeSwap pool through GangRouter (the buy tax applies; no Agent gate, no wallet cap)
568
603
  if (!c.pair) return fail('the pad marks this token graduated but has no PancakeSwap pair on record: nothing to trade it on', { token })
569
604
  if (notes.following) fail('--follow only counts on curve buys before graduation; this token trades on PancakeSwap now', { pair: c.pair })
605
+ if (flag('promoter')) fail('--promoter binds on the curve only, and this token has graduated: on a token with a pool share, a wallet bound on the curve keeps counting for its promoter here, inside its window', { token })
570
606
  if (!flag('amount') && !flag('bnb')) fail('--amount <quote (or BNB) to spend> required')
571
607
  const raw = parseAmount(fail, flag('amount') ? 'amount' : 'bnb', opt('amount') ?? opt('bnb'))
572
608
  return out(await poolTrade(ctx, {
@@ -601,8 +637,38 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
601
637
  step: 'buy', chainId: Number(ctx.chainId), token, spend: raw, quote: c.quoteSymbol, expectTokens: formatUnits(tokensOut, 18),
602
638
  minTokensOut: formatUnits(minOut, 18), ...(await cutOf(tokensOut, refundAs)), curveTaxPct: 0, ...(c.buyTaxPct > 0 && { poolBuyTaxPct: c.buyTaxPct }),
603
639
  })
640
+ // --promoter: the wallet's first buy, sent directly to the pad (buyWithPromoter refuses any contract, the router too)
641
+ if (flag('promoter')) {
642
+ const raw_ = opt('promoter')
643
+ if (!isAddress(raw_ ?? '') || raw_ === zeroAddress) fail('--promoter must be the promoter\'s 0x address', { got: raw_ ?? null })
644
+ const bind = await checkPromoter(ctx, { token, me, raw: raw_, creator: c.creator })
645
+ if (bind.refuse) fail(bind.refuse, { token, promoter: bind.promoter, ...(bind.retry && { retry: bind.retry }) })
646
+ const wbnbQuoted = c.quote.toLowerCase() === String(ctx.wbnb).toLowerCase()
647
+ if (wbnbQuoted && flag('use-wbnb')) fail('--use-wbnb can\'t go with --promoter: a WBNB-quoted buy naming a promoter pays native BNB')
648
+ if (wbnbQuoted) {
649
+ const native = await ctx.client.getBalance({ address: me })
650
+ if (native < quoteIn + GAS_RESERVE) {
651
+ fail('not enough BNB for this buy (native BNB must also cover gas)', { haveBnb: formatUnits(native, 18), needBnb: raw, reserveForGas: formatUnits(GAS_RESERVE, 18) })
652
+ }
653
+ } else {
654
+ const pre = await fundingStep(ctx, me, c.quote, quoteIn, c.quoteSymbol, 'approve-quote', rawOnly, summarize)
655
+ if (pre) return out(pre.success ? { ...pre, ...notes.skipped(follow) } : pre)
656
+ }
657
+ const value = wbnbQuoted ? quoteIn : 0n
658
+ const sim = await simulate(ctx, me, ctx.pad, PROMOTE_PAD_ABI, 'buyWithPromoter', [token, quoteIn, 0n, bind.promoter], value)
659
+ if (sim.failed) return out({ success: false, step: 'buy', ...sim.failed })
660
+ const [tokensOut] = sim.result
661
+ const minOut = minOf(tokensOut, slippage)
662
+ const data = encodeFunctionData({ abi: PROMOTE_PAD_ABI, functionName: 'buyWithPromoter', args: [token, quoteIn, minOut, bind.promoter] })
663
+ return out(notes.step(ctx, { from: me, to: ctx.pad, data, ...(value > 0n && { value }) }, {
664
+ ...(await extra(tokensOut, minOut, wbnbQuoted ? 'WBNB (not BNB)' : c.quoteSymbol)), curveFeePct: (await feesOf(ctx)).curveFeePct, promoter: bind.promoter,
665
+ note: 'binds this wallet to the promoter for good, by its first trade of this token, sent directly from the wallet. You pay the same price and fee: the promoter\'s part comes out of the creator\'s fee, and after graduation, on a token with a pool share and inside the window, out of the tax recipient\'s part. Pool trades count only if this wallet itself moves the tokens or calls a listed router directly: tokens moved to another address first, or sold through an unlisted contract, don\'t',
666
+ }, 'buy', await priced(tokensOut)))
667
+ }
604
668
  // WBNB-quoted: pay native BNB through the router in one tx (it wraps; tokens land in this wallet; a cap / graduation
605
669
  // refund comes back from the pad to this wallet as WBNB, not BNB)
670
+ const bindWarning = await firstBuyWarning(ctx, token, me)
671
+ const warned = bindWarning ? { promoteWarning: bindWarning } : {}
606
672
  if (viaRouter(ctx, c.quote, flag)) {
607
673
  const native = await ctx.client.getBalance({ address: me })
608
674
  if (native < quoteIn + GAS_RESERVE) {
@@ -615,7 +681,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
615
681
  const minOut = minOf(sim.result, slippage)
616
682
  const data = encodeFunctionData({ abi: GANG_ROUTER_ABI, functionName: 'v3BuyBNB', args: [token, minOut, routerDeadline()] })
617
683
  return out(notes.step(ctx, { from: me, to: ctx.router, data, value: quoteIn }, {
618
- ...(await extra(sim.result, minOut, 'WBNB (not BNB)')), via: 'router', curveFeePct: (await feesOf(ctx)).curveFeePct,
684
+ ...(await extra(sim.result, minOut, 'WBNB (not BNB)')), via: 'router', curveFeePct: (await feesOf(ctx)).curveFeePct, ...warned,
619
685
  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)',
620
686
  }, 'buy', await priced(sim.result)))
621
687
  }
@@ -625,7 +691,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
625
691
  if (sim.failed) return out({ success: false, step: 'buy', ...sim.failed })
626
692
  const minOut = minOf(sim.result, slippage)
627
693
  return out(notes.step(ctx, { from: me, to: ctx.pad, data: encodeFunctionData({ abi: PAD_ABI, functionName: 'buy', args: [token, quoteIn, minOut] }) }, {
628
- ...(await extra(sim.result, minOut)), curveFeePct: (await feesOf(ctx)).curveFeePct,
694
+ ...(await extra(sim.result, minOut)), curveFeePct: (await feesOf(ctx)).curveFeePct, ...warned,
629
695
  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',
630
696
  }, 'buy', await priced(sim.result)))
631
697
  }