@gangfun/cli 0.37.0 → 0.39.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
@@ -14,6 +14,8 @@ import { splitOf } from './split.js'
14
14
  import { lpOf } from './lp.js'
15
15
  import { comboOf, decoyWarning } from './combo.js'
16
16
  import { cappedOf, decoyWarning as cappedDecoyWarning } from './capped.js'
17
+ import { floorFactoryAddress, floorOf, floorShown, treasuryShare, typedFloorModule } from './floor.js'
18
+ import { VANITY_ABI, vanityCreate, vanityDeployer } from './vanity.js'
17
19
 
18
20
  /**
19
21
  * `gang v3 …` — LaunchpadV3 (tax recipient): a token with its own buy / sell tax (1–5% each), a dividend share and a
@@ -160,7 +162,7 @@ const VIRTUAL_TOKEN = 1_066_666_666_666_666_666_666_666_667n
160
162
  const ceilDiv = (a, b) => (a + b - 1n) / b
161
163
 
162
164
  /** Revert name (+ BadTaxConfig reason) of a failed call, or null when it was the RPC. */
163
- 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 })
165
+ const revertOf = (e) => revertIn(e, [PAD_ABI, VANITY_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 })
164
166
 
165
167
  /** eth_call `data` from `from`: { result } when it passes, { failed } with the revert (or RPC error) otherwise. */
166
168
  async function simulate(ctx, from, to, abi, functionName, args, value = 0n) {
@@ -190,8 +192,12 @@ async function taxContracts(ctx) {
190
192
  return ctx._tax
191
193
  }
192
194
 
193
- /** The call hit a contract without this function: a bare revert (no error data) or an empty return. */
195
+ /**
196
+ * The call hit a contract without this function: a bare revert (no error data) or an empty return. A node's internal
197
+ * error (-32603) also comes back from viem as a revert: it is the node's, never "no such function" (as gangpad.js).
198
+ */
194
199
  function noSuchFunction(e) {
200
+ if (e?.walk?.((x) => x?.code === -32603)) return false
195
201
  if (e?.walk?.((x) => x?.name === 'ContractFunctionZeroDataError')) return true
196
202
  const r = e?.walk?.((x) => x?.name === 'ContractFunctionRevertedError')
197
203
  return !!r && !r.data && (!r.raw || r.raw === '0x')
@@ -302,7 +308,7 @@ const USAGE = 'usage: gang v3 <list|info|status|create|buy|sell|claim|income|rel
302
308
  * Entry for `gang v3 <sub>`. io: { opt, flag, out, fail, summarize, resolveLogo, checkMeta, resolveMeta, notes } from
303
309
  * index.js (summarize = summarizePreview, so previews look like every other command's; notes = padNotes: --note / --follow).
304
310
  */
305
- export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo, checkMeta, resolveMeta, notes, launchPoolModule = null }) {
311
+ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo, checkMeta, resolveMeta, notes, launchPoolModule = null, launchFloor = null }) {
306
312
  if (!SUBS.includes(sub)) return fail(USAGE, { got: sub ?? null })
307
313
  const testnet = flag('testnet')
308
314
  const net = testnet ? ' --testnet' : ''
@@ -373,6 +379,16 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
373
379
  const capped = c.recipient && !c.recipientIsCreator && !buyback && !split && !lp && !combo
374
380
  ? await cappedOf(ctx.read, c.recipient, { wbnb: ctx.wbnb, pad: ctx.pad, extraAssets: [c.quote], ref: comboRef }) : null
375
381
  const cappedWarning = capped ? cappedDecoyWarning(capped, token, c.quote, comboRef) : null
382
+ // or the dev's floor module (floor-v1): the tax kept as a treasury holders can redeem. Only one GangFloorModuleFactory
383
+ // made, cloned for this very token, is this token's floor: anything else is shown with a warning, never as one
384
+ const floorRaw = c.recipient && !c.recipientIsCreator && !buyback && !split && !lp && !combo && !capped
385
+ ? await floorOf(ctx.read, c.recipient, { wbnb: ctx.wbnb, pad: ctx.pad, factory: ctx.floorFactory, extraAssets: [c.quote], ref: comboRef, getCode: (a) => ctx.client.getCode({ address: a }) }) : null
386
+ // not this token's floor (not made by the factory, unchecked, or cloned for another token): only the warning, no numbers
387
+ const floorSeen = floorRaw ? floorShown(floorRaw, token) : null
388
+ const floor = floorRaw && (floorSeen !== floorRaw ? floorSeen : {
389
+ ...floorRaw,
390
+ treasuryGets: treasuryShare({ buyTaxPct: c.buyTaxPct, sellTaxPct: c.sellTaxPct, platformTaxPct: fees.platformTaxPct, dividendPct: c.dividendPct, payBps: floorRaw.cap?.reached ? 0 : floorRaw.payBps }),
391
+ })
376
392
  const lpWarn = lp && lp.token && lp.token.toLowerCase() !== token.toLowerCase()
377
393
  ? { 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
378
394
  const splitWarn = split && split.token && split.token.toLowerCase() !== token.toLowerCase()
@@ -391,6 +407,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
391
407
  ...(split && { split: { ...split, ...splitWarn } }), ...(lp && { lp: { ...lp, ...lpWarn } }),
392
408
  ...(combo && { combo: { ...combo, ...(comboWarning && { warning: comboWarning }) } }),
393
409
  ...(capped && { capped: { ...capped, ...(cappedWarning && { warning: cappedWarning }) } }),
410
+ ...(floor && { floor }),
394
411
  })
