@gangfun/cli 0.37.0 → 0.38.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/DEVELOPERS.md CHANGED
@@ -95,6 +95,18 @@ Each command prints one JSON object on stdout. The exceptions: `gang watch` prin
95
95
 
96
96
  New fields can appear at any time, so ignore what you don't know. Other fields can change with a minor version: read `gang capabilities` and test before you upgrade.
97
97
 
98
+ ### Pad 3.0 token addresses
99
+
100
+ After the owner enables the `abcd` factory on Pad 3.0, the CLI automatically searches a CREATE2 salt for every curve,
101
+ fair-mint and fly launch, including vault and promoter variants. The commands and flags stay the same. The create preview
102
+ includes `addressSuffix: "abcd"` and `tokenIfNext`: this address is fixed for that transaction, including its final metadata,
103
+ and does not change when another creator launches first. Confirm the deployed token from the `Created` event.
104
+
105
+ Direct integrations read `vanityDeployer()` on the pad. A nonzero result requires wrapping the original create calldata in
106
+ `createWithSalt(bytes32 salt, bytes data)`. Obtain the exact `tokenInitCodeHash` or `mintInitCodeHash` from that factory and
107
+ search with the effective salt `keccak256(abi.encode(creator, salt))`. The address must end in `abcd` (hex, ignoring checksum
108
+ capitalization). Existing tokens keep their addresses. A suffix alone does not prove a token was launched on Gang.
109
+
98
110
  ### Failure codes
99
111
 
100
112
  | `code` | Meaning |
@@ -95,6 +95,16 @@ gang execute --request-id <id> 发送
95
95
 
96
96
  随时可能增加新字段,不认识的忽略即可。其他字段可能随小版本变化:升级前看 `gang capabilities` 并先测试。
97
97
 
98
+ ### Pad 3.0 代币地址
99
+
100
+ Pad 3.0 的 owner 启用 `abcd` 部署器后,CLI 会为曲线、打新、铸币飞轮发币自动搜索 CREATE2 salt,金库和推广员版本也包含在内。
101
+ 命令和参数不变。发币预览增加 `addressSuffix: "abcd"` 和 `tokenIfNext`:地址按这笔交易的最终元数据确定,其他人先发币也不会改变它。
102
+ 实际部署结果仍以 `Created` 事件为准。
103
+
104
+ 直接对接合约时,先读 pad 的 `vanityDeployer()`。返回非零地址就必须用 `createWithSalt(bytes32 salt, bytes data)` 包住原来的发币 calldata。
105
+ 从该部署器读取准确的 `tokenInitCodeHash` 或 `mintInitCodeHash`,按有效 salt `keccak256(abi.encode(creator, salt))` 搜索地址。
106
+ 十六进制地址后四位必须为 `abcd`,忽略校验和带来的大小写。旧币地址不变;仅凭后缀不能认定是 Gang 发行的币。
107
+
98
108
  ### 失败代码
99
109
 
100
110
  | `code` | 含义 |
