four-flap-meme-sdk 4.5.4 → 4.5.5

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.
@@ -1,2 +1,10 @@
1
+ import { ethers } from 'ethers';
1
2
  export { generateDisperseHopPaths, buildNativeHopChain, NATIVE_TRANSFER_GAS_LIMIT, } from '../../utils/hop-chains.js';
2
3
  export type { DisperseHopPath } from './types/index.js';
4
+ /**
5
+ * 读代币上明确声明的转账税(钱包间互转)。买卖税不算:只收买卖税的币多跳不能少转。
6
+ * 读不到返回 0,行为与不传税率一致。
7
+ */
8
+ export declare function readTransferTaxBps(provider: ethers.JsonRpcProvider, token: string): Promise<number>;
9
+ /** 扣转账税后的到账数量;税额向上取整,保证转出不超过实际余额 */
10
+ export declare function amountAfterTransferTax(amount: bigint, taxBps: number): bigint;
@@ -1 +1,28 @@
1
+ import { ethers } from 'ethers';
2
+ import { normalizeFeeToBps } from '../../domains/lp-inspect/inspect-tax.js';
1
3
  export { generateDisperseHopPaths, buildNativeHopChain, NATIVE_TRANSFER_GAS_LIMIT, } from '../../utils/hop-chains.js';
