four-flap-meme-sdk 1.5.33 → 1.5.35

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/dist/index.d.ts CHANGED
@@ -53,4 +53,4 @@ export { submitDirectToRpc, submitDirectToRpcSequential, // ✅ 新增:顺序
53
53
  submitDirectToRpcParallel, type DirectSubmitConfig, type DirectSubmitResult, type DirectTxResult } from './contracts/tm-bundle-merkle/submit.js';
54
54
  export { directV2BatchBuy, directV2BatchSell, directV3BatchBuy, directV3BatchSell, getRouterAddress, DIRECT_ROUTERS, type DirectV2BuyParams, type DirectV2SellParams, type DirectV3BuyParams, type DirectV3SellParams, type DirectRouterResult, type DirectRouterSignConfig, type DexKey, type RouterVersion, } from './dex/index.js';
55
55
  export * as XLayer from './xlayer/index.js';
56
- export { bundleBuy as xlayerBundleBuy, bundleSell as xlayerBundleSell, bundleBuySell as xlayerBundleBuySell, bundleSwapSign as xlayerBundleSwapSign, bundleBatchSwapSign as xlayerBundleBatchSwapSign, createBundleExecutor as xlayerCreateBundleExecutor, BundleExecutor as XLayerBundleExecutor, makeVolume as xlayerMakeVolume, singleRoundVolume as xlayerSingleRoundVolume, createVolumeExecutor as xlayerCreateVolumeExecutor, VolumeExecutor as XLayerVolumeExecutor, createDexExecutor as xlayerCreateDexExecutor, createDexQuery as xlayerCreateDexQuery, quoteOkbToToken as xlayerQuoteOkbToToken, quoteTokenToOkb as xlayerQuoteTokenToOkb, DexExecutor as XLayerDexExecutor, DexQuery as XLayerDexQuery, createAAAccountManager as xlayerCreateAAAccountManager, predictSender as xlayerPredictSender, createWallet as xlayerCreateWallet, AAAccountManager as XLayerAAAccountManager, generateAAWallets as xlayerGenerateAAWallets, generateAAWalletsFromMnemonic as xlayerGenerateAAWalletsFromMnemonic, predictSendersFromPrivateKeys as xlayerPredictSendersFromPrivateKeys, createBundlerClient as xlayerCreateBundlerClient, BundlerClient as XLayerBundlerClient, createPortalQuery as xlayerCreatePortalQuery, PortalQuery as XLayerPortalQuery, encodeBuyCall as xlayerEncodeBuyCall, encodeSellCall as xlayerEncodeSellCall, encodeApproveCall as xlayerEncodeApproveCall, parseOkb as xlayerParseOkb, formatOkb as xlayerFormatOkb, XLAYER_CHAIN_ID, FLAP_PORTAL as XLAYER_FLAP_PORTAL, ENTRYPOINT_V06 as XLAYER_ENTRYPOINT, SIMPLE_ACCOUNT_FACTORY as XLAYER_FACTORY, PARTICLE_BUNDLER_URL as XLAYER_BUNDLER_URL, WOKB as XLAYER_WOKB, POTATOSWAP_V2_ROUTER as XLAYER_POTATOSWAP_ROUTER, type XLayerConfig, type BundleBuyParams as XLayerBundleBuyParams, type BundleSellParams as XLayerBundleSellParams, type BundleBuySellParams as XLayerBundleBuySellParams, type BundleSwapParams as XLayerBundleSwapParams, type BundleSwapSignParams as XLayerBundleSwapSignParams, type BundleBatchSwapParams as XLayerBundleBatchSwapParams, type BundleBatchSwapSignParams as XLayerBundleBatchSwapSignParams, type VolumeParams as XLayerVolumeParams, type BundleBuyResult as XLayerBundleBuyResult, type BundleSellResult as XLayerBundleSellResult, type BundleBuySellResult as XLayerBundleBuySellResult, type BundleSwapResult as XLayerBundleSwapResult, type BundleSwapSignResult as XLayerBundleSwapSignResult, type BundleBatchSwapResult as XLayerBundleBatchSwapResult, type BundleBatchSwapSignResult as XLayerBundleBatchSwapSignResult, type VolumeResult as XLayerVolumeResult, type HandleOpsResult as XLayerHandleOpsResult, type AAAccount as XLayerAAAccount, type UserOperation as XLayerUserOperation, type GeneratedAAWallet as XLayerGeneratedAAWallet, type GenerateAAWalletsParams as XLayerGenerateAAWalletsParams, type GenerateAAWalletsResult as XLayerGenerateAAWalletsResult, } from './xlayer/index.js';
56
+ export { bundleBuy as xlayerBundleBuy, bundleSell as xlayerBundleSell, bundleBuySell as xlayerBundleBuySell, bundleSwapSign as xlayerBundleSwapSign, bundleBatchSwapSign as xlayerBundleBatchSwapSign, createBundleExecutor as xlayerCreateBundleExecutor, BundleExecutor as XLayerBundleExecutor, makeVolume as xlayerMakeVolume, singleRoundVolume as xlayerSingleRoundVolume, createVolumeExecutor as xlayerCreateVolumeExecutor, VolumeExecutor as XLayerVolumeExecutor, makeBuyFirstVolume as xlayerMakeBuyFirstVolume, BuyFirstVolumeExecutor as XLayerBuyFirstVolumeExecutor, AAPortalBuyFirstExecutor as XLayerAAPortalBuyFirstExecutor, AADexBuyFirstExecutor as XLayerAADexBuyFirstExecutor, createDexExecutor as xlayerCreateDexExecutor, createDexQuery as xlayerCreateDexQuery, quoteOkbToToken as xlayerQuoteOkbToToken, quoteTokenToOkb as xlayerQuoteTokenToOkb, DexExecutor as XLayerDexExecutor, DexQuery as XLayerDexQuery, createAAAccountManager as xlayerCreateAAAccountManager, predictSender as xlayerPredictSender, createWallet as xlayerCreateWallet, AAAccountManager as XLayerAAAccountManager, generateAAWallets as xlayerGenerateAAWallets, generateAAWalletsFromMnemonic as xlayerGenerateAAWalletsFromMnemonic, predictSendersFromPrivateKeys as xlayerPredictSendersFromPrivateKeys, createBundlerClient as xlayerCreateBundlerClient, BundlerClient as XLayerBundlerClient, createPortalQuery as xlayerCreatePortalQuery, PortalQuery as XLayerPortalQuery, encodeBuyCall as xlayerEncodeBuyCall, encodeSellCall as xlayerEncodeSellCall, encodeApproveCall as xlayerEncodeApproveCall, parseOkb as xlayerParseOkb, formatOkb as xlayerFormatOkb, XLAYER_CHAIN_ID, FLAP_PORTAL as XLAYER_FLAP_PORTAL, ENTRYPOINT_V06 as XLAYER_ENTRYPOINT, SIMPLE_ACCOUNT_FACTORY as XLAYER_FACTORY, PARTICLE_BUNDLER_URL as XLAYER_BUNDLER_URL, WOKB as XLAYER_WOKB, POTATOSWAP_V2_ROUTER as XLAYER_POTATOSWAP_ROUTER, type XLayerConfig, type BundleBuyParams as XLayerBundleBuyParams, type BundleSellParams as XLayerBundleSellParams, type BundleBuySellParams as XLayerBundleBuySellParams, type BundleSwapParams as XLayerBundleSwapParams, type BundleSwapSignParams as XLayerBundleSwapSignParams, type BundleBatchSwapParams as XLayerBundleBatchSwapParams, type BundleBatchSwapSignParams as XLayerBundleBatchSwapSignParams, type VolumeParams as XLayerVolumeParams, type BundleBuyResult as XLayerBundleBuyResult, type BundleSellResult as XLayerBundleSellResult, type BundleBuySellResult as XLayerBundleBuySellResult, type BundleSwapResult as XLayerBundleSwapResult, type BundleSwapSignResult as XLayerBundleSwapSignResult, type BundleBatchSwapResult as XLayerBundleBatchSwapResult, type BundleBatchSwapSignResult as XLayerBundleBatchSwapSignResult, type VolumeResult as XLayerVolumeResult, type BuyFirstParams as XLayerBuyFirstParams, type BuyFirstResult as XLayerBuyFirstResult, type BuyFirstVolumeParams as XLayerBuyFirstVolumeParams, type BuyFirstVolumeResult as XLayerBuyFirstVolumeResult, type HandleOpsResult as XLayerHandleOpsResult, type AAAccount as XLayerAAAccount, type UserOperation as XLayerUserOperation, type GeneratedAAWallet as XLayerGeneratedAAWallet, type GenerateAAWalletsParams as XLayerGenerateAAWalletsParams, type GenerateAAWalletsResult as XLayerGenerateAAWalletsResult, } from './xlayer/index.js';
package/dist/index.js CHANGED
@@ -105,6 +105,8 @@ export {
105
105
  bundleBuy as xlayerBundleBuy, bundleSell as xlayerBundleSell, bundleBuySell as xlayerBundleBuySell, bundleSwapSign as xlayerBundleSwapSign, bundleBatchSwapSign as xlayerBundleBatchSwapSign, createBundleExecutor as xlayerCreateBundleExecutor, BundleExecutor as XLayerBundleExecutor,
106
106
  // 刷量
107
107
  makeVolume as xlayerMakeVolume, singleRoundVolume as xlayerSingleRoundVolume, createVolumeExecutor as xlayerCreateVolumeExecutor, VolumeExecutor as XLayerVolumeExecutor,
108
+ // ✅ Buy-First 刷量(对齐 BSC buy-first)
109
+ makeBuyFirstVolume as xlayerMakeBuyFirstVolume, BuyFirstVolumeExecutor as XLayerBuyFirstVolumeExecutor, AAPortalBuyFirstExecutor as XLayerAAPortalBuyFirstExecutor, AADexBuyFirstExecutor as XLayerAADexBuyFirstExecutor,
108
110
  // DEX 交易
109
111
  createDexExecutor as xlayerCreateDexExecutor, createDexQuery as xlayerCreateDexQuery, quoteOkbToToken as xlayerQuoteOkbToToken, quoteTokenToOkb as xlayerQuoteTokenToOkb, DexExecutor as XLayerDexExecutor, DexQuery as XLayerDexQuery,
110
112
  // AA 账户管理
@@ -71,6 +71,8 @@ export declare class BundleExecutor {
71
71
  * 捆绑买入
72
72
  *
73
73
  * 多个地址同一笔 handleOps 买入代币
74
+ * ✅ 对齐 BSC:在买入时从买入金额中扣除利润,买入后立即转账利润(直接转账,无需多跳)
75
+ * ✅ 支持 ERC20 代币作为 quoteToken(如 USDC),利润会报价转换为 OKB 后转账
74
76
  */
75
77
  bundleBuy(params: BundleBuyParams): Promise<BundleBuyResult>;
76
78
  /**
@@ -12,7 +12,8 @@ import { FLAP_PORTAL, ENTRYPOINT_ABI, DEFAULT_CALL_GAS_LIMIT_SELL, DEFAULT_WITHD
12
12
  import { AAAccountManager, encodeExecute, encodeExecuteBatch } from './aa-account.js';
13
13
  import { encodeBuyCall, encodeSellCall, encodeApproveCall, encodeTransferCall, PortalQuery, parseOkb, formatOkb, } from './portal-ops.js';
14
14
  import { mapWithConcurrency } from '../utils/concurrency.js';
15
- import { PROFIT_CONFIG } from '../utils/constants.js';
15
+ import { PROFIT_CONFIG, ZERO_ADDRESS } from '../utils/constants.js';
16
+ import { DexQuery } from './dex.js';
16
17
  // ============================================================================
17
18
  // AA Nonce(EntryPoint nonce)本地分配器
18
19
  // ============================================================================
@@ -88,6 +89,14 @@ function calculateProfitWei(amountWei, profitBps) {
88
89
  return 0n;
89
90
  return (amountWei * BigInt(profitBps)) / 10000n;
90
91
  }
92
+ /**
93
+ * ✅ 对齐 BSC:计算利润和剩余金额(从买入金额中扣除利润)
94
+ */
95
+ function calculateProfit(amountWei, profitBps) {
96
+ const profit = calculateProfitWei(amountWei, profitBps);
97
+ const remaining = amountWei - profit;
98
+ return { profit, remaining };
99
+ }
91
100
  /**
92
101
  * XLayer 捆绑交易执行器
93
102
  *
@@ -426,9 +435,11 @@ export class BundleExecutor {
426
435
  nonce: params.nonce,
427
436
  initCode: params.initCode,
428
437
  });
429
- // 计算可归集金额(用已知余额近似;fund 发生时余额会变大,属于可接受的保守近似)
430
- const withdrawAmount = senderBalance > prefundWei + params.reserveWei
431
- ? senderBalance - prefundWei - params.reserveWei
438
+ // 使用最新余额计算可归集金额(避免因预充导致旧余额低估)
439
+ const freshBalance = await this.aaManager.getProvider().getBalance(params.sender);
440
+ const baseBalance = freshBalance > 0n ? freshBalance : senderBalance;
441
+ const withdrawAmount = baseBalance > prefundWei + params.reserveWei
442
+ ? baseBalance - prefundWei - params.reserveWei
432
443
  : 0n;
433
444
  if (withdrawAmount <= 0n) {
434
445
  console.log(`\n[${params.ownerName ?? 'owner'}] 归集后可转出=0(余额不足以覆盖 prefund+reserve)`);
@@ -524,9 +535,11 @@ export class BundleExecutor {
524
535
  * 捆绑买入
525
536
  *
526
537
  * 多个地址同一笔 handleOps 买入代币
538
+ * ✅ 对齐 BSC:在买入时从买入金额中扣除利润,买入后立即转账利润(直接转账,无需多跳)
539
+ * ✅ 支持 ERC20 代币作为 quoteToken(如 USDC),利润会报价转换为 OKB 后转账
527
540
  */
528
541
  async bundleBuy(params) {
529
- const { tokenAddress, privateKeys, buyAmounts, transferBackToOwner, config } = params;
542
+ const { tokenAddress, privateKeys, buyAmounts, quoteToken, quoteTokenDecimals, transferBackToOwner, config } = params;
530
543
  if (privateKeys.length !== buyAmounts.length) {
531
544
  throw new Error('私钥数量和购买金额数量必须一致');
532
545
  }
@@ -538,20 +551,84 @@ export class BundleExecutor {
538
551
  console.log('=== XLayer Bundle Buy ===');
539
552
  console.log('token:', tokenAddress);
540
553
  console.log('owners:', wallets.length);
554
+ const effConfig = { ...(this.config ?? {}), ...(config ?? {}) };
555
+ const profitSettings = resolveProfitSettings(effConfig);
556
+ // ✅ 确定 inputToken:如果传入了 quoteToken 且非零地址,则使用它;否则使用零地址(原生代币)
557
+ const inputToken = quoteToken && quoteToken !== ZERO_ADDRESS ? quoteToken : ZERO_ADDRESS;
558
+ const useNativeToken = inputToken === ZERO_ADDRESS;
559
+ // ✅ 对齐 BSC:计算利润并从买入金额中扣除
560
+ // 如果使用非原生代币,需要根据精度转换金额(buyAmounts 是按 18 位精度传入的)
561
+ const originalBuyWeis = buyAmounts.map((a) => parseOkb(a));
562
+ let adjustedOriginalBuyWeis = originalBuyWeis;
563
+ if (!useNativeToken && quoteTokenDecimals !== undefined && quoteTokenDecimals !== 18) {
564
+ const decimalsDiff = 18 - quoteTokenDecimals;
565
+ const divisor = BigInt(10 ** decimalsDiff);
566
+ adjustedOriginalBuyWeis = originalBuyWeis.map(amount => amount / divisor);
567
+ }
568
+ const buyWeis = [];
569
+ const profitWeis = [];
570
+ let totalProfitWei = 0n; // 原生代币利润(OKB)或 ERC20 代币利润(需要报价转换)
571
+ for (let i = 0; i < adjustedOriginalBuyWeis.length; i++) {
572
+ const original = adjustedOriginalBuyWeis[i];
573
+ if (profitSettings.extractProfit) {
574
+ const { profit, remaining } = calculateProfit(original, profitSettings.profitBps);
575
+ buyWeis.push(remaining);
576
+ profitWeis.push(profit);
577
+ totalProfitWei += profit;
578
+ }
579
+ else {
580
+ buyWeis.push(original);
581
+ profitWeis.push(0n);
582
+ }
583
+ }
584
+ // ✅ ERC20 购买:获取代币利润等值的原生代币(OKB)报价
585
+ let nativeProfitAmount = totalProfitWei; // 原生代币购买时直接使用
586
+ if (!useNativeToken && profitSettings.extractProfit && totalProfitWei > 0n) {
587
+ // 将代币利润转换为等值原生代币(OKB)
588
+ const dexQuery = new DexQuery(effConfig);
589
+ nativeProfitAmount = await dexQuery.quoteTokenToOkb(totalProfitWei, inputToken);
590
+ if (nativeProfitAmount === 0n) {
591
+ console.warn(`[警告] ERC20 代币利润报价失败,跳过利润提取`);
592
+ }
593
+ }
594
+ if (profitSettings.extractProfit && nativeProfitAmount > 0n) {
595
+ console.log(`[利润提取] 总利润: ${useNativeToken ? formatOkb(nativeProfitAmount) : `${formatOkb(totalProfitWei)} (ERC20) -> ${formatOkb(nativeProfitAmount)} (OKB)`} -> ${profitSettings.profitRecipient}`);
596
+ }
541
597
  // 1. 预取账户信息(并行),并批量估算 gas(减少对 bundler 的 N 次请求)
542
598
  const accountInfos = await this.aaManager.getMultipleAccountInfo(wallets.map((w) => w.address));
543
- const buyWeis = buyAmounts.map((a) => parseOkb(a));
544
599
  const nonceMap = new AANonceMap();
545
600
  for (const ai of accountInfos)
546
601
  nonceMap.init(ai.sender, ai.nonce);
547
602
  // 估算前确保 sender 有足够余额(用于 bundler 模拟;paymaster 场景会自动跳过)
548
- // 避免 Promise.all 突发并发(大规模地址会触发 RPC 限流)
603
+ // 注意:需要包含原始买入金额(因为利润会在买入后单独转走)
604
+ // 如果使用 ERC20 代币,需要确保 sender 有足够的 ERC20 代币余额
549
605
  await mapWithConcurrency(accountInfos, 6, async (ai, i) => {
550
- await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, buyWeis[i] + parseOkb('0.0003'), `owner${i + 1}/buy-prefund-before-estimate`);
606
+ if (useNativeToken) {
607
+ await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, originalBuyWeis[i] + parseOkb('0.0003'), `owner${i + 1}/buy-prefund-before-estimate`);
608
+ }
609
+ else {
610
+ // ERC20 代币:确保有足够的 OKB 用于 gas,以及足够的 ERC20 代币用于购买
611
+ await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, parseOkb('0.0003'), `owner${i + 1}/buy-prefund-before-estimate`);
612
+ // TODO: 如果需要,可以在这里检查并转账 ERC20 代币到 sender
613
+ }
551
614
  });
615
+ // ✅ 构建买入 callData:如果使用 ERC20 代币,需要修改 encodeBuyCall 以支持 inputToken
552
616
  const buyCallDatas = buyWeis.map((buyWei) => {
553
- const swapData = encodeBuyCall(tokenAddress, buyWei, 0n);
554
- return encodeExecute(this.portalAddress, buyWei, swapData);
617
+ // 使用 portal swapExactInput,支持 inputToken 参数
618
+ const portalIface = new Interface([
619
+ 'function swapExactInput((address inputToken,address outputToken,uint256 inputAmount,uint256 minOutputAmount,bytes permitData) params) payable returns (uint256)',
620
+ ]);
621
+ const swapData = portalIface.encodeFunctionData('swapExactInput', [
622
+ {
623
+ inputToken,
624
+ outputToken: tokenAddress,
625
+ inputAmount: buyWei,
626
+ minOutputAmount: 0n,
627
+ permitData: '0x',
628
+ },
629
+ ]);
630
+ // 如果使用原生代币,value 为买入金额;否则为 0
631
+ return encodeExecute(this.portalAddress, useNativeToken ? buyWei : 0n, swapData);
555
632
  });
556
633
  const initCodes = accountInfos.map((ai, i) => ai.deployed ? '0x' : this.aaManager.generateInitCode(wallets[i].address));
557
634
  const { userOps: buyUserOps, prefundWeis } = await this.aaManager.buildUserOpsWithBundlerEstimateBatch({
@@ -562,15 +639,50 @@ export class BundleExecutor {
562
639
  initCode: initCodes[i],
563
640
  })),
564
641
  });