package/README.md CHANGED
@@ -6,6 +6,8 @@ Operate [gang.fun](https://gang.fun) from a Binance **Agentic Wallet**. Curve bu
6
6
 
7
7
  **One command per action (0.12.0+):** `gang buy` / `sell` / `info` / `status` / `claim` / `mint` / `withdraw` / `release` work on every token: the CLI reads the token's kind and runs the V3, 打新 or V2 / Soft code. `gang v3 …` / `gang fair …` stay as aliases.
8
8
 
9
+ **Pad 3.0 address suffix (0.38.0+):** after the owner activates the `abcd` deployer, all new curve, fair-mint and flywheel tokens end in `abcd` (ignoring checksum capitalization). The CLI automatically finds the salt after metadata is finalized, including `--grad`, `--vault` and `--promote` launches, and shows the predicted address in `tokenIfNext`. Update the CLI before activation: old direct create calls are then refused. Existing tokens keep their addresses and trade normally. Before activation the new CLI uses the existing create flow.
10
+
9
11
  **铸币飞轮 / Mint Flywheel (0.18.0+):** `gang create --fly` starts a sale (kind 3): shares with a quota per wallet (invites add quota), a pool at the mint price once it fills, and minting that goes on after launch. The unified commands detect these tokens (`kind: "fly"`); `gang fly …` is the alias. Live on BSC mainnet since 2026-10-30 (V1 pad `0x631e66560F4FAE4e486B65349edE48189E48B029`); from 0.21.0 new tokens went to the V2 pad `0x281889ad915c1A95ffc4922235c6314b3Cbd8a5a`, and from 0.30.0 they go to GangLaunchpad 3.0 (below). Every other command follows the token's own pad, so V1 and V2 tokens keep working (`padVersion` in `gang info`: 1, 2 or 3). `--testnet` uses BSC testnet (V1 set 2, V2 `0x7069…E3d6`, 3.0). Rules: `skill/references/fly.md`.
10
12
 
11
13
  **V3 tax tokens and 打新 (0.9.0+):** on GangLaunchpad, live on BSC mainnet since 2026-10-27 (1.0: pad `0x15CFD2dc8278Fb87a1783ef42111618E20874365`, GangRouter `0xE040445690Aa56C8b68B7f7038C7b2562B5079C4`; 2.0 since 2026-10-31: pad `0x770331a9accdb53ACb4a45B6c5B7D151fADCe557`, GangRouter `0xa83209d6bfC2B220cD86410cCDDC71FEb354844a`; new tokens go to 3.0 since CLI 0.30.0, see below; all built in); `--testnet` uses BSC testnet (3.0 for new tokens; 2.0 and set 10 = 1.0 for their tokens).
package/README.zh-CN.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # Gang CLI(`gang`)
2
2
 
3
+ **Pad 3.0 地址后缀(0.38.0+):** owner 启用 `abcd` 部署器后,曲线、打新和铸币飞轮新币地址统一以 `abcd` 结尾(忽略校验和大小写)。CLI 会在最终元数据确定后自动计算 salt,`--grad`、`--vault`、`--promote` 发币也包含在内,`tokenIfNext` 显示确定的预测地址。请在启用前升级 CLI:启用后旧的直接发币调用会被拒绝。旧币地址和交易不变;启用前,新 CLI 仍走原有发币流程。
4
+
3
5
  用 Binance **Agentic Wallet** 操作 [gang.fun](https://gang.fun)。内盘买入/发币需要 SPACE ID `.ai` Agent ID。本 CLI 只组 calldata,签名走 `baw`,不持有私钥。
4
6
 
5
7
  **`gang create`:** 在 GangLaunchpad 上发 V3 币(`gang create --fair` 发打新);不带 `--buy-tax` / `--sell-tax` 就是无税币。LaunchpadV2 / Soft / LaunchpadU / LaunchpadS **不再发新币**,存量币照常交易(`gang buy` / `gang sell`)。V3 新币在 GangLaunchpad 1.0 上 **15 BNB** 毕业;2.0 和 3.0 上由 creator 用 `--grad` 选 **6 / 9 / 12 / 15 BNB**(默认 9)。Soft 存量链上仍为 20 BNB 毕业。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gangfun/cli",
3
- "version": "0.37.0",
3
+ "version": "0.38.0",
4
4
  "mcpName": "io.github.gangfun/gang",
5
5
  "description": "Gang launchpad CLI for Binance Agentic Wallet agents: create on GangLaunchpad (untaxed or tax tokens), 打新 fair mint, PancakeSwap pool trades, LaunchpadV2 and legacy Soft/U/S trade.",
6
6
  "type": "module",
package/src/fair.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createPublicClient, parseAbi, encodeFunctionData, decodeEventLog, formatUnits, parseEther, parseUnits, isAddress, zeroAddress } from 'viem'
2
+ import { VANITY_ABI, vanityCreate, vanityDeployer } from './vanity.js'
2
3
  import { bawAddress } from './baw.js'
3
4
  import { defaultRefPool, dividendOf, fundingStep as fund, parseAmount, parseIntIn, parseNum, poolSellQuote, POOL_SELL_HINT, revertOf as revertIn, ROUTER_ABI, ROUTER_HINTS, routerDeadline, step, swapBackState, units, viaRouter, GAS_RESERVE } from './steps.js'
4
5
  import { API } from './discover.js'
@@ -125,7 +126,7 @@ export function walletFor(ctx, from) {
125
126
  }
126
127
 
127
128
  /** Revert name (+ BadConfig reason) of a failed eth_call, or null when it was the RPC. */
128
- const revertOf = (e) => revertIn(e, [PAD_ABI, ROUTER_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
129
+ const revertOf = (e) => revertIn(e, [PAD_ABI, VANITY_ABI, ROUTER_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
129
130
 
130
131
  /** Dry-run `data` from `from`; null when it would pass. */
131
132
  async function dryRun(ctx, from, to, data, value = 0n) {
@@ -329,15 +330,21 @@ export async function runFair(sub, { opt, flag, out, fail, summarize, resolveLog
329
330
  const createData = (logoURI, metaURI) => encodeFunctionData({
330
331
  abi: PAD_ABI, functionName: 'create', args: [name, symbol, logoURI, metaURI, quote, refPool, cfg, BigInt(devShares)],
331
332
  })
333
+ const vanity = await vanityDeployer(ctx)
334
+ const handler = vanity ? await ctx.read(ctx.pad, PAD_ABI, 'taxHandler') : zeroAddress
335
+ const prepareCreate = (logoURI, metaURI) => vanityCreate(ctx, me, createData(logoURI, metaURI), {
336
+ args: [name, symbol, metaURI, handler, 100, 100, true],
337
+ })
332
338
  // the logo / metadata strings never decide a revert: dry-run without them, so a create that would fail uploads nothing
333
- const dry = await dryRun(ctx, me, ctx.pad, createData('', ''))
339
+ const dry = await dryRun(ctx, me, ctx.pad, (await prepareCreate('', '')).data)
334
340
  if (dry) return out({ success: false, step: 'create', ...dry })
335
341
  const logo = await resolveLogo()
336
342
  const meta = await resolveMeta({ name, symbol, logoURI: logo.logoURI })
337
- const data = createData(logo.logoURI, meta.metaURI)
338
- return out(notes.step(ctx, { from: me, to: ctx.pad, data }, {
343
+ const launch = await prepareCreate(logo.logoURI, meta.metaURI)
344
+ return out(notes.step(ctx, { from: me, to: ctx.pad, data: launch.data }, {
339
345
  step: 'create', chainId: Number(ctx.chainId), name, symbol, logoURI: logo.logoURI, ...(logo.uploaded && { uploaded: true }),
340
346
  metaURI: meta.metaURI, metadata: meta.metadata, quote: sym || quote,
347
+ ...(launch.token && { tokenIfNext: launch.token, addressSuffix: 'abcd' }),
341
348
  raise: await units(ctx, quote, raiseQuote), sharePrice: await units(ctx, quote, sharePrice),
342
349
  capShares: cfg.capBps * 2, minWallets: Math.ceil(10_000 / (cfg.capBps * 2)), holdPct, mintFeePct, exitFeePct, devShares,
343
350
  devCost: await units(ctx, quote, need),
package/src/fly.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createPublicClient, parseAbi, encodeFunctionData, decodeEventLog, formatUnits, parseEther, parseUnits, isAddress, zeroAddress } from 'viem'
2
+ import { VANITY_ABI, vanityCreate, vanityDeployer } from './vanity.js'
2
3
  import { defaultRefPool, dividendOf, VAULT_ABI, fundingStep as fund, parseAmount, parseIntIn, parseNum, poolSellQuote, POOL_SELL_HINT, revertOf as revertIn, roomyGas, ROUTER_ABI, ROUTER_HINTS, step, swapBackState, units, GAS_RESERVE } from './steps.js'
3
4
  import { API, get as apiGet } from './discover.js'
4
5
  import { walletFor } from './fair.js'
@@ -191,7 +192,7 @@ const HINTS = {
191
192
  FeeOnTransferQuote: 'the quote token takes a fee on transfer; it cannot be used',
192
193
  RouterNeedsGate: 'this sale has no Agent gate, so router entries are off',
193
194
  }
194
- const revertOf = (e) => revertIn(e, [FLY_PAD_ABI, FLY_HANDLER_ABI, TOKEN_ABI, ROUTER_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
195
+ const revertOf = (e) => revertIn(e, [FLY_PAD_ABI, VANITY_ABI, FLY_HANDLER_ABI, TOKEN_ABI, ROUTER_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
195
196
 
196
197
  /**
197
198
  * Network settings: GangLaunchpad's chain, RPCs, WBNB and GangRouter (pool trades), with the fly pads. ctx.pad /
@@ -827,16 +828,24 @@ export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo
827
828
  const sym = await symbolOf(ctx, quote)
828
829
  const pre = await fund(ctx, { me: who, token: quote, need, spender: ctx.pad, sym }, rawOnly, summarize)
829
830
  if (pre) return out(pre)
830
- const createData = (logoURI, metaURI) => tagged(encodeFunctionData({
831
+ const createData = (logoURI, metaURI) => encodeFunctionData({
831
832
  abi: padAbi, functionName: 'create', args: [[name, symbol, logoURI, metaURI], quote, refPool, cfg, BigInt(devShares)],
832
- }))
833
- const dry = await dryRun(ctx, who, ctx.pad, createData('', ''))
833
+ })
834
+ const vanity = await vanityDeployer(ctx)
835
+ const handler = vanity ? await handlerOf() : zeroAddress
836
+ const maxSupply = parseEther('2000000000') * BigInt(cfg.postMint ? cfg.supplyCapMul : 1)
837
+ const prepareCreate = (logoURI, metaURI) => vanityCreate(ctx, who, createData(logoURI, metaURI), {
838
+ mint: true, args: [name, symbol, metaURI, handler, 100, cfg.sellTaxBps, 0n, maxSupply],
839
+ })
840
+ const dry = await dryRun(ctx, who, ctx.pad, tagged((await prepareCreate('', '')).data))
834
841
  if (dry) return out({ success: false, step: 'create', ...dry })
835
842
  const logo = await resolveLogo()
836
843
  const meta = await resolveMeta({ name, symbol, logoURI: logo.logoURI })
837
- return out(write({ from: who, to: ctx.pad, data: createData(logo.logoURI, meta.metaURI) }, {
844
+ const launch = await prepareCreate(logo.logoURI, meta.metaURI)
845
+ return out(write({ from: who, to: ctx.pad, data: tagged(launch.data) }, {
838
846
  step: 'create', kind: 'fly', padVersion: ctx.version, ...(ctx.version === 3 && { padGen: PAD3_GEN }), pad: ctx.pad, name, symbol, logoURI: logo.logoURI, ...(logo.uploaded && { uploaded: true }),
839
847
  metaURI: meta.metaURI, metadata: meta.metadata, quote: sym || quote, preset: presetName, config: cfgView(cfg),
848
+ ...(launch.token && { tokenIfNext: launch.token, addressSuffix: 'abcd' }),
840
849
  sharePrice: await units(ctx, quote, quoteWbnb ? price : (price * 100n) / 102n), devShares, devCost: await units(ctx, quote, need),
841
850
  ...(v2 && v.postMint && {
842
851
  guardNote: cfg.guardBps
package/src/v3.js CHANGED
@@ -14,6 +14,7 @@ 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 { VANITY_ABI, vanityCreate, vanityDeployer } from './vanity.js'
17
18
 
18
19
  /**
19
20
  * `gang v3 …` — LaunchpadV3 (tax recipient): a token with its own buy / sell tax (1–5% each), a dividend share and a
@@ -160,7 +161,7 @@ const VIRTUAL_TOKEN = 1_066_666_666_666_666_666_666_666_667n
160
161
  const ceilDiv = (a, b) => (a + b - 1n) / b
161
162
 
162
163
  /** 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 })
164
+ 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
165
 
165
166
  /** eth_call `data` from `from`: { result } when it passes, { failed } with the revert (or RPC error) otherwise. */
166
167
  async function simulate(ctx, from, to, abi, functionName, args, value = 0n) {
@@ -557,11 +558,19 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
557
558
  const argsOf = (logoURI, metaURI) => [name, symbol, logoURI, metaURI, quote, refPool, tax,
558
559
  ...(vault ? [parseUnits(String(targetBnb), 18), vault] : promote ? [parseUnits(String(targetBnb), 18), promote.shareBps, promote.window] : grad !== null ? [parseUnits(String(grad), 18)] : [])]
559
560
  const createData = (logoURI, metaURI) => encodeFunctionData({ abi: PAD_ABI, functionName: fn, args: argsOf(logoURI, metaURI) })
561
+ const vanity = await vanityDeployer(ctx)
562
+ const handler = vanity && taxed ? (await taxContracts(ctx)).handler : zeroAddress
563
+ const prepareCreate = (logoURI, metaURI) => vanityCreate(ctx, me, createData(logoURI, metaURI), {
564
+ args: [name, symbol, metaURI, handler, tax.buyTaxBps, tax.sellTaxBps, false],
565
+ })
560
566
  // 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('', ''))
567
+ const probe = await prepareCreate('', '')
568
+ const dry = await simulate(ctx, me, ctx.pad, probe.salt ? VANITY_ABI : PAD_ABI,
569
+ probe.salt ? 'createWithSalt' : fn, probe.salt ? [probe.salt, createData('', '')] : argsOf('', ''))
562
570
  if (dry.failed) return out({ success: false, step: 'create', ...dry.failed })
563
571
  const logo = await resolveLogo()
564
572
  const meta = await resolveMeta({ name, symbol, logoURI: logo.logoURI })
573
+ const launch = await prepareCreate(logo.logoURI, meta.metaURI)
565
574
  let label = null
566
575
  const selfRecipient = recipient !== zeroAddress && recipient.toLowerCase() === String(me).toLowerCase()
567
576
  if (recipient !== zeroAddress && !selfRecipient) {
@@ -572,14 +581,15 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
572
581
  const baseCreatorFee = await createNote(ctx, net)
573
582
  const creatorFee = baseCreatorFee && promote ? `${baseCreatorFee} Less the ${promote.shareBps / 100}% of it you give promoters on their bound wallets' trades.` : baseCreatorFee
574
583
  const poolModule = promote && !!launchPoolModule
575
- return out(notes.step(ctx, { from: me, to: ctx.pad, data: createData(logo.logoURI, meta.metaURI) }, {
584
+ return out(notes.step(ctx, { from: me, to: ctx.pad, data: launch.data }, {
576
585
  step: 'create', chainId: Number(ctx.chainId), name, symbol, logoURI: logo.logoURI, ...(logo.uploaded && { uploaded: true }),
577
586
  metaURI: meta.metaURI, metadata: meta.metadata,
578
587
  quote: (await symbolOf(ctx, quote)) || quote, graduationTargetBnb: targetBnb, graduationAt: await units(ctx, quote, gradAmt),
579
588
  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
589
  ...(refPool !== zeroAddress && quote.toLowerCase() !== String(ctx.wbnb).toLowerCase() && { refPool }),
581
590
  buyTaxPct: buyTax, sellTaxPct: sellTax, dividendPct: dividend,
582
- recipient: recipient === zeroAddress ? null : recipient, recipientLabel: selfRecipient ? 'you (the creator)' : label, tokenIfNext: dry.result,
591
+ recipient: recipient === zeroAddress ? null : recipient, recipientLabel: selfRecipient ? 'you (the creator)' : label, tokenIfNext: launch.token ?? dry.result,
592
+ ...(launch.token && { addressSuffix: 'abcd' }),
583
593
  split: taxed
584
594
  ? `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
595
  + (dividend > 0 ? '; if no holder has 10,000+ tokens when a tax is paid, the holders\' part goes to the recipient too' : '')
@@ -597,7 +607,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
597
607
  padGen: ctx.gen, pad: ctx.pad, vault,
598
608
  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
609
  }),
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 …\`.`,
610
+ 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
611
  }, 'create'))
602
612
  }
603
613
 
package/src/vanity.js ADDED
@@ -0,0 +1,57 @@
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
+ /** No RPC calls per attempt. Only the chosen candidate is checked for existing code. */
14
+ export async function mineSalt(deployer, creator, initCodeHash, start = BigInt(toHex(randomBytes(32)))) {
15
+ const bound = new Uint8Array(64)
16
+ bound.set(hexToBytes(creator), 12)
17
+ const preimage = new Uint8Array(85)
18
+ preimage[0] = 0xff
19
+ preimage.set(hexToBytes(deployer), 1)
20
+ preimage.set(hexToBytes(initCodeHash), 53)
21
+ for (let i = 0n; ; i++) {
22
+ const salt = toHex((start + i) % (1n << 256n), { size: 32 })
23
+ bound.set(hexToBytes(salt), 32)
24
+ preimage.set(hexToBytes(keccak256(bound)), 21)
25
+ const hash = keccak256(preimage)
26
+ if (hash.endsWith('abcd')) return { salt, token: `0x${hash.slice(-40)}` }
27
+ if (i % 4096n === 4095n) await new Promise((resolve) => setImmediate(resolve))
28
+ }
29
+ }
30
+
31
+ /** Probe only 3.0; a transport failure must never silently build an unsalted launch. */
32
+ export async function vanityDeployer(ctx) {
33
+ if (ctx.gen !== PAD3_GEN && ctx.version !== 3) return null
34
+ if (!ctx._vanityDeployer) ctx._vanityDeployer = (async () => {
35
+ let deployer
36
+ try { deployer = await ctx.read(ctx.pad, VANITY_ABI, 'vanityDeployer') } catch (e) {
37
+ const reverted = e?.walk?.((x) => x?.name === 'ContractFunctionRevertedError')
38
+ if (reverted && !reverted.data && (!reverted.raw || reverted.raw === '0x')) return null
39
+ throw e
40
+ }
41
+ return deployer.toLowerCase() === zeroAddress ? null : deployer
42
+ })()
43
+ return ctx._vanityDeployer
44
+ }
45
+
46
+ export async function vanityCreate(ctx, creator, data, { mint = false, args }) {
47
+ const deployer = await vanityDeployer(ctx)
48
+ if (!deployer) return { data }
49
+ const initCodeHash = await ctx.read(deployer, VANITY_ABI, mint ? 'mintInitCodeHash' : 'tokenInitCodeHash', args)
50
+ let found
51
+ do { found = await mineSalt(deployer, creator, initCodeHash) }
52
+ while (await ctx.client.getBytecode({ address: found.token }).then((code) => code && code !== '0x'))
53
+ return {
54
+ ...found,
55
+ data: encodeFunctionData({ abi: VANITY_ABI, functionName: 'createWithSalt', args: [found.salt, data] }),
56
+ }
57
+ }