395
412
  }
396
413
 
@@ -534,6 +551,21 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
534
551
  return ctx.read(ctx.pad, PAD_ABI, 'checkTaxConfig', [tax])
535
552
  })
536
553
  if (!ok) fail(`tax setting refused: ${reason}`, { hint: HINTS.BadTaxConfig, tax: { buyTax, sellTax, dividend, recipient } })
554
+ // a floor module serves the one token address it was cloned for: a token that names one by hand lands elsewhere, and
555
+ // its tax goes into a module that can never bind it — for good. Only the launch that cloned it for this very token
556
+ // names it. Checked on the chain's own records, at one block, and nothing is built on an answer that is not sure
557
+ if (recipient !== zeroAddress && !launchFloor && recipient.toLowerCase() !== String(me).toLowerCase()) {
558
+ // the floor factory of the create target's generation, even when --vault moved ctx to the vault pad (whose own
559
+ // generation has none: its handler lists no floor module, so nothing matches there)
560
+ const typed = await typedFloorModule({ client: ctx.client, pad: ctx.pad }, recipient, floorFactoryAddress(testnet))
561
+ if (typed.floor) {
562
+ fail('--recipient is a floor module: a token can\'t name one by hand. A floor module serves only the token address it was cloned for, so this token\'s tax would go into a module that can never bind it, and the token would have no floor. Leave --recipient out and add --floor: the launch clones a module for this token', { recipient, seenBy: typed.by })
563
+ }
564
+ // the pad just took this recipient, so it is listed: a node that says otherwise is behind (or the two answers are
565
+ // of different blocks). Not sure → nothing is built
566
+ if (typed.unlisted) fail('could not check --recipient: the pad accepts it, but the tax handler did not show it as listed at the block it was checked on (a node may be behind)', { recipient, retry: 'same command again' })
567
+ if (typed.unread) fail('could not check --recipient (RPC error)', { detail: typed.unread, retry: 'same command again' })
568
+ }
537
569
  if (!(await ctx.read(ctx.pad, PAD_ABI, 'isAgent', [me]))) fail('this wallet holds no Agent ID; V3 create is Agent-only', { wallet: me })
538
570
  // the target: --grad (2.0, createWithGradTarget) or the pad's default (create: 9 BNB on 2.0, 15 on 1.0)
539
571
  const targetBnb = grad ?? bnbOf(await ctx.read(ctx.pad, GRAD_TARGET_ABI, 'TARGET_GRAD_BNB'))
@@ -557,11 +589,36 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
557
589
  const argsOf = (logoURI, metaURI) => [name, symbol, logoURI, metaURI, quote, refPool, tax,
558
590
  ...(vault ? [parseUnits(String(targetBnb), 18), vault] : promote ? [parseUnits(String(targetBnb), 18), promote.shareBps, promote.window] : grad !== null ? [parseUnits(String(grad), 18)] : [])]