4
+ const TRANSFER_TAX_FNS = ['transferTaxBps', 'transferTax', 'transferFee'];
5
+ /**
6
+ * 读代币上明确声明的转账税(钱包间互转)。买卖税不算:只收买卖税的币多跳不能少转。
7
+ * 读不到返回 0,行为与不传税率一致。
8
+ */
9
+ export async function readTransferTaxBps(provider, token) {
10
+ const contract = new ethers.Contract(token, TRANSFER_TAX_FNS.map((name) => `function ${name}() view returns (uint256)`), provider);
11
+ const reads = await Promise.allSettled(TRANSFER_TAX_FNS.map(async (name) => Number(await contract.getFunction(name).staticCall())));
12
+ let bps = 0;
13
+ for (const [i, item] of reads.entries()) {
14
+ if (item.status !== 'fulfilled')
15
+ continue;
16
+ const value = TRANSFER_TAX_FNS[i] === 'transferTaxBps' ? item.value : normalizeFeeToBps(item.value);
17
+ if (typeof value === 'number' && value > 0 && value < 10000)
18
+ bps = Math.max(bps, value);
19
+ }
20
+ return bps;
21
+ }
22
+ /** 扣转账税后的到账数量;税额向上取整,保证转出不超过实际余额 */
23
+ export function amountAfterTransferTax(amount, taxBps) {
24
+ if (taxBps <= 0)
25
+ return amount;
26
+ const tax = (amount * BigInt(taxBps) + 9999n) / 10000n;
27
+ return amount - tax;
28
+ }
@@ -98,6 +98,8 @@ export type SweepSignParams = {
98
98
  config: FourSignConfig;
99
99
  /** ✅ 新增:起始 nonce(用于并行调用时避免 nonce 冲突,仅对第一个源钱包生效) */
100
100
  startNonce?: number;
101
+ /** 代币转账税(bps)。ERC20 多跳时每个中转钱包只转出实际到账的数量;不传则读代币的 transferTaxBps() 等 view */
102
+ transferTaxBps?: number;
101
103
  /** ✅ 新增:代币池子类型(用于利润报价),默认 'v2' */
102
104
  tokenPoolType?: TokenPoolType;
103
105
  /** ✅ 新增:报价代币类型(池子的计价代币),默认 'native'(BNB/MON) */
@@ -129,6 +131,8 @@ export type PairwiseTransferSignParams = {
129
131
  config: FourSignConfig;
130
132
  /** ✅ 起始 nonce(仅对第一个 sender 生效,用于并行调用避免 nonce 冲突) */
131
133
  startNonce?: number;
134
+ /** 代币转账税(bps)。ERC20 多跳时每个中转钱包只转出实际到账的数量;不传则读代币的 transferTaxBps() 等 view */
135
+ transferTaxBps?: number;
132
136
  tokenPoolType?: TokenPoolType;
133
137
  quoteToken?: QuoteTokenType;
134
138
  userType?: UserType;
@@ -1,6 +1,4 @@
1
1
  import type { DisperseSignParams, DisperseMerkleResult } from './types/index.js';
2
- /** 扣转账税后的到账数量;税额向上取整,保证转出不超过实际余额 */
3
- export declare function amountAfterTransferTax(amount: bigint, taxBps: number): bigint;
4
2
  /**
5
3
  * 分发(仅签名版本 - 不依赖 Merkle)
6
4
  * ✅ 精简版:只负责签名交易,不提交到 Merkle
@@ -2,35 +2,10 @@ import { ethers, Wallet } from 'ethers';
2
2
  import { getOptimizedGasPrice, NonceManager, buildProfitHopTransactions, PROFIT_HOP_COUNT, } from '../../utils/bundle-helpers.js';
3
3
  import { calculateTransferFee, floorErc20TransferGasLimit, GAS_LIMITS, isBscChain } from '../../core/constants/index.js';
4
4
  import { getGasPriceConfig, shouldExtractProfit, getProfitRecipient, getBribeAmount } from '../config-helpers.js';
5
- import { normalizeFeeToBps } from '../../domains/lp-inspect/inspect-tax.js';
5
+ import { amountAfterTransferTax, readTransferTaxBps } from './swap-hop-helpers.js';
6
6
  import { getErc20Decimals as _getErc20Decimals, generateHopWallets as _generateHopWallets, normalizeAmounts as _normalizeAmounts, calculateGasLimit as _calculateGasLimit, estimateSweepLimits, isNativeTokenAddress as _isNativeTokenAddress, } from '../internal.js';
7
7
  import { normalizeItemsOrRecipientsAmounts, resolveHopCountInput, resolveProvidedHops, resolveSignContext, signBribeTransaction, } from '../../core/sign-context-helpers.js';
8
8
  // ==================== 钱包转账按地址收费 ====================
9
- const TRANSFER_TAX_FNS = ['transferTaxBps', 'transferTax', 'transferFee'];
10
- /**
11
- * 读代币上明确声明的转账税(钱包间互转)。买卖税不算:只收买卖税的币多跳不能少转。
12
- * 读不到返回 0,行为与不传税率一致。
13
- */
14
- async function readTransferTaxBps(provider, token) {
15
- const contract = new ethers.Contract(token, TRANSFER_TAX_FNS.map((name) => `function ${name}() view returns (uint256)`), provider);
16
- const reads = await Promise.allSettled(TRANSFER_TAX_FNS.map(async (name) => Number(await contract.getFunction(name).staticCall())));
17
- let bps = 0;
18
- for (const [i, item] of reads.entries()) {
19
- if (item.status !== 'fulfilled')
20
- continue;
21
- const value = TRANSFER_TAX_FNS[i] === 'transferTaxBps' ? item.value : normalizeFeeToBps(item.value);
22
- if (typeof value === 'number' && value > 0 && value < 10000)
23
- bps = Math.max(bps, value);
24
- }
25
- return bps;
26
- }
27
- /** 扣转账税后的到账数量;税额向上取整,保证转出不超过实际余额 */
28
- export function amountAfterTransferTax(amount, taxBps) {
29
- if (taxBps <= 0)
30
- return amount;
31
- const tax = (amount * BigInt(taxBps) + 9999n) / 10000n;
32
- return amount - tax;
33
- }
34
9
  /**
35
10
  * 分发(仅签名版本 - 不依赖 Merkle)
36
11
  * ✅ 精简版:只负责签名交易,不提交到 Merkle
@@ -4,6 +4,7 @@ import { BLOCKRAZOR_BUILDER_EOA, calculateTransferFee, CHAINS, floorErc20Transfe
4
4
  import { getTxType, getGasPriceConfig, shouldExtractProfit, getProfitRecipient, getBribeAmount, } from '../config-helpers.js';
5
5
  import { getErc20Decimals as _getErc20Decimals, generateHopWallets as _generateHopWallets, calculateGasLimit as _calculateGasLimit, isNativeTokenAddress as _isNativeTokenAddress, } from '../internal.js';
6
6
  import { createSignProvider, resolveProvidedHops } from '../../core/sign-context-helpers.js';
7
+ import { amountAfterTransferTax, readTransferTaxBps } from './swap-hop-helpers.js';
7
8
  /**
8
9
  * 多对多(地址一一对应)转账(仅签名版本 - 不依赖 Merkle)
9
10
  * - 支持原生币 / ERC20
@@ -11,7 +12,7 @@ import { createSignProvider, resolveProvidedHops } from '../../core/sign-context
11
12
  * - 支持利润刮取:利润由第一个 sender 支付(作为额外费用,不扣减每对转账金额)
12
13
  */
13
14
  export async function pairwiseTransferWithBundleMerkle(params) {
14
- const { senderPrivateKeys, receiverAddresses, amount, amounts, tokenAddress, tokenDecimals, hopCount = 0, hopPrivateKeys, config, startNonce, } = params;
15
+ const { senderPrivateKeys, receiverAddresses, amount, amounts, tokenAddress, tokenDecimals, hopCount = 0, hopPrivateKeys, config, startNonce, transferTaxBps: transferTaxBpsParam, } = params;
15
16
  if (!senderPrivateKeys || senderPrivateKeys.length === 0) {
16
17
  return { signedTransactions: [], hopWallets: undefined };
17
18
  }
@@ -49,11 +50,15 @@ export async function pairwiseTransferWithBundleMerkle(params) {
49
50
  const nativeGasLimit = (config.prefer21000ForNative ?? false) ? 21000n : finalGasLimit;
50
51
  const nativeTransferGasLimit = 21000n;
51
52
  const erc20TransferGasLimit = floorErc20TransferGasLimit(config.gasLimit);
52
- const [gasPrice, decimals] = await Promise.all([
53
+ const [gasPrice, decimals, transferTaxBps] = await Promise.all([
53
54
  getOptimizedGasPrice(provider, getGasPriceConfig(config)),
54
55
  isNative
55
56
  ? Promise.resolve(18)
56
57
  : Promise.resolve(tokenDecimals ?? (await _getErc20Decimals(provider, tokenAddress, chainIdNum))),
58
+ // ERC20 多跳才需要转账税;不走多跳时接收方到账少一些但不会失败
59
+ isNative || !preparedHops || transferTaxBpsParam !== undefined
60
+ ? Promise.resolve(transferTaxBpsParam ?? 0)
61
+ : readTransferTaxBps(provider, tokenAddress).catch(() => 0),
57
62
  ]);
58
63
  const gasFields = buildGasFields(txType, gasPrice);
59
64
  const iface = isNative ? null : new ethers.Interface(['function transfer(address,uint256) returns (bool)']);
@@ -222,7 +227,11 @@ export async function pairwiseTransferWithBundleMerkle(params) {
222
227
  chainId: BigInt(chainIdNum),
223
228
  },
224
229
  });
225
- // hop wallets:逐层传递
230
+ // hop wallets:逐层传递;hopAmounts[j] = 第 j 个钱包实际收到、可以转出的数量(带税代币逐跳递减)
231
+ const hopAmounts = [amtWei];
232
+ for (let j = 1; j < fullChain.length; j++) {
233
+ hopAmounts.push(amountAfterTransferTax(hopAmounts[j - 1], transferTaxBps));
234
+ }
226
235
  for (let j = 1; j < fullChain.length; j++) {
227
236
  const fromWallet = fullChain[j];
228
237
  const toAddress = addresses[j + 1];
@@ -240,7 +249,7 @@ export async function pairwiseTransferWithBundleMerkle(params) {
240
249
  chainId: BigInt(chainIdNum),
241
250
  },
242
251
  });
243
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, amtWei]);
252
+ const erc20Data = iface.encodeFunctionData('transfer', [toAddress, hopAmounts[j]]);
244
253
  txsToSign.push({
245
254
  wallet: fromWallet,
246
255
  tx: {
@@ -255,7 +264,7 @@ export async function pairwiseTransferWithBundleMerkle(params) {
255
264
  });
256
265
  }
257
266
  else {
258
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, amtWei]);
267
+ const erc20Data = iface.encodeFunctionData('transfer', [toAddress, hopAmounts[j]]);
259
268
  txsToSign.push({
260
269
  wallet: fromWallet,
261
270
  tx: {
@@ -34,6 +34,8 @@ export interface SweepBranchContext {
34
34
  ratio: number | undefined;
35
35
  /** 共享 NonceManager(用于统一协调 贿赂/利润提取 等 targetWallet 交易的 nonce,避免 nonce 冲突) */
36
36
  nonceManager: NonceManager;
37
+ /** 调用方指定的转账税;undefined 时多跳分支自行读取 */
38
+ transferTaxBps?: number;
37
39
  }
38
40
  /** 归集分支返回值(由主流程合并) */
39
41
  export interface SweepBranchResult {
@@ -16,7 +16,7 @@ import { sweepNativeNoHop } from './native-no-hop.js';
16
16
  import { sweepErc20NoHop } from './erc20-no-hop.js';
17
17
  import { sweepWithHops } from './with-hops.js';
18
18
  export async function sweepWithBundleMerkle(params) {
19
- const { sourcePrivateKeys, target, targetPrivateKey, ratioPct, ratios, amount, amounts, tokenAddress, tokenDecimals, skipIfInsufficient = true, hopCount = 0, hopPrivateKeys, sources, config, startNonce, } = params;
19
+ const { sourcePrivateKeys, target, targetPrivateKey, ratioPct, ratios, amount, amounts, tokenAddress, tokenDecimals, skipIfInsufficient = true, hopCount = 0, hopPrivateKeys, sources, config, startNonce, transferTaxBps, } = params;
20
20
  // 快速返回空结果
21
21
  if (!sourcePrivateKeys || sourcePrivateKeys.length === 0) {
22
22
  return {
@@ -119,6 +119,7 @@ export async function sweepWithBundleMerkle(params) {
119
119
  gasEstimated,
120
120
  ratio,
121
121
  nonceManager,
122
+ transferTaxBps,
122
123
  };
123
124
  const branch = !preparedHops
124
125
  ? isNative
@@ -7,8 +7,9 @@ import { getGasPriceConfig } from '../../config-helpers.js';
7
7
  import { calculateTransferFee, floorErc20TransferGasLimit, GAS_LIMITS } from '../../../core/constants/index.js';
8
8
  import { batchGetBalances as _batchGetBalances, batchGetTokenAndNativeBalances, getErc20Decimals as _getErc20Decimals, } from '../../internal.js';
9
9
  import { clampRatio } from './context.js';
10
+ import { amountAfterTransferTax, readTransferTaxBps } from '../swap-hop-helpers.js';
10
11
  export async function sweepWithHops(ctx, preparedHops) {
11
- const { provider, chainIdNum, txType, config, target, targetWallet, tokenAddress, tokenDecimals, skipIfInsufficient, isNative, extractProfit, profitAddr, actualKeys, sources, ratios, amounts, amount, finalGasLimit, nativeGasLimit, gasEstimated, ratio, } = ctx;
12
+ const { provider, chainIdNum, txType, config, target, targetWallet, tokenAddress, tokenDecimals, skipIfInsufficient, isNative, extractProfit, profitAddr, actualKeys, sources, ratios, amounts, amount, finalGasLimit, nativeGasLimit, gasEstimated, ratio, transferTaxBps: transferTaxBpsParam, } = ctx;
12
13
  const signedTxs = [];
13
14
  let totalProfit = 0n;
14
15
  let totalAmountBeforeProfit = 0n;
@@ -26,8 +27,8 @@ export async function sweepWithHops(ctx, preparedHops) {
26
27
  }
27
28
  }
28
29
  const sourceAddresses = sourceWallets.map((w) => w.address);
29
- // ✅ 优化:并行获取 gasPrice、decimals、余额
30
- const [gasPrice, decimals, paired] = await Promise.all([
30
+ // ✅ 优化:并行获取 gasPrice、decimals、余额、ERC20 转账税
31
+ const [gasPrice, decimals, paired, transferTaxBps] = await Promise.all([
31
32
  getOptimizedGasPrice(provider, getGasPriceConfig(config)),
32
33
  isNative
33
34
  ? Promise.resolve(18)
@@ -38,6 +39,9 @@ export async function sweepWithHops(ctx, preparedHops) {
38
39
  native: [],
39
40
  }))
40
41
  : batchGetTokenAndNativeBalances(provider, sourceAddresses, tokenAddress, chainIdNum),
42
+ isNative || !tokenAddress || transferTaxBpsParam !== undefined
43
+ ? Promise.resolve(transferTaxBpsParam ?? 0)
44
+ : readTransferTaxBps(provider, tokenAddress).catch(() => 0),
41
45
  ]);
42
46
  const balances = paired.token;
43
47
  const bnbBalances = paired.native;
@@ -283,6 +287,11 @@ export async function sweepWithHops(ctx, preparedHops) {
283
287
  },
284
288
  });
285
289
  // 第三步:中转钱包逐层传递(gas 和 ERC20)
290
+ // hopAmounts[j] = 第 j 个钱包实际收到、可以转出的数量(带税代币逐跳递减)
291
+ const hopAmounts = [toSend];
292
+ for (let j = 1; j < fullChain.length; j++) {
293
+ hopAmounts.push(amountAfterTransferTax(hopAmounts[j - 1], transferTaxBps));
294
+ }
286
295
  for (let j = 1; j < fullChain.length; j++) {
287
296
  const fromWallet = fullChain[j];
288
297
  const toAddress = addresses[j + 1]; // 下一个地址(可能是中转钱包或最终目标)
@@ -302,8 +311,8 @@ export async function sweepWithHops(ctx, preparedHops) {
302
311
  type: txType,
303
312
  },
304
313
  });
305
- // 再转 ERC20
306
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, toSend]);
314
+ // 再转 ERC20(只转上一跳实际到账的数量)
315
+ const erc20Data = iface.encodeFunctionData('transfer', [toAddress, hopAmounts[j]]);
307
316
  hopTxsToSign.push({
308
317
  wallet: fromWallet,
309
318
  tx: {
@@ -320,7 +329,7 @@ export async function sweepWithHops(ctx, preparedHops) {
320
329
  }
321
330
  else {
322
331
  // 最后一个中转钱包:只转 ERC20 给最终目标
323
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, toSend]);
332
+ const erc20Data = iface.encodeFunctionData('transfer', [toAddress, hopAmounts[j]]);
324
333
  hopTxsToSign.push({
325
334
  wallet: fromWallet,
326
335
  tx: {
@@ -7,6 +7,7 @@ import { ethers, Contract, Wallet } from 'ethers';
7
7
  import { calculateSellAmount } from '../../../utils/swap-helpers.js';
8
8
  import { NonceManager, buildProfitHopTransactions, PROFIT_HOP_COUNT, } from '../../../utils/bundle-helpers.js';
9
9
  import { ERC20_ABI } from '../../../abis/common.js';
10
+ import { signMissingAllowanceApprovals } from '../../../domains/dex/direct-router-approvals.js';
10
11
  import { BRIBE_GAS_LIMIT, FLAT_FEE, NATIVE_TRANSFER_GAS_LIMIT, PANCAKE_V2_ROUTER_ABI, PANCAKE_V2_ROUTER_ADDRESS, PANCAKE_V3_ROUTER_ABI, PANCAKE_V3_ROUTER_ADDRESS, WBNB_ADDRESS, buildBNBHopChainForERC20, buildERC20HopChain, buildNativeHopChain, calculateProfitAmount, createPancakeContext, generateDisperseHopPaths, getERC20ToNativeQuote, getGasPrice, grossUpPancakeSellProceedsToBuySide, quoteSellOutput, quoteBuyOutputs, applyPancakeSlippage, sequentialBuyAmountOutMins, taxedSellQuoteInput, resolvePancakeQuoteMode, } from './bundle-swap-helpers.js';
11
12
  /**
12
13
  * PancakeSwap 快捷批量换手(资金自动流转)
@@ -216,6 +217,23 @@ export async function pancakeQuickBatchSwapMerkle(params) {
216
217
  // ==================== 2. 卖出交易 ====================
217
218
  const v3RouterIface2 = new ethers.Interface(PANCAKE_V3_ROUTER_ABI);
218
219
  const quickV2Addr = config.v2RouterAddress || PANCAKE_V2_ROUTER_ADDRESS;
220
+ // 卖方对当前 Router 的代币授权不够时,同包在卖出前补 approve(换了 DEX 后旧授权不算数)
221
+ const sellSpender = routeParams.routeType === 'v2' ? quickV2Addr : PANCAKE_V3_ROUTER_ADDRESS;
222
+ const sellerAllowance = (await new Contract(tokenAddress, ERC20_ABI, context.provider).allowance(seller.address, sellSpender));
223
+ const approveNonces = [sellerNonce];
224
+ const sellApproveTxs = await signMissingAllowanceApprovals({
225
+ provider: context.provider,
226
+ wallets: [seller],
227
+ nonces: approveNonces,
228
+ tokenAddress,
229
+ spender: sellSpender,
230
+ amounts: [sellAmountWei],
231
+ allowances: [sellerAllowance],
232
+ txType,
233
+ gasPrice,
234
+ chainId: context.chainId,
235
+ });
236
+ sellerNonce = approveNonces[0];
219
237
  let sellUnsigned;
220
238
  if (routeParams.routeType === 'v2') {
221
239
  const { v2Path } = routeParams;
@@ -401,6 +419,7 @@ export async function pancakeQuickBatchSwapMerkle(params) {
401
419
  const signedTransactions = [];
402
420
  if (bribeTx)
403
421
  signedTransactions.push(bribeTx);
422
+ signedTransactions.push(...sellApproveTxs);
404
423
  signedTransactions.push(signedSell);
405
424
  signedTransactions.push(...transferTxs);
406
425
  signedTransactions.push(...signedBuys);
@@ -6,7 +6,7 @@ import { generateWallets } from '../../utils/wallet.js';
6
6
  import { NonceManager, getOptimizedGasPrice, buildProfitHopTransactions, PROFIT_HOP_COUNT } from '../../utils/bundle-helpers.js';
7
7
  import { BLOCKRAZOR_BUILDER_EOA, getProfitRecipient, getTransferFeePerAddress, } from '../../core/constants/index.js';
8
8
  import { getErrorMessageFromUnknown } from '../../core/index.js';
9
- import { DEFAULT_GAS_LIMIT, DEFAULT_GAS_PRICE_GWEI, DEFAULT_MAX_WALLETS_PER_BATCH_ERC20, DEFAULT_MAX_WALLETS_PER_BATCH_NATIVE, ERC20_APPROVE_GAS_LIMIT, GAS_BUFFER_MULTIPLIER, NATIVE_TRANSFER_GAS_LIMIT, buildDaoaasBuyTx, buildDisperseHopChainERC20, buildDisperseHopChainNative, buildERC20ApproveTx, buildFlapBuyTx, buildFourBuyTx, buildNativeTransferTx, buildV2BuyTx, buildV2BuyTxWithERC20, buildV3BuyTx, buildV3BuyTxWithERC20, calculateMaxWalletsPerBatch, chunkArray, generateDisperseHopPaths, getBaseTokenAddress, getRouterAddress, } from './holders-maker-helpers.js';
9
+ import { DEFAULT_GAS_LIMIT, DEFAULT_GAS_PRICE_GWEI, DEFAULT_MAX_WALLETS_PER_BATCH_ERC20, DEFAULT_MAX_WALLETS_PER_BATCH_NATIVE, ERC20_TRANSFER_GAS_LIMIT, GAS_BUFFER_MULTIPLIER, NATIVE_TRANSFER_GAS_LIMIT, buildDaoaasBuyTx, buildDisperseHopChainNative, buildERC20ApproveTx, buildFlapBuyTx, buildFourBuyTx, buildNativeTransferTx, buildV2BuyTx, buildV2BuyTxWithERC20, buildV3BuyTx, buildV3BuyTxWithERC20, calculateMaxWalletsPerBatch, chunkArray, generateDisperseHopPaths, getBaseTokenAddress, getRouterAddress, } from './holders-maker-helpers.js';
10
10
  function formatUnitsFixed(value, decimals, precision = 6) {
11
11
  const raw = ethers.formatUnits(value, decimals);
12
12
  const [intPart, fracPart = ''] = raw.split('.');
@@ -73,8 +73,8 @@ export async function holdersMaker(params) {
73
73
  if (isERC20Mode) {
74
74
  // ERC20 模式:解析购买金额(考虑精度)
75
75
  buyAmountWei = ethers.parseUnits(buyAmountPerHolder, baseTokenDecimals);
76
- // 只转够 gas:授权 + 买入两笔的 gasLimit × gasPrice(maxFee=gasPrice,节点预检按上限扣,不再额外翻倍)
77
- transferNativePerWallet = (ERC20_APPROVE_GAS_LIMIT + BigInt(gasLimit)) * gasPrice;
76
+ // 付款钱包代买,持有人不发交易;只留一次 ERC20 转账的 gas,供以后归集
77
+ transferNativePerWallet = ERC20_TRANSFER_GAS_LIMIT * gasPrice;
78
78
  // 获取 ERC20 地址
79
79
  erc20TokenAddress = getBaseTokenAddress(baseToken, chain, baseTokenAddress);
80
80
  }
@@ -83,6 +83,14 @@ export async function holdersMaker(params) {
83
83
  buyAmountWei = ethers.parseEther(buyAmountPerHolder);
84
84
  transferNativePerWallet = buyAmountWei + gasWithBuffer;
85
85
  }
86
+ // ERC20 模式:付款钱包对 Router 的授权不够时,在第 0 批买入前补一次无限授权
87
+ const erc20RouterAddress = isERC20Mode ? getRouterAddress(tradeType, chain, config.v2RouterAddress) : undefined;
88
+ let needPayerApprove = false;
89
+ if (isERC20Mode && erc20TokenAddress && erc20RouterAddress) {
90
+ const erc20 = new ethers.Contract(erc20TokenAddress, ['function allowance(address,address) view returns (uint256)'], provider);
91
+ const allowance = (await erc20.allowance(payer.address, erc20RouterAddress));
92
+ needPayerApprove = allowance < buyAmountWei * BigInt(holdersCount);
93
+ }
86
94
  // 4. 分批处理
87
95
  const walletBatches = chunkArray(newWallets, maxWalletsPerBatch);
88
96
  result.totalBatchCount = walletBatches.length;
@@ -115,11 +123,12 @@ export async function holdersMaker(params) {
115
123
  // XLayer: 分发 N + 买入后利润 1
116
124
  // BSC 原生模式(无多跳): 贿赂 1 + 分发 N + 利润 (PROFIT_HOP_COUNT + 1)
117
125
  // BSC 原生模式(有多跳H): 贿赂 1 + 分发首跳 N + 利润 (PROFIT_HOP_COUNT + 1)
118
- // BSC ERC20模式(无多跳): 贿赂 1 + 分发BNB N + 分发ERC20 N + 利润 (PROFIT_HOP_COUNT + 1)
126
+ // BSC ERC20模式: 贿赂 1 + [第 0 批授权 1] + 分发gas N + 代买 N + 利润 (PROFIT_HOP_COUNT + 1)
119
127
  const bribeCount = needBribe ? 1 : 0;
120
128
  const profitCount = needProfitHop ? PROFIT_HOP_COUNT + 1 : 1; // XLayer 只有 1 笔利润转账
129
+ const approveInBatch = needPayerApprove && batchIdx === 0;
121
130
  const payerNonceCount = isERC20Mode
122
- ? bribeCount + batch.length * 2 + profitCount
131
+ ? bribeCount + (approveInBatch ? 1 : 0) + batch.length * 2 + profitCount
123
132
  : bribeCount + batch.length + profitCount;
124
133
  const payerNonces = await nonceManager.getNextNonceBatch(payer, payerNonceCount);
125
134
  let payerNonceIdx = 0;
@@ -134,43 +143,28 @@ export async function holdersMaker(params) {
134
143
  // (2) 分发原生代币(支持多跳)
135
144
  for (let i = 0; i < batch.length; i++) {
136
145
  const path = batchPaths[i];
137
- const { signedTxs: hopTxs } = await buildDisperseHopChainNative(payer, path, transferNativePerWallet, gasPrice, chainId, txType, payerNonces[payerNonceIdx++], isERC20Mode);
146
+ const { signedTxs: hopTxs } = await buildDisperseHopChainNative(payer, path, transferNativePerWallet, gasPrice, chainId, txType, payerNonces[payerNonceIdx++]);
138
147
  signedTxs.push(...hopTxs);
139
148
  }
140
- // (3) ERC20 模式:分发 ERC20 代币(支持多跳)
141
- if (isERC20Mode && erc20TokenAddress) {
142
- for (let i = 0; i < batch.length; i++) {
143
- const path = batchPaths[i];
144
- const { signedTxs: hopTxs } = await buildDisperseHopChainERC20(payer, path, erc20TokenAddress, buyAmountWei, gasPrice, chainId, txType, payerNonces[payerNonceIdx++]);
145
- signedTxs.push(...hopTxs);
146
- }
147
- }
148
- // (4) ERC20 模式:授权交易(新钱包 nonce=0)
149
- if (isERC20Mode && erc20TokenAddress) {
150
- const routerAddress = getRouterAddress(tradeType, chain, config.v2RouterAddress);
151
- for (const newWallet of batch) {
152
- const buyerWallet = new Wallet(newWallet.privateKey, provider);
153
- const approveTx = await buildERC20ApproveTx(buyerWallet, erc20TokenAddress, routerAddress, ethers.MaxUint256, // 无限授权
154
- 0, // 新钱包 nonce=0
155
- gasPrice, chainId, txType);
156
- signedTxs.push(approveTx);
157
- }
149
+ // (3) ERC20 模式:付款钱包授权(只在第 0 批、且额度不够时)
150
+ if (approveInBatch && erc20TokenAddress && erc20RouterAddress) {
151
+ signedTxs.push(await buildERC20ApproveTx(payer, erc20TokenAddress, erc20RouterAddress, ethers.MaxUint256, payerNonces[payerNonceIdx++], gasPrice, chainId, txType));
158
152
  }
159
- // (5) 买入交易
160
- // 原生模式: nonce=0
161
- // ERC20模式: nonce=1(授权后)
162
- const buyNonce = isERC20Mode ? 1 : 0;
153
+ // (4) 买入交易
154
+ // 原生模式: 持有人自己买,nonce=0
155
+ // ERC20模式: 付款钱包代买,代币直接打到持有人地址
163
156
  for (const newWallet of batch) {
164
- const buyerWallet = new Wallet(newWallet.privateKey, provider);
157
+ const buyerWallet = isERC20Mode ? payer : new Wallet(newWallet.privateKey, provider);
158
+ const buyNonce = isERC20Mode ? payerNonces[payerNonceIdx++] : 0;
165
159
  let buyTx;
166
160
  if (isERC20Mode && erc20TokenAddress) {
167
- // ERC20 购买
161
+ // ERC20 购买:付款钱包付 USDT,代币打到持有人
168
162
  switch (tradeType) {
169
163
  case 'v2':
170
- buyTx = await buildV2BuyTxWithERC20(buyerWallet, tokenAddress, erc20TokenAddress, buyAmountWei, buyNonce, gasPrice, gasLimit, chainId, txType, config.v2RouterAddress, chain);
164
+ buyTx = await buildV2BuyTxWithERC20(buyerWallet, tokenAddress, erc20TokenAddress, buyAmountWei, buyNonce, gasPrice, gasLimit, chainId, txType, config.v2RouterAddress, chain, newWallet.address);
171
165
  break;
172
166
  case 'v3':
173
- buyTx = await buildV3BuyTxWithERC20(buyerWallet, tokenAddress, erc20TokenAddress, buyAmountWei, buyNonce, gasPrice, gasLimit, chainId, txType, config.v3Fee, chain);
167
+ buyTx = await buildV3BuyTxWithERC20(buyerWallet, tokenAddress, erc20TokenAddress, buyAmountWei, buyNonce, gasPrice, gasLimit, chainId, txType, config.v3Fee, chain, newWallet.address);
174
168
  break;
175
169
  default:
176
170
  throw new Error(`ERC20 模式不支持交易类型: ${tradeType}`);
@@ -292,8 +286,8 @@ export function estimateHoldersMakerCost(params) {
292
286
  const maxPerBatch = isERC20Mode ? DEFAULT_MAX_WALLETS_PER_BATCH_ERC20 : DEFAULT_MAX_WALLETS_PER_BATCH_NATIVE;
293
287
  const batchCount = Math.ceil(holdersCount / maxPerBatch);
294
288
  if (isERC20Mode) {
295
- // ERC20 模式:原生代币只用于 gas(与 holdersMaker 实际分发一致)
296
- const totalNativeCostWei = (ERC20_APPROVE_GAS_LIMIT + BigInt(gasLimit)) * gasPriceWei * BigInt(holdersCount);
289
+ // ERC20 模式:付款钱包代买(买入 gas 按上限预留)+ 每个持有人一次 ERC20 转账 gas
290
+ const totalNativeCostWei = (ERC20_TRANSFER_GAS_LIMIT + BigInt(gasLimit)) * gasPriceWei * BigInt(holdersCount);
297
291
  const totalERC20CostWei = buyAmountWei * BigInt(holdersCount);
298
292
  return {
299
293
  totalNativeCost: formatUnitsFixed(totalNativeCostWei, 18, 6),
@@ -1,7 +1,13 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { estimateHoldersMakerCost } from './holders-maker.js';
1
+ import { ethers } from 'ethers';
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+ import { estimateHoldersMakerCost, holdersMaker } from './holders-maker.js';
4
+ import { setProfitRecipients } from '../../core/constants/profit.js';
5
+ const MNEMONIC = 'test test test test test test test test test test test junk';
6
+ const TOKEN = '0x3240179d0304215b88422e134bf931549f2b07ae';
7
+ const USDT = '0x55d398326f99059fF775485246999027B3197955';
8
+ const UNISWAP_V2_ROUTER = '0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24';
3
9
  describe('estimateHoldersMakerCost', () => {
4
- it('USDT 模式每个 holder 只转授权 + 买入两笔 gasLimit × gasPrice', () => {
10
+ it('USDT 模式:付款钱包代买 gas + 每个持有人一次 ERC20 转账 gas', () => {
5
11
  const r = estimateHoldersMakerCost({
6
12
  holdersCount: 10,
7
13
  buyAmountPerHolder: '1',
@@ -9,8 +15,8 @@ describe('estimateHoldersMakerCost', () => {
9
15
  gasLimit: 800_000,
10
16
  gasPriceGwei: 3,
11
17
  });
12
- // (150000 + 800000) × 3 gwei × 10 = 0.0285 BNB
13
- expect(r.totalNativeCost).toBe('0.028500');
18
+ // (120000 + 800000) × 3 gwei × 10 = 0.0276 BNB
19
+ expect(r.totalNativeCost).toBe('0.027600');
14
20
  expect(r.totalERC20Cost).toBe('10.000000');
15
21
  });
16
22
  it('原生模式仍是买入金额 + 买入 gas 缓冲', () => {
@@ -25,3 +31,63 @@ describe('estimateHoldersMakerCost', () => {
25
31
  expect(r.totalNativeCost).toBe('0.014800');
26
32
  });
27
33
  });
34
+ describe('holdersMaker USDT 模式 (offline)', () => {
35
+ afterEach(() => {
36
+ setProfitRecipients([]);
37
+ vi.restoreAllMocks();
38
+ });
39
+ const run = async (payerAllowance) => {
40
+ setProfitRecipients(['0x70997970C51812dc3A010C7d01b50e0d17dc79C8']);
41
+ vi.spyOn(ethers.JsonRpcProvider.prototype, 'getFeeData').mockResolvedValue(new ethers.FeeData(ethers.parseUnits('0.05', 'gwei'), null, null));
42
+ vi.spyOn(ethers.JsonRpcProvider.prototype, 'getTransactionCount').mockResolvedValue(5);
43
+ vi.spyOn(ethers.JsonRpcProvider.prototype, 'call').mockResolvedValue(ethers.AbiCoder.defaultAbiCoder().encode(['uint256'], [payerAllowance]));
44
+ const payer = ethers.HDNodeWallet.fromPhrase(MNEMONIC, undefined, "m/44'/60'/0'/0/5");
45
+ const result = await holdersMaker({
46
+ payerPrivateKey: payer.privateKey,
47
+ holdersCount: 2,
48
+ buyAmountPerHolder: '1',
49
+ tokenAddress: TOKEN,
50
+ baseToken: 'usdt',
51
+ config: {
52
+ rpcUrl: 'http://127.0.0.1:8545',
53
+ chainId: 56,
54
+ chain: 'BSC',
55
+ tradeType: 'v2',
56
+ gasLimit: 800_000,
57
+ gasPriceGwei: 0.05,
58
+ v2RouterAddress: UNISWAP_V2_ROUTER,
59
+ },
60
+ });
61
+ expect(result.success).toBe(true);
62
+ const txs = result.signedTransactions.flat().map((raw) => ethers.Transaction.from(raw));
63
+ return { payer, txs, holders: result.newWallets.map((w) => w.address.toLowerCase()) };
64
+ };
65
+ it('持有人只收一次 ERC20 转账 gas,付款钱包代买并把代币打到持有人', async () => {
66
+ const { payer, txs, holders } = await run(0n);
67
+ const gasPrice = ethers.parseUnits('0.075', 'gwei'); // 链上 0.05 × 1.5
68
+ // 持有人自己不发任何交易
69
+ expect(txs.every((tx) => tx.from?.toLowerCase() === payer.address.toLowerCase() || !holders.includes(tx.from.toLowerCase()))).toBe(true);
70
+ const toHolders = txs.filter((tx) => holders.includes(String(tx.to).toLowerCase()));
71
+ expect(toHolders.map((tx) => tx.value)).toEqual(holders.map(() => 120000n * gasPrice));
72
+ // 授权不够:先 approve USDT 给 Uniswap Router
73
+ const approve = txs.find((tx) => tx.to?.toLowerCase() === USDT.toLowerCase());
74
+ const erc20 = new ethers.Interface(['function approve(address,uint256)']);
75
+ expect(approve?.from?.toLowerCase()).toBe(payer.address.toLowerCase());
76
+ expect(String(erc20.decodeFunctionData('approve', approve.data)[0]).toLowerCase()).toBe(UNISWAP_V2_ROUTER.toLowerCase());
77
+ const router = new ethers.Interface([
78
+ 'function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256,uint256,address[],address,uint256)',
79
+ ]);
80
+ const buys = txs.filter((tx) => tx.to?.toLowerCase() === UNISWAP_V2_ROUTER.toLowerCase());
81
+ expect(buys.length).toBe(2);
82
+ for (const [i, buy] of buys.entries()) {
83
+ expect(buy.from?.toLowerCase()).toBe(payer.address.toLowerCase());
84
+ const args = router.decodeFunctionData('swapExactTokensForTokensSupportingFeeOnTransferTokens', buy.data);
85
+ expect(String(args[3]).toLowerCase()).toBe(holders[i]);
86
+ expect(buy.nonce).toBeGreaterThan(approve.nonce);
87
+ }
88
+ });
89
+ it('付款钱包已授权时不再补授权', async () => {
90
+ const { txs } = await run(ethers.MaxUint256);
91
+ expect(txs.some((tx) => tx.to?.toLowerCase() === USDT.toLowerCase())).toBe(false);
92
+ });
93
+ });
@@ -34,11 +34,11 @@ chain?: HoldersMakerChain): Promise<string>;
34
34
  * 构建 V2 买入交易(ERC20 输入)
35
35
  * USDT/USDC → Token (使用 swapExactTokensForTokensSupportingFeeOnTransferTokens)
36
36
  */
37
- export declare function buildV2BuyTxWithERC20(wallet: Wallet, tokenAddress: string, baseTokenAddress: string, buyAmount: bigint, nonce: number, gasPrice: bigint, gasLimit: number, chainId: number, txType: 0 | 2, v2RouterOverride?: string, chain?: HoldersMakerChain): Promise<string>;
37
+ export declare function buildV2BuyTxWithERC20(wallet: Wallet, tokenAddress: string, baseTokenAddress: string, buyAmount: bigint, nonce: number, gasPrice: bigint, gasLimit: number, chainId: number, txType: 0 | 2, v2RouterOverride?: string, chain?: HoldersMakerChain, recipient?: string): Promise<string>;
38
38
  /**
39
39
  * 构建 V3 买入交易(ERC20 输入)
40
40
  * USDT/USDC → Token (使用 exactInputSingle + multicall)
41
41
  *
42
42
  * ✅ 修复:使用 ethers.Interface 手动编码 calldata,避免 multicall 重载问题
43
43
  */
44
- export declare function buildV3BuyTxWithERC20(wallet: Wallet, tokenAddress: string, baseTokenAddress: string, buyAmount: bigint, nonce: number, gasPrice: bigint, gasLimit: number, chainId: number, txType: 0 | 2, v3Fee?: number, chain?: HoldersMakerChain): Promise<string>;
44
+ export declare function buildV3BuyTxWithERC20(wallet: Wallet, tokenAddress: string, baseTokenAddress: string, buyAmount: bigint, nonce: number, gasPrice: bigint, gasLimit: number, chainId: number, txType: 0 | 2, v3Fee?: number, chain?: HoldersMakerChain, recipient?: string): Promise<string>;
@@ -211,14 +211,14 @@ chain) {
211
211
  * 构建 V2 买入交易(ERC20 输入)
212
212
  * USDT/USDC → Token (使用 swapExactTokensForTokensSupportingFeeOnTransferTokens)
213
213
  */
214
- export async function buildV2BuyTxWithERC20(wallet, tokenAddress, baseTokenAddress, buyAmount, nonce, gasPrice, gasLimit, chainId, txType, v2RouterOverride, chain) {
214
+ export async function buildV2BuyTxWithERC20(wallet, tokenAddress, baseTokenAddress, buyAmount, nonce, gasPrice, gasLimit, chainId, txType, v2RouterOverride, chain, recipient = wallet.address) {
215
215
  const path = [baseTokenAddress, tokenAddress];
216
216
  const deadline = getDeadline();
217
217
  const routerAddress = v2RouterOverride || getRouterAddress('v2', chain);
218
218
  const v2Router = new Contract(routerAddress, V2_ROUTER_ABI, wallet);
219
219
  const unsigned = await v2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens.populateTransaction(buyAmount, // amountIn
220
220
  0n, // amountOutMin(不设滑点保护)
221
- path, wallet.address, deadline);
221
+ path, recipient, deadline);
222
222
  const tx = {
223
223
  ...unsigned,
224
224
  nonce,
@@ -242,7 +242,7 @@ export async function buildV2BuyTxWithERC20(wallet, tokenAddress, baseTokenAddre
242
242
  *
243
243
  * ✅ 修复:使用 ethers.Interface 手动编码 calldata,避免 multicall 重载问题
244
244
  */
245
- export async function buildV3BuyTxWithERC20(wallet, tokenAddress, baseTokenAddress, buyAmount, nonce, gasPrice, gasLimit, chainId, txType, v3Fee = 2500, chain) {
245
+ export async function buildV3BuyTxWithERC20(wallet, tokenAddress, baseTokenAddress, buyAmount, nonce, gasPrice, gasLimit, chainId, txType, v3Fee = 2500, chain, recipient = wallet.address) {
246
246
  const deadline = getDeadline();
247
247
  const v3RouterIface = new ethers.Interface(V3_ROUTER02_ABI);
248
248
  // 构建 exactInputSingle calldata
@@ -250,7 +250,7 @@ export async function buildV3BuyTxWithERC20(wallet, tokenAddress, baseTokenAddre
250
250
  tokenIn: baseTokenAddress,
251
251
  tokenOut: tokenAddress,
252
252
  fee: v3Fee,
253
- recipient: wallet.address,
253
+ recipient,
254
254
  amountIn: buyAmount,
255
255
  amountOutMinimum: 0n,
256
256
  sqrtPriceLimitX96: 0n,
@@ -57,8 +57,9 @@ export function calculateMaxWalletsPerBatch(isERC20Mode, disperseHopCount, chain
57
57
  const fixedOverhead = isSimpleChain ? 1 : 1 + PROFIT_HOP_COUNT + 1;
58
58
  const maxTxs = 50 - fixedOverhead;
59
59
  if (isERC20Mode) {
60
- const perWalletTxs = 2 * (disperseHopCount + 1) + 2;
61
- return Math.floor(maxTxs / perWalletTxs);
60
+ // 付款钱包代买:每个持有人 = gas 转账链 + 一笔代买;第 0 批可能多一笔付款钱包授权
61
+ const perWalletTxs = disperseHopCount + 2;
62
+ return Math.floor((maxTxs - 1) / perWalletTxs);
62
63
  }
63
64
  const perWalletTxs = disperseHopCount + 2;
64
65
  return Math.floor(maxTxs / perWalletTxs);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "four-flap-meme-sdk",
3
- "version": "4.5.4",
3
+ "version": "4.5.5",
4
4
  "description": "SDK for Flap bonding curve and four.meme TokenManager",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",