565
- // 补足 prefund + 买入金额(多数情况下上一步的 0.0003 已足够,这里通常不会再转账)
642
+ // 补足 prefund + 买入金额(使用扣除利润后的金额)
566
643
  await mapWithConcurrency(accountInfos, 6, async (ai, i) => {
567
- await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, buyWeis[i] + prefundWeis[i] + parseOkb('0.0002'), `owner${i + 1}/buy-fund`);
644
+ if (useNativeToken) {
645
+ await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, buyWeis[i] + prefundWeis[i] + parseOkb('0.0002'), `owner${i + 1}/buy-fund`);
646
+ }
647
+ else {
648
+ // ERC20 代币:只需要确保有足够的 OKB 用于 gas
649
+ await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, prefundWeis[i] + parseOkb('0.0002'), `owner${i + 1}/buy-fund`);
650
+ // TODO: 如果需要,可以在这里检查并转账 ERC20 代币到 sender
651
+ }
568
652
  });
569
653
  // 签名(受控并发,避免大规模时阻塞)
570
654
  const signedBuy = await mapWithConcurrency(buyUserOps, 10, async (op, i) => this.aaManager.signUserOp(op, wallets[i]));
571
655
  const buyOps = signedBuy.map((s) => s.userOp);
572
- // 2. 执行买入
573
- const buyResult = await this.runHandleOps('buyBundle', buyOps, bundlerSigner, beneficiary);
656
+ // 利润转账 UserOps(买入后立即转走利润,直接转账无需多跳)
657
+ // 对齐 BSC:如果使用 ERC20 代币,利润已通过报价转换为 OKB,直接转账 OKB
658
+ const profitOps = [];
659
+ if (profitSettings.extractProfit && nativeProfitAmount > 0n) {
660
+ // 找到利润最大的钱包作为利润转账的 sender(对齐 BSC 的 maxFundsIndex 逻辑)
661
+ const maxProfitIndex = profitWeis.reduce((maxIdx, profit, idx) => profit > profitWeis[maxIdx] ? idx : maxIdx, 0);
662
+ const profitSender = accountInfos[maxProfitIndex].sender;
663
+ const profitOwner = wallets[maxProfitIndex];
664
+ // 利润转账:直接转账 OKB(无论原始是原生代币还是 ERC20 代币,最终都转 OKB)
665
+ const profitCallData = encodeExecute(profitSettings.profitRecipient, nativeProfitAmount, '0x');
666
+ const { userOp: profitOp, prefundWei: profitPrefund } = await this.aaManager.buildUserOpWithFixedGas({
667
+ ownerWallet: profitOwner,
668
+ sender: profitSender,
669
+ nonce: nonceMap.next(profitSender),
670
+ initCode: initCodes[maxProfitIndex] === '0x' ? '0x' : initCodes[maxProfitIndex],
671
+ callData: profitCallData,
672
+ deployed: accountInfos[maxProfitIndex].deployed,
673
+ fixedGas: {
674
+ ...(effConfig.fixedGas ?? {}),
675
+ callGasLimit: effConfig.fixedGas?.callGasLimit ?? DEFAULT_CALL_GAS_LIMIT_WITHDRAW,
676
+ },
677
+ });
678
+ // 确保 profit sender 有足够余额(用于支付利润转账的 gas)
679
+ await this.aaManager.ensureSenderBalance(profitOwner, profitSender, nativeProfitAmount + profitPrefund + parseOkb('0.0001'), `profit-transfer-fund`);
680
+ const signedProfit = await this.aaManager.signUserOp(profitOp, profitOwner);
681
+ profitOps.push(signedProfit.userOp);
682
+ }
683
+ // 2. 执行买入 + 利润转账(同一笔 handleOps)
684
+ const allBuyOps = [...buyOps, ...profitOps];
685
+ const buyResult = await this.runHandleOps('buyBundle', allBuyOps, bundlerSigner, beneficiary);
574
686
  if (!buyResult) {
575
687
  throw new Error('买入交易失败');
576
688
  }