559
591
  const createData = (logoURI, metaURI) => encodeFunctionData({ abi: PAD_ABI, functionName: fn, args: argsOf(logoURI, metaURI) })
592
+ const vanity = await vanityDeployer(ctx)
593
+ const handler = vanity && taxed ? (await taxContracts(ctx)).handler : zeroAddress
594
+ const prepareCreate = (logoURI, metaURI, fixed = null) => vanityCreate(ctx, me, createData(logoURI, metaURI), {
595
+ args: [name, symbol, metaURI, handler, tax.buyTaxBps, tax.sellTaxBps, false], fixed,
596
+ })
560
597
  // the logo / metadata strings never decide a revert: dry-run without them, so a create that would fail uploads nothing
561
- const dry = await simulate(ctx, me, ctx.pad, PAD_ABI, fn, argsOf('', ''))
598
+ const probe = await prepareCreate('', '')
599
+ const dry = await simulate(ctx, me, ctx.pad, probe.salt ? VANITY_ABI : PAD_ABI,
600
+ probe.salt ? 'createWithSalt' : fn, probe.salt ? [probe.salt, createData('', '')] : argsOf('', ''))
562
601
  if (dry.failed) return out({ success: false, step: 'create', ...dry.failed })
563
- const logo = await resolveLogo()
564
- const meta = await resolveMeta({ name, symbol, logoURI: logo.logoURI })
602
+ // a floor launch: the module was cloned for one token address, so the create reuses the metadata and the salt that
603
+ // give it, and is refused when anything that decides the address (name, symbol, tax rates) changed since
604
+ const logo = launchFloor ? { logoURI: launchFloor.logoURI, uploaded: !!launchFloor.uploaded } : await resolveLogo()
605
+ const meta = launchFloor ? { metaURI: launchFloor.metaURI, metadata: launchFloor.metadata } : await resolveMeta({ name, symbol, logoURI: logo.logoURI })
606
+ const launch = await prepareCreate(logo.logoURI, meta.metaURI, launchFloor ? { salt: launchFloor.salt, token: launchFloor.token } : null)
607
+ if (launch.mismatch) {
608
+ return fail(launch.mismatch.got
609
+ ? 'this create would put the token at another address than the one its floor module was cloned for: the name, the symbol or a tax rate changed since the module was cloned. Run the launch again with what it began with, or add --restart for a new module and token'
610
+ : 'the pad\'s token deployer could not be read: a floor launch creates its token at the address its module was cloned for, so nothing is built without it', {
611
+ floorToken: launch.mismatch.expected, ...(launch.mismatch.got && { wouldBe: launch.mismatch.got }), retry: launch.mismatch.got ? undefined : 'same command again',
612
+ })
613
+ }
614
+ if (launchFloor) {
615
+ // the last check before the tx: the pad itself says where this exact call puts the token
616
+ const sure = await simulate(ctx, me, ctx.pad, VANITY_ABI, 'createWithSalt', [launch.salt, createData(logo.logoURI, meta.metaURI)])
617
+ if (sure.failed) return out({ success: false, step: 'create', ...sure.failed })
618
+ if (String(sure.result).toLowerCase() !== String(launchFloor.token).toLowerCase()) {
619
+ return fail('the pad would create this token at another address than the one its floor module was cloned for: nothing is built. Add --restart for a new module and token', { floorToken: launchFloor.token, padSays: sure.result })
620
+ }
621
+ }
565
622
  let label = null
566
623
  const selfRecipient = recipient !== zeroAddress && recipient.toLowerCase() === String(me).toLowerCase()
567
624
  if (recipient !== zeroAddress && !selfRecipient) {
@@ -572,14 +629,16 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
572
629
  const baseCreatorFee = await createNote(ctx, net)
573
630
  const creatorFee = baseCreatorFee && promote ? `${baseCreatorFee} Less the ${promote.shareBps / 100}% of it you give promoters on their bound wallets' trades.` : baseCreatorFee
574
631
  const poolModule = promote && !!launchPoolModule
575
- return out(notes.step(ctx, { from: me, to: ctx.pad, data: createData(logo.logoURI, meta.metaURI) }, {
632
+ return out(notes.step(ctx, { from: me, to: ctx.pad, data: launch.data }, {
576
633
  step: 'create', chainId: Number(ctx.chainId), name, symbol, logoURI: logo.logoURI, ...(logo.uploaded && { uploaded: true }),
577
634
  metaURI: meta.metaURI, metadata: meta.metadata,
578
635
  quote: (await symbolOf(ctx, quote)) || quote, graduationTargetBnb: targetBnb, graduationAt: await units(ctx, quote, gradAmt),
579
636
  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(' / ')}` : ''}`,
580
637
  ...(refPool !== zeroAddress && quote.toLowerCase() !== String(ctx.wbnb).toLowerCase() && { refPool }),
581
638
  buyTaxPct: buyTax, sellTaxPct: sellTax, dividendPct: dividend,
582
- recipient: recipient === zeroAddress ? null : recipient, recipientLabel: selfRecipient ? 'you (the creator)' : label, tokenIfNext: dry.result,
639
+ recipient: recipient === zeroAddress ? null : recipient, recipientLabel: selfRecipient ? 'you (the creator)' : label, tokenIfNext: launch.token ?? dry.result,
640
+ ...(launch.token && { addressSuffix: 'abcd' }),
641
+ ...(launchFloor && { floorToken: launchFloor.token, metadataFixed: 'the metadata is the one fixed when the floor module was cloned (its URL is part of the token\'s address); --logo / --description / --website / --twitter given now are not read again' }),
583
642
  split: taxed
584
643
  ? `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`
585
644
  + (dividend > 0 ? '; if no holder has 10,000+ tokens when a tax is paid, the holders\' part goes to the recipient too' : '')
@@ -597,7 +656,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
597
656
  padGen: ctx.gen, pad: ctx.pad, vault,
598
657
  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',
599
658
  }),
600
- 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 …\`.`,
659
+ 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' : ''}. ${launch.token ? 'The CREATE2 address ends in abcd and is fixed for this transaction.' : 'tokenIfNext changes if another create lands first: the real address is the Created event from `gang tx --hash …`.'}`,
601
660
  }, 'create'))
602
661
  }
603
662
 