@@ -773,7 +885,7 @@ export class BundleExecutor {
773
885
  * 完整流程:买入 -> 授权 -> 卖出 -> 归集
774
886
  */
775
887
  async bundleBuySell(params) {
776
- const { tokenAddress, privateKeys, buyAmounts, sellPercent = 100, withdrawToOwner = true, withdrawReserve = DEFAULT_WITHDRAW_RESERVE, config, } = params;
888
+ const { tokenAddress, privateKeys, buyAmounts, quoteToken, quoteTokenDecimals, sellPercent = 100, withdrawToOwner = true, withdrawReserve = DEFAULT_WITHDRAW_RESERVE, config, } = params;
777
889
  if (privateKeys.length !== buyAmounts.length) {
778
890
  throw new Error('私钥数量和购买金额数量必须一致');
779
891
  }
@@ -792,17 +904,81 @@ export class BundleExecutor {
792
904
  const nonceMap = new AANonceMap();
793
905
  for (const ai of accountInfos)
794
906
  nonceMap.init(ai.sender, ai.nonce);
907
+ const effProfitCfgBuySell = { ...(this.config ?? {}), ...(config ?? {}) };
908
+ const profitSettingsBuySell = resolveProfitSettings(effProfitCfgBuySell);
909
+ // ✅ 确定 inputToken:如果传入了 quoteToken 且非零地址,则使用它;否则使用零地址(原生代币)
910
+ const inputToken = quoteToken && quoteToken !== ZERO_ADDRESS ? quoteToken : ZERO_ADDRESS;
911
+ const useNativeToken = inputToken === ZERO_ADDRESS;
912
+ // ✅ 对齐 BSC:计算利润并从买入金额中扣除
913
+ // 如果使用非原生代币,需要根据精度转换金额(buyAmounts 是按 18 位精度传入的)
914
+ const originalBuyWeis = buyAmounts.map((a) => parseOkb(a));
915
+ let adjustedOriginalBuyWeis = originalBuyWeis;
916
+ if (!useNativeToken && quoteTokenDecimals !== undefined && quoteTokenDecimals !== 18) {
917
+ const decimalsDiff = 18 - quoteTokenDecimals;
918
+ const divisor = BigInt(10 ** decimalsDiff);
919
+ adjustedOriginalBuyWeis = originalBuyWeis.map(amount => amount / divisor);
920
+ }
921
+ const buyWeis = [];
922
+ const profitWeis = [];
923
+ let totalBuyProfitWei = 0n; // 原生代币利润(OKB)或 ERC20 代币利润(需要报价转换)
924
+ for (let i = 0; i < adjustedOriginalBuyWeis.length; i++) {
925
+ const original = adjustedOriginalBuyWeis[i];
926
+ if (profitSettingsBuySell.extractProfit) {
927
+ const { profit, remaining } = calculateProfit(original, profitSettingsBuySell.profitBps);
928
+ buyWeis.push(remaining);
929
+ profitWeis.push(profit);
930
+ totalBuyProfitWei += profit;
931
+ }
932
+ else {
933
+ buyWeis.push(original);
934
+ profitWeis.push(0n);
935
+ }
936
+ }
937
+ // ✅ ERC20 购买:获取代币利润等值的原生代币(OKB)报价
938
+ let nativeBuyProfitAmount = totalBuyProfitWei; // 原生代币购买时直接使用
939
+ if (!useNativeToken && profitSettingsBuySell.extractProfit && totalBuyProfitWei > 0n) {
940
+ // 将代币利润转换为等值原生代币(OKB)
941
+ const dexQuery = new DexQuery(effProfitCfgBuySell);
942
+ nativeBuyProfitAmount = await dexQuery.quoteTokenToOkb(totalBuyProfitWei, inputToken);
943
+ if (nativeBuyProfitAmount === 0n) {
944
+ console.warn(`[警告] ERC20 代币利润报价失败,跳过利润提取`);
945
+ }
946
+ }
947
+ if (profitSettingsBuySell.extractProfit && nativeBuyProfitAmount > 0n) {
948
+ console.log(`[利润提取-买入] 总利润: ${useNativeToken ? formatOkb(nativeBuyProfitAmount) : `${formatOkb(totalBuyProfitWei)} (ERC20) -> ${formatOkb(nativeBuyProfitAmount)} (OKB)`} -> ${profitSettingsBuySell.profitRecipient}`);
949
+ }
795
950
  // 1. 买入(批量估算 + 并发补余额 + 并发签名)
796
- const buyWeis = buyAmounts.map((a) => parseOkb(a));
797
951
  await mapWithConcurrency(accountInfos, 6, async (ai, i) => {
798
952
  const buyWei = buyWeis[i] ?? 0n;
799
953
  if (buyWei <= 0n)
800
954
  return;
801
- await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, buyWei + parseOkb('0.0003'), `owner${i + 1}/buy-prefund-before-estimate`);
955
+ if (useNativeToken) {
956
+ // 注意:需要包含原始买入金额(因为利润会在买入后单独转走)
957
+ await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, originalBuyWeis[i] + parseOkb('0.0003'), `owner${i + 1}/buy-prefund-before-estimate`);
958
+ }
959
+ else {
960
+ // ERC20 代币:确保有足够的 OKB 用于 gas
961
+ await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, parseOkb('0.0003'), `owner${i + 1}/buy-prefund-before-estimate`);
962
+ // TODO: 如果需要,可以在这里检查并转账 ERC20 代币到 sender
963
+ }
802
964
  });
965
+ // ✅ 构建买入 callData:如果使用 ERC20 代币,需要修改 encodeBuyCall 以支持 inputToken
803
966
  const buyCallDatas = buyWeis.map((buyWei) => {
804
- const swapData = encodeBuyCall(tokenAddress, buyWei, 0n);
805
- return encodeExecute(this.portalAddress, buyWei, swapData);
967
+ // 使用 portal swapExactInput,支持 inputToken 参数
968
+ const portalIface = new Interface([
969
+ 'function swapExactInput((address inputToken,address outputToken,uint256 inputAmount,uint256 minOutputAmount,bytes permitData) params) payable returns (uint256)',
970
+ ]);
971
+ const swapData = portalIface.encodeFunctionData('swapExactInput', [
972
+ {
973
+ inputToken,
974
+ outputToken: tokenAddress,
975
+ inputAmount: buyWei,
976
+ minOutputAmount: 0n,
977
+ permitData: '0x',
978
+ },
979
+ ]);
980
+ // 如果使用原生代币,value 为买入金额;否则为 0
981
+ return encodeExecute(this.portalAddress, useNativeToken ? buyWei : 0n, swapData);
806
982
  });
807
983
  const initCodes = accountInfos.map((ai, i) => (ai.deployed ? '0x' : this.aaManager.generateInitCode(wallets[i].address)));