package/src/vanity.js ADDED
@@ -0,0 +1,97 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { encodeFunctionData, hexToBytes, keccak256, parseAbi, toHex, zeroAddress } from 'viem'
3
+ import { PAD3_GEN } from './gangpad.js'
4
+
5
+ export const VANITY_ABI = parseAbi([
6
+ 'function vanityDeployer() view returns (address)',
7
+ 'function createWithSalt(bytes32 salt, bytes data) returns (address token)',
8
+ 'function tokenInitCodeHash(string name, string symbol, string uri, address handler, uint16 buyTaxBps, uint16 sellTaxBps, bool reclaimable) view returns (bytes32)',
9
+ 'function mintInitCodeHash(string name, string symbol, string uri, address handler, uint16 buyTaxBps, uint16 sellTaxBps, uint256 startSupply, uint256 maxSupply) view returns (bytes32)',
10
+ 'error InvalidSuffix()', 'error VanityContextRequired()', 'error BadVanityCall()',
11
+ ])
12
+
13
+ /** The CREATE2 address `creator`'s user `salt` gives for `initCodeHash` (the pad binds the salt to the creator). */
14
+ export function vanityAddress(deployer, creator, initCodeHash, salt) {
15
+ const bound = new Uint8Array(64)
16
+ bound.set(hexToBytes(creator), 12)
17
+ bound.set(hexToBytes(salt), 32)
18
+ const preimage = new Uint8Array(85)
19
+ preimage[0] = 0xff
20
+ preimage.set(hexToBytes(deployer), 1)
21
+ preimage.set(hexToBytes(keccak256(bound)), 21)
22
+ preimage.set(hexToBytes(initCodeHash), 53)
23
+ return `0x${keccak256(preimage).slice(-40)}`
24
+ }
25
+
26
+ /** No RPC calls per attempt. Only the chosen candidate is checked for existing code. */
27
+ export async function mineSalt(deployer, creator, initCodeHash, start = BigInt(toHex(randomBytes(32)))) {
28
+ const bound = new Uint8Array(64)
29
+ bound.set(hexToBytes(creator), 12)
30
+ const preimage = new Uint8Array(85)
31
+ preimage[0] = 0xff
32
+ preimage.set(hexToBytes(deployer), 1)
33
+ preimage.set(hexToBytes(initCodeHash), 53)
34
+ for (let i = 0n; ; i++) {
35
+ const salt = toHex((start + i) % (1n << 256n), { size: 32 })
36
+ bound.set(hexToBytes(salt), 32)
37
+ preimage.set(hexToBytes(keccak256(bound)), 21)
38
+ const hash = keccak256(preimage)
39
+ if (hash.endsWith('abcd')) return { salt, token: `0x${hash.slice(-40)}` }
40
+ if (i % 4096n === 4095n) await new Promise((resolve) => setImmediate(resolve))
41
+ }
42
+ }
43
+
44
+ /** Probe only 3.0; a transport failure must never silently build an unsalted launch. */
45
+ export async function vanityDeployer(ctx) {
46
+ if (ctx.gen !== PAD3_GEN && ctx.version !== 3) return null
47
+ if (!ctx._vanityDeployer) ctx._vanityDeployer = (async () => {
48
+ let deployer
49
+ try { deployer = await ctx.read(ctx.pad, VANITY_ABI, 'vanityDeployer') } catch (e) {
50
+ const reverted = e?.walk?.((x) => x?.name === 'ContractFunctionRevertedError')
51
+ if (reverted && !reverted.data && (!reverted.raw || reverted.raw === '0x')) return null
52
+ throw e
53
+ }
54
+ return deployer.toLowerCase() === zeroAddress ? null : deployer
55
+ })()
56
+ return ctx._vanityDeployer
57
+ }
58
+
59
+ /**
60
+ * A salt whose address ends in abcd and has no code yet, for a token with these constructor `args`
61
+ * (tokenInitCodeHash's / mintInitCodeHash's): the address the token will have, known before it exists. null on a pad
62
+ * without the deployer.
63
+ */
64
+ export async function mineToken(ctx, creator, { mint = false, args }) {
65
+ const deployer = await vanityDeployer(ctx)
66
+ if (!deployer) return null
67
+ const initCodeHash = await ctx.read(deployer, VANITY_ABI, mint ? 'mintInitCodeHash' : 'tokenInitCodeHash', args)
68
+ let found
69
+ do { found = await mineSalt(deployer, creator, initCodeHash) }
70
+ while (await ctx.client.getBytecode({ address: found.token }).then((code) => code && code !== '0x'))
71
+ return { ...found, deployer, initCodeHash }
72
+ }
73
+
74
+ /**
75
+ * The create through the deployer. `fixed` ({ salt, token }): a launch that already named the token's address (a floor
76
+ * module is cloned for it) — the same salt is used, and when these `args` no longer lead to that address the result is
77
+ * { mismatch: { expected, got } } instead of a tx: the token would land elsewhere.
78
+ */
79
+ export async function vanityCreate(ctx, creator, data, { mint = false, args, fixed = null }) {
80
+ if (fixed) {
81
+ const deployer = await vanityDeployer(ctx)
82
+ if (!deployer) return { mismatch: { expected: fixed.token, got: null } }
83
+ const initCodeHash = await ctx.read(deployer, VANITY_ABI, mint ? 'mintInitCodeHash' : 'tokenInitCodeHash', args)
84
+ const got = vanityAddress(deployer, creator, initCodeHash, fixed.salt)
85
+ if (got.toLowerCase() !== String(fixed.token).toLowerCase()) return { mismatch: { expected: fixed.token, got } }
86
+ return {
87
+ salt: fixed.salt, token: got,
88
+ data: encodeFunctionData({ abi: VANITY_ABI, functionName: 'createWithSalt', args: [fixed.salt, data] }),
89
+ }
90
+ }
91
+ const found = await mineToken(ctx, creator, { mint, args })
92
+ if (!found) return { data }
93
+ return {
94
+ salt: found.salt, token: found.token,
95
+ data: encodeFunctionData({ abi: VANITY_ABI, functionName: 'createWithSalt', args: [found.salt, data] }),
96
+ }
97
+ }