808
984
  const { userOps: buyUserOps, prefundWeis } = await this.aaManager.buildUserOpsWithBundlerEstimateBatch({
@@ -815,11 +991,44 @@ export class BundleExecutor {
815
991
  });
816
992
  await mapWithConcurrency(accountInfos, 6, async (ai, i) => {
817
993
  const buyWei = buyWeis[i] ?? 0n;
818
- await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, buyWei + (prefundWeis[i] ?? 0n) + parseOkb('0.0002'), `owner${i + 1}/buy-fund`);
994
+ if (useNativeToken) {
995
+ await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, buyWei + (prefundWeis[i] ?? 0n) + parseOkb('0.0002'), `owner${i + 1}/buy-fund`);
996
+ }
997
+ else {
998
+ // ERC20 代币:只需要确保有足够的 OKB 用于 gas
999
+ await this.aaManager.ensureSenderBalance(wallets[i], ai.sender, (prefundWeis[i] ?? 0n) + parseOkb('0.0002'), `owner${i + 1}/buy-fund`);
1000
+ // TODO: 如果需要,可以在这里检查并转账 ERC20 代币到 sender
1001
+ }
819
1002
  });
820
1003
  const signedBuy = await mapWithConcurrency(buyUserOps, 10, async (op, i) => this.aaManager.signUserOp(op, wallets[i]));
821
1004
  const buyOps = signedBuy.map((s) => s.userOp);
822
- const buyResult = await this.runHandleOps('buyBundle', buyOps, bundlerSigner, beneficiary);
1005
+ // 利润转账 UserOps(买入后立即转走利润,直接转账无需多跳)
1006
+ // ✅ 对齐 BSC:如果使用 ERC20 代币,利润已通过报价转换为 OKB,直接转账 OKB
1007
+ const profitOps = [];
1008
+ if (profitSettingsBuySell.extractProfit && nativeBuyProfitAmount > 0n) {
1009
+ const maxProfitIndex = profitWeis.reduce((maxIdx, profit, idx) => profit > profitWeis[maxIdx] ? idx : maxIdx, 0);
1010
+ const profitSender = accountInfos[maxProfitIndex].sender;
1011
+ const profitOwner = wallets[maxProfitIndex];
1012
+ // 利润转账:直接转账 OKB(无论原始是原生代币还是 ERC20 代币,最终都转 OKB)
1013
+ const profitCallData = encodeExecute(profitSettingsBuySell.profitRecipient, nativeBuyProfitAmount, '0x');
1014
+ const { userOp: profitOp, prefundWei: profitPrefund } = await this.aaManager.buildUserOpWithFixedGas({
1015
+ ownerWallet: profitOwner,
1016
+ sender: profitSender,
1017
+ nonce: nonceMap.next(profitSender),
1018
+ initCode: initCodes[maxProfitIndex] === '0x' ? '0x' : initCodes[maxProfitIndex],
1019
+ callData: profitCallData,
1020
+ deployed: accountInfos[maxProfitIndex].deployed,
1021
+ fixedGas: {
1022
+ ...(effProfitCfgBuySell.fixedGas ?? {}),
1023
+ callGasLimit: effProfitCfgBuySell.fixedGas?.callGasLimit ?? DEFAULT_CALL_GAS_LIMIT_WITHDRAW,
1024
+ },
1025
+ });
1026
+ await this.aaManager.ensureSenderBalance(profitOwner, profitSender, nativeBuyProfitAmount + profitPrefund + parseOkb('0.0001'), `profit-transfer-fund`);
1027
+ const signedProfit = await this.aaManager.signUserOp(profitOp, profitOwner);
1028
+ profitOps.push(signedProfit.userOp);
1029
+ }
1030
+ const allBuyOps = [...buyOps, ...profitOps];
1031
+ const buyResult = await this.runHandleOps('buyBundle', allBuyOps, bundlerSigner, beneficiary);
823
1032
  if (!buyResult) {
824
1033
  throw new Error('买入交易失败');
825
1034
  }
@@ -858,11 +1067,9 @@ export class BundleExecutor {
858
1067
  if (!sellResult) {
859
1068
  throw new Error('卖出交易失败');
860
1069
  }
861
- // 3. 可选:归集 OKB
1070
+ // 3. 可选:归集 OKB(卖出后的利润在 withdraw 阶段刮取)
862
1071
  let withdrawResult;
863
- let totalProfitWei = 0n;
864
- const effProfitCfg = { ...(this.config ?? {}), ...(config ?? {}) };
865
- const profitSettings = resolveProfitSettings(effProfitCfg);
1072
+ let totalSellWithdrawProfitWei = 0n;
866
1073
  if (withdrawToOwner) {
867
1074
  const withdrawOps = [];
868
1075
  // 批量获取 OKB 余额(sell 后状态)
@@ -886,11 +1093,11 @@ export class BundleExecutor {
886
1093
  ownerName: `owner${it.i + 1}`,
887
1094
  configOverride: config,
888
1095
  });
889
- if (signed && profitSettings.extractProfit) {
1096
+ if (signed && profitSettingsBuySell.extractProfit) {
890
1097
  const withdrawAmount = it.senderBalance > signed.prefundWei + reserveWei
891
1098
  ? it.senderBalance - signed.prefundWei - reserveWei
892
1099
  : 0n;
893
- totalProfitWei += calculateProfitWei(withdrawAmount, profitSettings.profitBps);
1100
+ totalSellWithdrawProfitWei += calculateProfitWei(withdrawAmount, profitSettingsBuySell.profitBps);
894
1101
  }
895
1102
  if (signed?.userOp)
896
1103
  nonceMap.commit(it.sender, it.nonce);
@@ -913,10 +1120,11 @@ export class BundleExecutor {
913
1120
  finalBalances,
914
1121
  profit: withdrawToOwner
915
1122
  ? {
916
- extractProfit: profitSettings.extractProfit,
917
- profitBps: profitSettings.profitBps,
918
- profitRecipient: profitSettings.profitRecipient,
919
- totalProfitWei: totalProfitWei.toString(),
1123
+ extractProfit: profitSettingsBuySell.extractProfit,
1124
+ profitBps: profitSettingsBuySell.profitBps,
1125
+ profitRecipient: profitSettingsBuySell.profitRecipient,
1126
+ // 总利润 = 买入阶段利润(已转走)+ 卖出后归集阶段的利润
1127
+ totalProfitWei: (totalBuyProfitWei + totalSellWithdrawProfitWei).toString(),
920
1128
  }
921
1129
  : undefined,
922
1130
  };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * XLayer AA Buy-First 自动刷量(对齐 BSC buy-first 思路)
3
+ *
4
+ * - tradeType=FLAP:内盘(Flap Portal)
5
+ * - tradeType=V2:外盘(PotatoSwap V2)
6
+ *
7
+ * 代码实现分离:
8
+ * - 内盘执行器:`portal-buy-first.ts`
9
+ * - 外盘执行器:`dex-buy-first.ts`
10
+ */
11
+ import type { BuyFirstVolumeParams, BuyFirstVolumeResult, XLayerConfig } from './types.js';
12
+ export declare class BuyFirstVolumeExecutor {
13
+ private config;
14
+ constructor(config?: XLayerConfig);
15
+ execute(params: BuyFirstVolumeParams): Promise<BuyFirstVolumeResult>;
16
+ }
17
+ export declare function createBuyFirstVolumeExecutor(config?: XLayerConfig): BuyFirstVolumeExecutor;
18
+ export declare function makeBuyFirstVolume(params: BuyFirstVolumeParams): Promise<BuyFirstVolumeResult>;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * XLayer AA Buy-First 自动刷量(对齐 BSC buy-first 思路)
3
+ *
4
+ * - tradeType=FLAP:内盘(Flap Portal)
5
+ * - tradeType=V2:外盘(PotatoSwap V2)
6
+ *
7
+ * 代码实现分离:
8
+ * - 内盘执行器:`portal-buy-first.ts`
9
+ * - 外盘执行器:`dex-buy-first.ts`
10
+ */
11
+ import { parseOkb, formatOkb } from './portal-ops.js';
12
+ import { AAPortalBuyFirstExecutor } from './portal-buy-first.js';
13
+ import { AADexBuyFirstExecutor } from './dex-buy-first.js';
14
+ function sleep(ms) {
15
+ return new Promise((resolve) => setTimeout(resolve, ms));
16
+ }
17
+ export class BuyFirstVolumeExecutor {
18
+ constructor(config = {}) {
19
+ this.config = config;
20
+ }
21
+ async execute(params) {
22
+ const { tradeType = 'FLAP', buyerFundsPerRound, rounds, intervalMs = 3000, config, ...rest } = params;
23
+ const effConfig = { ...(this.config ?? {}), ...(config ?? {}) };
24
+ const roundResults = [];
25
+ let successRounds = 0;
26
+ let failedRounds = 0;
27
+ let totalVolume = 0n;
28
+ const perRoundWei = parseOkb(String(buyerFundsPerRound));
29
+ for (let r = 0; r < rounds; r++) {
30
+ console.log(`\n========== AA BuyFirst Round ${r + 1}/${rounds} (${tradeType}) ==========`);
31
+ try {
32
+ const execParams = {
33
+ tradeType,
34
+ buyerFunds: buyerFundsPerRound,
35
+ config: effConfig,
36
+ ...rest,
37
+ };
38
+ const result = tradeType === 'FLAP'
39
+ ? await new AAPortalBuyFirstExecutor(effConfig).execute(execParams)
40
+ : await new AADexBuyFirstExecutor(effConfig).execute(execParams);
41
+ roundResults.push(result);
42
+ successRounds++;
43
+ // 交易量按“买入资金 * 2(买+卖)”统计(与 BSC buy-first 口径更接近)
44
+ totalVolume += perRoundWei * 2n;
45
+ }
46
+ catch (e) {
47
+ console.error(`AA BuyFirst Round ${r + 1} 失败:`, e);
48
+ failedRounds++;
49
+ }
50
+ if (r < rounds - 1 && intervalMs > 0) {
51
+ console.log(`等待 ${intervalMs}ms...`);
52
+ await sleep(intervalMs);
53
+ }
54
+ }
55
+ console.log('\n=== AA BuyFirst Volume Summary ===');
56
+ console.log('成功轮数:', successRounds);
57
+ console.log('失败轮数:', failedRounds);
58
+ console.log('总交易量:', formatOkb(totalVolume), 'OKB');
59
+ return { successRounds, failedRounds, roundResults, totalVolume };
60
+ }
61
+ }
62
+ export function createBuyFirstVolumeExecutor(config) {
63
+ return new BuyFirstVolumeExecutor(config);
64
+ }
65
+ export async function makeBuyFirstVolume(params) {
66
+ const executor = createBuyFirstVolumeExecutor(params.config);
67
+ return executor.execute(params);
68
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * XLayer AA Buy-First(外盘 / PotatoSwap V2)
3
+ *
4
+ * 对齐 BSC buy-first 思路:
5
+ * - 买方先买入(OKB -> token)
6
+ * - 卖方再卖出等值 token(token -> OKB,卖方需要预持仓)
7
+ * - ✅ 利润:在卖出后归集阶段刮取
8
+ */
9
+ import type { XLayerConfig } from './types.js';
10
+ import type { BuyFirstParams, BuyFirstResult } from './types.js';
11
+ export declare class AADexBuyFirstExecutor {
12
+ private aaManager;
13
+ private portalQuery;
14
+ private dexQuery;
15
+ private config;
16
+ constructor(config?: XLayerConfig);
17
+ private getEffectiveRouter;
18
+ private runHandleOps;
19
+ private pickWallets;
20
+ private buildWithdrawUserOp;
21
+ private safeQuoteBuy;
22
+ execute(params: BuyFirstParams): Promise<BuyFirstResult>;
23
+ }
24
+ export declare function createAADexBuyFirstExecutor(config?: XLayerConfig): AADexBuyFirstExecutor;