four-flap-meme-sdk 2.0.0 → 2.2.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.
Files changed (220) hide show
  1. package/dist/__tests__/subpath-exports.test.js +64 -0
  2. package/dist/chains/bsc/iro.d.ts +5 -0
  3. package/dist/chains/bsc/iro.js +4 -0
  4. package/dist/chains/eni/flat-aliases.d.ts +10 -0
  5. package/dist/chains/eni/flat-aliases.js +8 -0
  6. package/dist/chains/eni/index.d.ts +1 -0
  7. package/dist/chains/eni/index.js +1 -0
  8. package/dist/chains/index.d.ts +13 -0
  9. package/dist/chains/index.js +13 -0
  10. package/dist/chains/xlayer/eip7702/flat-aliases.d.ts +13 -0
  11. package/dist/chains/xlayer/eip7702/flat-aliases.js +10 -0
  12. package/dist/chains/xlayer/eip7702/index.d.ts +1 -0
  13. package/dist/chains/xlayer/eip7702/index.js +1 -0
  14. package/dist/chains/xlayer/index.d.ts +3 -2
  15. package/dist/chains/xlayer/index.js +4 -7
  16. package/dist/flap/index.d.ts +10 -0
  17. package/dist/flap/index.js +8 -0
  18. package/dist/merkle/index.d.ts +12 -0
  19. package/dist/merkle/index.js +11 -0
  20. package/dist/shared/constants/index.d.ts +2 -0
  21. package/dist/shared/index.d.ts +2 -0
  22. package/dist/vanity/index.d.ts +5 -0
  23. package/dist/vanity/index.js +5 -0
  24. package/package.json +93 -2
  25. package/dist/chains/bsc/four/disperse.d.ts +0 -12
  26. package/dist/chains/bsc/four/disperse.js +0 -470
  27. package/dist/chains/bsc/four/pairwise.d.ts +0 -7
  28. package/dist/chains/bsc/four/pairwise.js +0 -308
  29. package/dist/chains/bsc/four/submit/blockrazor.d.ts +0 -18
  30. package/dist/chains/bsc/four/submit/blockrazor.js +0 -86
  31. package/dist/chains/bsc/four/submit/direct.d.ts +0 -66
  32. package/dist/chains/bsc/four/submit/direct.js +0 -452
  33. package/dist/chains/bsc/four/submit/helpers.d.ts +0 -18
  34. package/dist/chains/bsc/four/submit/helpers.js +0 -57
  35. package/dist/chains/bsc/four/submit/index.d.ts +0 -12
  36. package/dist/chains/bsc/four/submit/index.js +0 -11
  37. package/dist/chains/bsc/four/submit/merkle.d.ts +0 -18
  38. package/dist/chains/bsc/four/submit/merkle.js +0 -74
  39. package/dist/chains/bsc/four/submit/types.d.ts +0 -143
  40. package/dist/chains/bsc/four/swap/index.d.ts +0 -32
  41. package/dist/chains/bsc/four/swap/index.js +0 -829
  42. package/dist/chains/bsc/four/swap/types.d.ts +0 -70
  43. package/dist/chains/bsc/four/swap/types.js +0 -1
  44. package/dist/chains/bsc/four/sweep.d.ts +0 -13
  45. package/dist/chains/bsc/four/sweep.js +0 -788
  46. package/dist/chains/bsc/four/utils/index.d.ts +0 -20
  47. package/dist/chains/bsc/four/utils/index.js +0 -1558
  48. package/dist/chains/bsc/four/utils/types.d.ts +0 -1
  49. package/dist/chains/bsc/four/utils/types.js +0 -1
  50. package/dist/chains/bsc/pancake/bundle-buy-first/index.d.ts +0 -8
  51. package/dist/chains/bsc/pancake/bundle-buy-first/index.js +0 -907
  52. package/dist/chains/bsc/pancake/bundle-buy-first/types.d.ts +0 -73
  53. package/dist/chains/bsc/pancake/bundle-buy-first/types.js +0 -1
  54. package/dist/chains/bsc/pancake/bundle-swap/helpers.d.ts +0 -102
  55. package/dist/chains/bsc/pancake/bundle-swap/helpers.js +0 -572
  56. package/dist/chains/bsc/pancake/bundle-swap/index.d.ts +0 -50
  57. package/dist/chains/bsc/pancake/bundle-swap/index.js +0 -1066
  58. package/dist/chains/bsc/pancake/bundle-swap/types.d.ts +0 -202
  59. package/dist/chains/bsc/pancake/bundle-swap/types.js +0 -3
  60. package/dist/chains/xlayer/eip7702/bundle-swap/index.d.ts +0 -72
  61. package/dist/chains/xlayer/eip7702/bundle-swap/index.js +0 -921
  62. package/dist/chains/xlayer/eip7702/bundle-swap/types.d.ts +0 -65
  63. package/dist/chains/xlayer/eip7702/bundle-swap/types.js +0 -1
  64. package/dist/chains/xlayer/eip7702/multi-hop-transfer/index.d.ts +0 -128
  65. package/dist/chains/xlayer/eip7702/multi-hop-transfer/index.js +0 -857
  66. package/dist/chains/xlayer/eip7702/multi-hop-transfer/types.d.ts +0 -85
  67. package/dist/chains/xlayer/eip7702/multi-hop-transfer/types.js +0 -1
  68. package/dist/chains/xlayer/eip7702/volume/index.d.ts +0 -96
  69. package/dist/chains/xlayer/eip7702/volume/index.js +0 -793
  70. package/dist/chains/xlayer/eip7702/volume/types.d.ts +0 -124
  71. package/dist/chains/xlayer/eip7702/volume/types.js +0 -1
  72. package/dist/chains/xlayer/eoa/types-core.d.ts +0 -363
  73. package/dist/chains/xlayer/eoa/types-core.js +0 -53
  74. package/dist/chains/xlayer/eoa/types-create.d.ts +0 -413
  75. package/dist/chains/xlayer/eoa/types-create.js +0 -9
  76. package/dist/chains/xlayer/eoa/types-volume.d.ts +0 -209
  77. package/dist/chains/xlayer/eoa/types-volume.js +0 -13
  78. package/dist/dex/direct-router/index.d.ts +0 -70
  79. package/dist/dex/direct-router/index.js +0 -1410
  80. package/dist/dex/direct-router/types.d.ts +0 -81
  81. package/dist/dex/direct-router/types.js +0 -1
  82. package/dist/shared/abis/TaxToken.json +0 -969
  83. package/dist/shared/abis/TokenManager.json +0 -836
  84. package/dist/shared/abis/TokenManager2.json +0 -136
  85. package/dist/shared/abis/TokenManagerHelper3.json +0 -993
  86. package/dist/shared/abis 2/TaxToken.json +0 -105
  87. package/dist/shared/abis 2/TokenManager.json +0 -836
  88. package/dist/shared/abis 2/TokenManager2.json +0 -60
  89. package/dist/shared/abis 2/TokenManagerHelper3.json +0 -993
  90. package/dist/shared/abis 2/common.d.ts +0 -85
  91. package/dist/shared/abis 2/common.js +0 -254
  92. package/dist/shared/abis 2/index.d.ts +0 -8
  93. package/dist/shared/abis 2/index.js +0 -8
  94. package/dist/shared/clients 2/blockrazor.d.ts +0 -314
  95. package/dist/shared/clients 2/blockrazor.js +0 -596
  96. package/dist/shared/clients 2/club48.d.ts +0 -154
  97. package/dist/shared/clients 2/club48.js +0 -331
  98. package/dist/shared/clients 2/emitservice.d.ts +0 -47
  99. package/dist/shared/clients 2/emitservice.js +0 -44
  100. package/dist/shared/clients 2/four.d.ts +0 -132
  101. package/dist/shared/clients 2/four.js +0 -281
  102. package/dist/shared/clients 2/merkle.d.ts +0 -210
  103. package/dist/shared/clients 2/merkle.js +0 -400
  104. package/dist/shared/flap/__tests__/curve.test.d.ts +0 -1
  105. package/dist/shared/flap/__tests__/curve.test.js +0 -85
  106. package/dist/shared/flap/portal/index.d.ts +0 -12
  107. package/dist/shared/flap/portal/index.js +0 -11
  108. package/dist/shared/flap/portal/portal.d.ts +0 -47
  109. package/dist/shared/flap/portal/portal.js +0 -218
  110. package/dist/shared/flap/portal/types.d.ts +0 -227
  111. package/dist/shared/flap/portal/types.js +0 -80
  112. package/dist/shared/flap/portal/writer.d.ts +0 -121
  113. package/dist/shared/flap/portal/writer.js +0 -265
  114. package/dist/shared/flap/portal-bundle-merkle/core/index.d.ts +0 -18
  115. package/dist/shared/flap/portal-bundle-merkle/core/index.js +0 -938
  116. package/dist/shared/flap/portal-bundle-merkle/core/types.d.ts +0 -1
  117. package/dist/shared/flap/portal-bundle-merkle/core/types.js +0 -1
  118. package/dist/shared/flap/portal-bundle-merkle/swap/index.d.ts +0 -42
  119. package/dist/shared/flap/portal-bundle-merkle/swap/index.js +0 -1448
  120. package/dist/shared/flap/portal-bundle-merkle/swap/types.d.ts +0 -84
  121. package/dist/shared/flap/portal-bundle-merkle/swap/types.js +0 -1
  122. package/dist/shared/flap/portal-bundle-merkle/utils/index.d.ts +0 -17
  123. package/dist/shared/flap/portal-bundle-merkle/utils/index.js +0 -1024
  124. package/dist/shared/flap/portal-bundle-merkle/utils/types.d.ts +0 -16
  125. package/dist/shared/flap/portal-bundle-merkle/utils/types.js +0 -1
  126. package/dist/shared/flap/portal-bundle-merkle/utils-helpers.d.ts +0 -100
  127. package/dist/shared/flap/portal-bundle-merkle/utils-helpers.js +0 -133
  128. package/dist/shared/flap 2/__tests__/curve.test.d.ts +0 -1
  129. package/dist/shared/flap 2/__tests__/curve.test.js +0 -85
  130. package/dist/shared/flap 2/abi.d.ts +0 -4
  131. package/dist/shared/flap 2/abi.js +0 -4
  132. package/dist/shared/flap 2/constants.d.ts +0 -128
  133. package/dist/shared/flap 2/constants.js +0 -143
  134. package/dist/shared/flap 2/curve.d.ts +0 -33
  135. package/dist/shared/flap 2/curve.js +0 -84
  136. package/dist/shared/flap 2/errors.d.ts +0 -37
  137. package/dist/shared/flap 2/errors.js +0 -114
  138. package/dist/shared/flap 2/index.d.ts +0 -22
  139. package/dist/shared/flap 2/index.js +0 -33
  140. package/dist/shared/flap 2/ipfs.d.ts +0 -21
  141. package/dist/shared/flap 2/ipfs.js +0 -38
  142. package/dist/shared/flap 2/meta.d.ts +0 -30
  143. package/dist/shared/flap 2/meta.js +0 -195
  144. package/dist/shared/flap 2/permit.d.ts +0 -16
  145. package/dist/shared/flap 2/permit.js +0 -67
  146. package/dist/shared/flap 2/pinata.d.ts +0 -40
  147. package/dist/shared/flap 2/pinata.js +0 -106
  148. package/dist/shared/flap 2/portal-bundle-merkle/config.d.ts +0 -79
  149. package/dist/shared/flap 2/portal-bundle-merkle/config.js +0 -133
  150. package/dist/shared/flap 2/portal-bundle-merkle/core.d.ts +0 -18
  151. package/dist/shared/flap 2/portal-bundle-merkle/core.js +0 -938
  152. package/dist/shared/flap 2/portal-bundle-merkle/create-to-dex.d.ts +0 -125
  153. package/dist/shared/flap 2/portal-bundle-merkle/create-to-dex.js +0 -665
  154. package/dist/shared/flap 2/portal-bundle-merkle/curve-to-dex.d.ts +0 -88
  155. package/dist/shared/flap 2/portal-bundle-merkle/curve-to-dex.js +0 -446
  156. package/dist/shared/flap 2/portal-bundle-merkle/index.d.ts +0 -14
  157. package/dist/shared/flap 2/portal-bundle-merkle/index.js +0 -26
  158. package/dist/shared/flap 2/portal-bundle-merkle/pancake-proxy.d.ts +0 -28
  159. package/dist/shared/flap 2/portal-bundle-merkle/pancake-proxy.js +0 -701
  160. package/dist/shared/flap 2/portal-bundle-merkle/private.d.ts +0 -17
  161. package/dist/shared/flap 2/portal-bundle-merkle/private.js +0 -549
  162. package/dist/shared/flap 2/portal-bundle-merkle/swap-buy-first.d.ts +0 -65
  163. package/dist/shared/flap 2/portal-bundle-merkle/swap-buy-first.js +0 -831
  164. package/dist/shared/flap 2/portal-bundle-merkle/swap.d.ts +0 -201
  165. package/dist/shared/flap 2/portal-bundle-merkle/swap.js +0 -1359
  166. package/dist/shared/flap 2/portal-bundle-merkle/types.d.ts +0 -358
  167. package/dist/shared/flap 2/portal-bundle-merkle/types.js +0 -1
  168. package/dist/shared/flap 2/portal-bundle-merkle/utils.d.ts +0 -89
  169. package/dist/shared/flap 2/portal-bundle-merkle/utils.js +0 -963
  170. package/dist/shared/flap 2/portal-bundle.d.ts +0 -119
  171. package/dist/shared/flap 2/portal-bundle.js +0 -584
  172. package/dist/shared/flap 2/portal.d.ts +0 -392
  173. package/dist/shared/flap 2/portal.js +0 -559
  174. package/dist/shared/flap 2/vanity.d.ts +0 -48
  175. package/dist/shared/flap 2/vanity.js +0 -110
  176. package/dist/shared/flap 2/vault.d.ts +0 -240
  177. package/dist/shared/flap 2/vault.js +0 -366
  178. package/dist/shared/four 2/index.d.ts +0 -7
  179. package/dist/shared/four 2/index.js +0 -22
  180. package/dist/shared/four 2/tax-token.d.ts +0 -176
  181. package/dist/shared/four 2/tax-token.js +0 -302
  182. package/dist/shared/index 2.js +0 -10
  183. package/dist/shared/index.d 2.ts +0 -10
  184. package/dist/types/distribute.d.ts +0 -72
  185. package/dist/types/distribute.js +0 -1
  186. package/dist/types 2/errors.d.ts +0 -27
  187. package/dist/types 2/errors.js +0 -34
  188. package/dist/utils/__tests__/errors.test.d.ts +0 -1
  189. package/dist/utils/__tests__/errors.test.js +0 -76
  190. package/dist/utils/airdrop-sweep-types.d.ts +0 -1
  191. package/dist/utils/airdrop-sweep-types.js +0 -1
  192. package/dist/utils/erc20/index.d.ts +0 -242
  193. package/dist/utils/erc20/index.js +0 -645
  194. package/dist/utils/erc20/types.d.ts +0 -77
  195. package/dist/utils/erc20/types.js +0 -1
  196. package/dist/utils/erc20-types.d.ts +0 -1
  197. package/dist/utils/erc20-types.js +0 -1
  198. package/dist/utils/holders-maker/helpers.d.ts +0 -43
  199. package/dist/utils/holders-maker/helpers.js +0 -371
  200. package/dist/utils/holders-maker/index.d.ts +0 -26
  201. package/dist/utils/holders-maker/index.js +0 -218
  202. package/dist/utils/holders-maker/types.d.ts +0 -72
  203. package/dist/utils/holders-maker/types.js +0 -4
  204. package/dist/utils/holders-maker-types.d.ts +0 -1
  205. package/dist/utils/holders-maker-types.js +0 -1
  206. package/dist/utils/lp-inspect/index.d.ts +0 -44
  207. package/dist/utils/lp-inspect/index.js +0 -937
  208. package/dist/utils/lp-inspect/types.d.ts +0 -100
  209. package/dist/utils/lp-inspect/types.js +0 -1
  210. package/dist/utils/lp-inspect-types.d.ts +0 -1
  211. package/dist/utils/lp-inspect-types.js +0 -1
  212. package/dist/utils/private-sale-types.d.ts +0 -1
  213. package/dist/utils/private-sale-types.js +0 -1
  214. package/dist/utils/quote-helpers/index.d.ts +0 -107
  215. package/dist/utils/quote-helpers/index.js +0 -346
  216. package/dist/utils/quote-helpers/types.d.ts +0 -16
  217. package/dist/utils/quote-helpers/types.js +0 -1
  218. package/dist/utils/quote-helpers-types.d.ts +0 -1
  219. package/dist/utils/quote-helpers-types.js +0 -1
  220. /package/dist/{chains/bsc/four/submit/types.js → __tests__/subpath-exports.test.d.ts} +0 -0
@@ -1,1558 +0,0 @@
1
- import { ethers, Wallet } from 'ethers';
2
- import { getOptimizedGasPrice, NonceManager, buildProfitHopTransactions, PROFIT_HOP_COUNT, buildGasFields } from '../../../../utils/bundle-helpers.js';
3
- import { BLOCKRAZOR_BUILDER_EOA, calculateTransferFee } from '../../../../utils/constants.js';
4
- import { GAS_LIMITS, CHAINS } from '../../../../shared/constants/index.js';
5
- import { getTxType, getGasPriceConfig, shouldExtractProfit, getProfitRecipient, getBribeAmount } from '../config.js';
6
- // ==================== Gas 常量(使用统一常量) ====================
7
- const NATIVE_TRANSFER_GAS_LIMIT = GAS_LIMITS.NATIVE_TRANSFER;
8
- const ERC20_TRANSFER_GAS_LIMIT = GAS_LIMITS.ERC20_TRANSFER;
9
- const BRIBE_GAS_LIMIT = GAS_LIMITS.BRIBE;
10
- const PROFIT_HOP_GAS_LIMIT = GAS_LIMITS.NATIVE_TRANSFER; // 利润多跳使用 NATIVE_TRANSFER
11
- import { getErc20DecimalsMerkle as _getErc20DecimalsMerkle, generateHopWallets as _generateHopWallets, normalizeAmounts as _normalizeAmounts, batchGetBalances as _batchGetBalances, calculateGasLimit as _calculateGasLimit, isNativeTokenAddress as _isNativeTokenAddress } from '../internal.js';
12
- // ==================== 钱包转账按地址收费 ====================
13
- /**
14
- * 分发(仅签名版本 - 不依赖 Merkle)
15
- * ✅ 精简版:只负责签名交易,不提交到 Merkle
16
- * ✅ 优化版:支持 startNonce 参数避免并行调用时的 nonce 冲突
17
- */
18
- export async function disperseWithBundleMerkle(params) {
19
- const { fromPrivateKey, recipients, amount, amounts, tokenAddress, tokenDecimals, hopCount = 0, hopPrivateKeys, items, config, startNonce } = params;
20
- // 快速返回空结果
21
- if (!recipients || recipients.length === 0) {
22
- return {
23
- signedTransactions: [],
24
- hopWallets: undefined
25
- };
26
- }
27
- // 初始化
28
- const chainIdNum = config.chainId ?? CHAINS.BSC.chainId;
29
- const chainName = chainIdNum === CHAINS.MONAD.chainId ? 'Monad' : chainIdNum === CHAINS.BSC.chainId ? 'BSC' : `Chain-${chainIdNum}`;
30
- const provider = new ethers.JsonRpcProvider(config.rpcUrl, {
31
- chainId: chainIdNum,
32
- name: chainName
33
- });
34
- const mainWallet = new Wallet(fromPrivateKey, provider);
35
- const isNative = _isNativeTokenAddress(tokenAddress);
36
- const txType = getTxType(config);
37
- // ✅ 优化:预处理数据(不需要 RPC)
38
- const normalizedAmounts = items && items.length > 0
39
- ? items.map(it => (typeof it.amount === 'bigint' ? it.amount.toString() : String(it.amount)))
40
- : _normalizeAmounts(recipients, amount, amounts);
41
- const providedHops = (() => {
42
- if (hopPrivateKeys && hopPrivateKeys.length > 0) {
43
- if (hopPrivateKeys.length !== recipients.length) {
44
- throw new Error(`hopPrivateKeys length (${hopPrivateKeys.length}) must match recipients length (${recipients.length})`);
45
- }
46
- return hopPrivateKeys.every(h => h.length === 0) ? null : hopPrivateKeys;
47
- }
48
- if (items && items.length > 0) {
49
- const hops = items.map(it => it.hopPrivateKeys ?? []);
50
- return hops.every(h => h.length === 0) ? null : hops;
51
- }
52
- return null;
53
- })();
54
- const hopCountInput = (() => {
55
- if (items && items.length > 0) {
56
- const baseArray = Array.isArray(hopCount) ? hopCount : new Array(recipients.length).fill(hopCount);
57
- return items.map((it, i) => (typeof it.hopCount === 'number' ? it.hopCount : (baseArray[i] ?? 0)));
58
- }
59
- return hopCount;
60
- })();
61
- const preparedHops = providedHops ?? _generateHopWallets(recipients.length, hopCountInput);
62
- const hasHops = preparedHops !== null;
63
- const maxHopCount = hasHops ? Math.max(...preparedHops.map(h => h.length)) : 0;
64
- const finalGasLimit = _calculateGasLimit(config, isNative, hasHops, maxHopCount);
65
- const nativeGasLimit = (config.prefer21000ForNative ?? false) ? BRIBE_GAS_LIMIT : finalGasLimit;
66
- const signedTxs = [];
67
- const extractProfit = shouldExtractProfit(config);
68
- const profitAddr = getProfitRecipient();
69
- let totalProfit = 0n;
70
- let totalAmountBeforeProfit = 0n;
71
- let profitHopWallets; // ✅ 收集利润多跳钱包
72
- // ✅ 优化:并行获取 gasPrice 和 nonces(或使用传入的 startNonce)
73
- const nonceManager = new NonceManager(provider);
74
- if (!preparedHops) {
75
- // ========== 无多跳:直接批量转账 ==========
76
- // ✅ BSC 链贿赂支持
77
- const bribeAmount = chainIdNum === CHAINS.BSC.chainId ? getBribeAmount(config) : 0n;
78
- const needBribeTx = bribeAmount > 0n;
79
- const extraTxCount = (extractProfit ? 1 : 0) + (needBribeTx ? 1 : 0);
80
- const totalTxCount = recipients.length + extraTxCount;
81
- // ✅ 优化:并行获取 gasPrice 和 nonces
82
- const [gasPrice, nonces] = await Promise.all([
83
- getOptimizedGasPrice(provider, getGasPriceConfig(config)),
84
- startNonce !== undefined
85
- ? Promise.resolve(Array.from({ length: totalTxCount }, (_, i) => startNonce + i))
86
- : nonceManager.getNextNonceBatch(mainWallet, totalTxCount)
87
- ]);
88
- // ✅ 贿赂交易放在最前面
89
- let nonceOffset = 0;
90
- if (needBribeTx) {
91
- const bribeTx = await mainWallet.signTransaction({
92
- to: BLOCKRAZOR_BUILDER_EOA,
93
- value: bribeAmount,
94
- nonce: nonces[nonceOffset++],
95
- gasPrice,
96
- gasLimit: BRIBE_GAS_LIMIT,
97
- chainId: chainIdNum,
98
- type: txType
99
- });
100
- signedTxs.push(bribeTx);
101
- console.log(`[disperse] 贿赂交易已添加: ${ethers.formatEther(bribeAmount)} BNB`);
102
- }
103
- if (isNative) {
104
- // ✅ 原生币:按地址数量收取固定费用,全额转账
105
- if (extractProfit) {
106
- totalProfit = calculateTransferFee(chainIdNum, recipients.length);
107
- console.log(`[disperse Native] 按地址收费: ${recipients.length} 个地址 × ${ethers.formatEther(calculateTransferFee(chainIdNum, 1))} = ${ethers.formatEther(totalProfit)} 原生币`);
108
- }
109
- const txDataList = recipients.map((to, i) => {
110
- const originalAmount = ethers.parseEther(normalizedAmounts[i]);
111
- totalAmountBeforeProfit += originalAmount;
112
- return { to, value: originalAmount, nonce: nonces[nonceOffset + i] };
113
- });
114
- // ✅ 并行签名所有交易
115
- const txPromises = txDataList.map(({ to, value, nonce }) => mainWallet.signTransaction({
116
- to,
117
- value,
118
- nonce,
119
- gasPrice,
120
- gasLimit: nativeGasLimit,
121
- chainId: chainIdNum,
122
- type: txType
123
- }));
124
- signedTxs.push(...(await Promise.all(txPromises)));
125
- // ✅ 利润多跳转账(强制 2 跳中转)
126
- if (extractProfit && totalProfit > 0n) {
127
- const profitHopResult = await buildProfitHopTransactions({
128
- provider,
129
- payerWallet: mainWallet,
130
- profitAmount: totalProfit,
131
- profitRecipient: profitAddr,
132
- hopCount: PROFIT_HOP_COUNT,
133
- gasPrice,
134
- chainId: chainIdNum,
135
- txType,
136
- startNonce: nonces[nonceOffset + recipients.length]
137
- });
138
- signedTxs.push(...profitHopResult.signedTransactions);
139
- profitHopWallets = profitHopResult.hopWallets; // ✅ 收集利润多跳钱包
140
- }
141
- }
142
- else {
143
- // ✅ ERC20:并行获取 decimals(传入 chainIdNum 避免 NETWORK_ERROR)
144
- const decimals = tokenDecimals ?? (await _getErc20DecimalsMerkle(provider, tokenAddress, chainIdNum));
145
- const iface = new ethers.Interface(['function transfer(address,uint256) returns (bool)']);
146
- // ✅ 先计算所有原始金额
147
- const originalAmounts = [];
148
- for (let i = 0; i < recipients.length; i++) {
149
- const originalAmount = ethers.parseUnits(normalizedAmounts[i], decimals);
150
- originalAmounts.push(originalAmount);
151
- totalAmountBeforeProfit += originalAmount;
152
- }
153
- // ✅ 按地址数量收取固定费用(原生代币)
154
- let nativeProfitAmount = 0n;
155
- if (extractProfit) {
156
- nativeProfitAmount = calculateTransferFee(chainIdNum, recipients.length);
157
- totalProfit = nativeProfitAmount;
158
- console.log(`[disperse ERC20] 按地址收费: ${recipients.length} 个地址 × ${ethers.formatEther(calculateTransferFee(chainIdNum, 1))} = ${ethers.formatEther(nativeProfitAmount)} 原生币`);
159
- }
160
- // ✅ ERC20 全额分发,费用以原生币单独支付
161
- const txDataList = recipients.map((to, i) => {
162
- const originalAmount = originalAmounts[i];
163
- const data = iface.encodeFunctionData('transfer', [to, originalAmount]);
164
- return { data, nonce: nonces[nonceOffset + i] };
165
- });
166
- // ✅ 并行签名所有交易
167
- const txPromises = txDataList.map(({ data, nonce }) => mainWallet.signTransaction({
168
- to: tokenAddress,
169
- data,
170
- value: 0n,
171
- nonce,
172
- gasPrice,
173
- gasLimit: finalGasLimit,
174
- chainId: chainIdNum,
175
- type: txType
176
- }));
177
- signedTxs.push(...(await Promise.all(txPromises)));
178
- // ✅ 费用多跳转账(强制 2 跳中转)
179
- if (extractProfit && nativeProfitAmount > 0n) {
180
- const profitHopResult = await buildProfitHopTransactions({
181
- provider,
182
- payerWallet: mainWallet,
183
- profitAmount: nativeProfitAmount,
184
- profitRecipient: profitAddr,
185
- hopCount: PROFIT_HOP_COUNT,
186
- gasPrice,
187
- chainId: chainIdNum,
188
- txType,
189
- startNonce: nonces[nonceOffset + recipients.length]
190
- });
191
- signedTxs.push(...profitHopResult.signedTransactions);
192
- profitHopWallets = profitHopResult.hopWallets; // ✅ 收集利润多跳钱包
193
- console.log(`[disperse ERC20] 利润多跳已添加: ${ethers.formatEther(nativeProfitAmount)} 原生币`);
194
- }
195
- }
196
- }
197
- else {
198
- // ========== 有多跳:构建跳转链 ==========
199
- // ✅ BSC 链贿赂支持
200
- const bribeAmountHop = chainIdNum === CHAINS.BSC.chainId ? getBribeAmount(config) : 0n;
201
- const needBribeTxHop = bribeAmountHop > 0n;
202
- // ✅ 优化:并行获取 gasPrice 和 decimals
203
- const [gasPrice, decimals] = await Promise.all([
204
- getOptimizedGasPrice(provider, getGasPriceConfig(config)),
205
- isNative ? Promise.resolve(18) : Promise.resolve(tokenDecimals ?? await _getErc20DecimalsMerkle(provider, tokenAddress, chainIdNum))
206
- ]);
207
- const iface = isNative ? null : new ethers.Interface(['function transfer(address,uint256) returns (bool)']);
208
- // ✅ Gas limit 设置(与 swap.ts 保持一致)
209
- // - 原生代币转账:使用 GAS_LIMITS.NATIVE_TRANSFER(固定)
210
- // - ERC20 转账:使用 GAS_LIMITS.ERC20_TRANSFER(固定,因为 gas 波动较大)
211
- const nativeTransferGasLimit = NATIVE_TRANSFER_GAS_LIMIT;
212
- const erc20TransferGasLimit = GAS_LIMITS.ERC20_TRANSFER;
213
- // ✅ 原生代币多跳的 gas 费(每跳需要 21055)
214
- const nativeHopGasFee = nativeTransferGasLimit * gasPrice;
215
- // ✅ ERC20 多跳时,中转钱包需要执行 2 笔交易(转 gas + 转 ERC20)
216
- const erc20HopGasFee = erc20TransferGasLimit * gasPrice;
217
- const nativeHopGasFeeForErc20 = nativeTransferGasLimit * gasPrice;
218
- // ✅ 优化:预先计算主钱包需要的总 nonce 数量
219
- // - 原生代币多跳:主钱包只需要 1 个 nonce(一笔转账包含后续所有 gas)
220
- // - ERC20 多跳:主钱包需要 2 个 nonce(转 gas + 转 ERC20)
221
- let mainWalletNonceCount = 0;
222
- // 贿赂交易需要 1 个额外的 nonce
223
- if (needBribeTxHop)
224
- mainWalletNonceCount += 1;
225
- for (let i = 0; i < recipients.length; i++) {
226
- const hopChain = preparedHops[i];
227
- if (hopChain.length === 0) {
228
- // 无跳转:1 个 nonce
229
- mainWalletNonceCount += 1;
230
- }
231
- else {
232
- // 有跳转:
233
- // - Native: 1(一笔转账)
234
- // - ERC20: 2(转 gas + 转 ERC20)
235
- mainWalletNonceCount += isNative ? 1 : 2;
236
- }
237
- }
238
- // 利润交易需要额外 1 个 nonce
239
- if (extractProfit)
240
- mainWalletNonceCount += 1;
241
- // ✅ 一次性获取所有主钱包的 nonces
242
- const allMainNonces = startNonce !== undefined
243
- ? Array.from({ length: mainWalletNonceCount }, (_, i) => startNonce + i)
244
- : await nonceManager.getNextNonceBatch(mainWallet, mainWalletNonceCount);
245
- let mainNonceIdx = 0;
246
- // ✅ 贿赂交易放在最前面(多跳场景)
247
- if (needBribeTxHop) {
248
- const bribeTx = await mainWallet.signTransaction({
249
- to: BLOCKRAZOR_BUILDER_EOA,
250
- value: bribeAmountHop,
251
- nonce: allMainNonces[mainNonceIdx++],
252
- gasPrice,
253
- gasLimit: BRIBE_GAS_LIMIT,
254
- chainId: chainIdNum,
255
- type: txType
256
- });
257
- signedTxs.push(bribeTx);
258
- console.log(`[disperse with hops] 贿赂交易已添加: ${ethers.formatEther(bribeAmountHop)} BNB`);
259
- }
260
- // ✅ 优化:预先计算所有交易数据,然后并行签名
261
- const txsToSign = [];
262
- // ✅ 按地址数量收取固定费用(原生代币),不再扣除转账金额
263
- if (extractProfit) {
264
- totalProfit = calculateTransferFee(chainIdNum, recipients.length);
265
- console.log(`[disperse with hops] 按地址收费: ${recipients.length} 个地址 × ${ethers.formatEther(calculateTransferFee(chainIdNum, 1))} = ${ethers.formatEther(totalProfit)} 原生币`);
266
- }
267
- for (let i = 0; i < recipients.length; i++) {
268
- const finalRecipient = recipients[i];
269
- const originalAmountWei = isNative
270
- ? ethers.parseEther(normalizedAmounts[i])
271
- : ethers.parseUnits(normalizedAmounts[i], decimals);
272
- totalAmountBeforeProfit += originalAmountWei;
273
- const amountWei = originalAmountWei; // 全额转账
274
- const hopChain = preparedHops[i];
275
- if (hopChain.length === 0) {
276
- // 无跳转:直接转账
277
- const nonce = allMainNonces[mainNonceIdx++];
278
- if (isNative) {
279
- txsToSign.push({
280
- wallet: mainWallet,
281
- tx: {
282
- to: finalRecipient,
283
- value: amountWei,
284
- nonce,
285
- gasPrice,
286
- gasLimit: nativeGasLimit,
287
- chainId: chainIdNum,
288
- type: txType
289
- }
290
- });
291
- }
292
- else {
293
- const data = iface.encodeFunctionData('transfer', [finalRecipient, amountWei]);
294
- txsToSign.push({
295
- wallet: mainWallet,
296
- tx: {
297
- to: tokenAddress,
298
- data,
299
- value: 0n,
300
- nonce,
301
- gasPrice,
302
- gasLimit: finalGasLimit,
303
- chainId: chainIdNum,
304
- type: txType
305
- }
306
- });
307
- }
308
- continue;
309
- }
310
- // 有跳转
311
- // ✅ 支持 string 和 GeneratedWallet 两种类型
312
- const fullChain = [mainWallet, ...hopChain.map(w => new Wallet(typeof w === 'string' ? w : w.privateKey, provider))];
313
- const addresses = [...fullChain.map(w => w.address), finalRecipient];
314
- if (isNative) {
315
- // ========== 原生代币多跳:gas 包含在转账金额中逐层传递 ==========
316
- for (let j = 0; j < addresses.length - 1; j++) {
317
- const fromWallet = fullChain[j];
318
- const toAddress = addresses[j + 1];
319
- const nonce = j === 0 ? allMainNonces[mainNonceIdx++] : 0;
320
- const remainingHops = addresses.length - 2 - j;
321
- const additionalGas = nativeHopGasFee * BigInt(remainingHops);
322
- const transferValue = amountWei + additionalGas;
323
- txsToSign.push({
324
- wallet: fromWallet,
325
- tx: {
326
- to: toAddress,
327
- value: transferValue,
328
- nonce,
329
- gasPrice,
330
- gasLimit: nativeTransferGasLimit,
331
- chainId: chainIdNum,
332
- type: txType
333
- }
334
- });
335
- }
336
- }
337
- else {
338
- // ========== ERC20 多跳:gas 也逐层传递(保护隐私)==========
339
- // 计算每个中转钱包需要的 gas(从后往前)
340
- // - 最后一个中转钱包:只需要 ERC20 转账的 gas
341
- // - 其他中转钱包:需要 转 gas 的 gas + ERC20 转账的 gas + 后续所有的 gas
342
- const hopGasNeeds = [];
343
- for (let j = hopChain.length - 1; j >= 0; j--) {
344
- if (j === hopChain.length - 1) {
345
- // 最后一个中转钱包:只需要 ERC20 转账的 gas
346
- hopGasNeeds.unshift(erc20HopGasFee);
347
- }
348
- else {
349
- // 其他中转钱包:转 gas(21000) + 转 ERC20 + 后续的 gas
350
- const nextHopGas = hopGasNeeds[0];
351
- hopGasNeeds.unshift(nativeHopGasFeeForErc20 + erc20HopGasFee + nextHopGas);
352
- }
353
- }
354
- // 第一步:主钱包给第一个中转钱包转 gas(包含所有后续的 gas)
355
- const totalGasForFirstHop = hopGasNeeds[0];
356
- txsToSign.push({
357
- wallet: mainWallet,
358
- tx: {
359
- to: fullChain[1].address,
360
- value: totalGasForFirstHop,
361
- nonce: allMainNonces[mainNonceIdx++],
362
- gasPrice,
363
- gasLimit: nativeTransferGasLimit,
364
- chainId: chainIdNum,
365
- type: txType
366
- }
367
- });
368
- // 第二步:主钱包给第一个中转钱包转 ERC20
369
- const mainToFirstHopData = iface.encodeFunctionData('transfer', [fullChain[1].address, amountWei]);
370
- txsToSign.push({
371
- wallet: mainWallet,
372
- tx: {
373
- to: tokenAddress,
374
- data: mainToFirstHopData,
375
- value: 0n,
376
- nonce: allMainNonces[mainNonceIdx++],
377
- gasPrice,
378
- gasLimit: erc20TransferGasLimit,
379
- chainId: chainIdNum,
380
- type: txType
381
- }
382
- });
383
- // 第三步:中转钱包逐层传递(gas 和 ERC20)
384
- for (let j = 1; j < fullChain.length; j++) {
385
- const fromWallet = fullChain[j];
386
- const toAddress = addresses[j + 1]; // 下一个地址(可能是中转钱包或最终接收者)
387
- const isLastHop = j === fullChain.length - 1;
388
- if (!isLastHop) {
389
- // 非最后一个中转钱包:先转 gas 给下一个中转钱包
390
- const gasToTransfer = hopGasNeeds[j]; // 下一个中转钱包需要的 gas
391
- txsToSign.push({
392
- wallet: fromWallet,
393
- tx: {
394
- to: toAddress,
395
- value: gasToTransfer,
396
- nonce: 0, // 中转钱包的第一笔交易
397
- gasPrice,
398
- gasLimit: nativeTransferGasLimit,
399
- chainId: chainIdNum,
400
- type: txType
401
- }
402
- });
403
- // 再转 ERC20
404
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, amountWei]);
405
- txsToSign.push({
406
- wallet: fromWallet,
407
- tx: {
408
- to: tokenAddress,
409
- data: erc20Data,
410
- value: 0n,
411
- nonce: 1, // 中转钱包的第二笔交易
412
- gasPrice,
413
- gasLimit: erc20TransferGasLimit,
414
- chainId: chainIdNum,
415
- type: txType
416
- }
417
- });
418
- }
419
- else {
420
- // 最后一个中转钱包:只转 ERC20 给最终接收者
421
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, amountWei]);
422
- txsToSign.push({
423
- wallet: fromWallet,
424
- tx: {
425
- to: tokenAddress,
426
- data: erc20Data,
427
- value: 0n,
428
- nonce: 0, // 最后一个中转钱包只有一笔交易
429
- gasPrice,
430
- gasLimit: erc20TransferGasLimit,
431
- chainId: chainIdNum,
432
- type: txType
433
- }
434
- });
435
- }
436
- }
437
- }
438
- }
439
- // ✅ 并行签名所有交易
440
- const signedTxsResult = await Promise.all(txsToSign.map(({ wallet, tx }) => wallet.signTransaction(tx)));
441
- signedTxs.push(...signedTxsResult);
442
- // ✅ 利润多跳转账(强制 2 跳中转)
443
- if (extractProfit && totalProfit > 0n) {
444
- const profitNonce = allMainNonces[mainNonceIdx++];
445
- const profitHopResult = await buildProfitHopTransactions({
446
- provider,
447
- payerWallet: mainWallet,
448
- profitAmount: totalProfit,
449
- profitRecipient: profitAddr,
450
- hopCount: PROFIT_HOP_COUNT,
451
- gasPrice,
452
- chainId: chainIdNum,
453
- txType,
454
- startNonce: profitNonce
455
- });
456
- signedTxs.push(...profitHopResult.signedTransactions);
457
- profitHopWallets = profitHopResult.hopWallets; // ✅ 收集利润多跳钱包
458
- }
459
- }
460
- // ✅ 简化返回:只返回签名交易、多跳钱包和元数据
461
- return {
462
- signedTransactions: signedTxs,
463
- hopWallets: preparedHops || undefined,
464
- profitHopWallets, // ✅ 返回利润多跳钱包
465
- metadata: extractProfit ? {
466
- totalAmount: ethers.formatEther(totalAmountBeforeProfit),
467
- profitAmount: ethers.formatEther(totalProfit),
468
- profitRecipient: profitAddr,
469
- recipientCount: recipients.length,
470
- isNative,
471
- tokenAddress: isNative ? undefined : tokenAddress
472
- } : undefined
473
- };
474
- }
475
- /**
476
- * 归集(仅签名版本 - 不依赖 Merkle)
477
- * ✅ 精简版:只负责签名交易,不提交到 Merkle
478
- * ✅ 优化版:支持 startNonce 参数避免并行调用时的 nonce 冲突
479
- */
480
- export async function sweepWithBundleMerkle(params) {
481
- const { sourcePrivateKeys, target, targetPrivateKey, ratioPct, ratios, amount, amounts, tokenAddress, tokenDecimals, skipIfInsufficient = true, hopCount = 0, hopPrivateKeys, sources, config, startNonce } = params;
482
- // 快速返回空结果
483
- if (!sourcePrivateKeys || sourcePrivateKeys.length === 0) {
484
- return {
485
- signedTransactions: [],
486
- hopWallets: undefined
487
- };
488
- }
489
- // 初始化
490
- const chainIdNum = config.chainId ?? CHAINS.BSC.chainId;
491
- const chainName = chainIdNum === CHAINS.MONAD.chainId ? 'Monad' : chainIdNum === CHAINS.BSC.chainId ? 'BSC' : `Chain-${chainIdNum}`;
492
- const provider = new ethers.JsonRpcProvider(config.rpcUrl, {
493
- chainId: chainIdNum,
494
- name: chainName
495
- });
496
- const isNative = _isNativeTokenAddress(tokenAddress);
497
- const txType = getTxType(config);
498
- // ✅ 如果提供了 targetPrivateKey,创建 targetWallet 用于支付利润
499
- const targetWallet = targetPrivateKey ? new Wallet(targetPrivateKey, provider) : null;
500
- // 归集比例处理
501
- const clamp = (n) => (typeof n === 'number' && Number.isFinite(n)
502
- ? Math.max(0, Math.min(100, Math.floor(n)))
503
- : undefined);
504
- const ratio = clamp(ratioPct);
505
- // 生成跳转钱包
506
- // 统一 sources 输入
507
- const actualKeys = (() => {
508
- if (sources && sources.length > 0)
509
- return sources.map(s => s.privateKey);
510
- return sourcePrivateKeys;
511
- })();
512
- // hop 私钥链优先使用传入
513
- const providedHops = (() => {
514
- if (hopPrivateKeys && hopPrivateKeys.length > 0) {
515
- if (hopPrivateKeys.length !== actualKeys.length) {
516
- throw new Error(`hopPrivateKeys length (${hopPrivateKeys.length}) must match sourcePrivateKeys length (${actualKeys.length})`);
517
- }
518
- return hopPrivateKeys.every(h => h.length === 0) ? null : hopPrivateKeys;
519
- }
520
- if (sources && sources.length > 0) {
521
- const hops = sources.map(s => s.hopPrivateKeys ?? []);
522
- return hops.every(h => h.length === 0) ? null : hops;
523
- }
524
- return null;
525
- })();
526
- // hop 数量数组
527
- const hopCountInput = (() => {
528
- if (sources && sources.length > 0) {
529
- const baseArray = Array.isArray(hopCount) ? hopCount : new Array(actualKeys.length).fill(hopCount);
530
- return sources.map((s, i) => (typeof s.hopCount === 'number' ? s.hopCount : (baseArray[i] ?? 0)));
531
- }
532
- return hopCount;
533
- })();
534
- const preparedHops = providedHops ?? _generateHopWallets(actualKeys.length, hopCountInput);
535
- const hasHops = preparedHops !== null;
536
- const maxHopCount = hasHops ? Math.max(...preparedHops.map(h => h.length)) : 0;
537
- // 智能计算 Gas Limit
538
- const finalGasLimit = _calculateGasLimit(config, isNative, hasHops, maxHopCount);
539
- const nativeGasLimit = (config.prefer21000ForNative ?? false) ? BRIBE_GAS_LIMIT : finalGasLimit;
540
- const signedTxs = [];
541
- // ✅ 利润提取配置
542
- const extractProfit = shouldExtractProfit(config);
543
- const profitAddr = getProfitRecipient();
544
- let totalProfit = 0n;
545
- let totalAmountBeforeProfit = 0n;
546
- let profitHopWallets; // ✅ 收集利润多跳钱包
547
- // ✅ BSC 链贿赂支持(由 targetWallet 支付,如果提供了 targetPrivateKey)
548
- const bribeAmount = chainIdNum === CHAINS.BSC.chainId ? getBribeAmount(config) : 0n;
549
- const needBribeTx = bribeAmount > 0n && targetWallet !== null;
550
- const bribeSignedTx = [];
551
- // ✅ 修复 nonce 冲突:统一管理 targetWallet 的 nonce
552
- // 贿赂交易和利润多跳交易都由 targetWallet 签名,需要一次性获取所有 nonce
553
- let targetWalletNonceStart;
554
- let targetWalletNonceUsed = 0;
555
- if (targetWallet && (needBribeTx || extractProfit)) {
556
- // 预先获取 targetWallet 的 pending nonce,后续按顺序使用
557
- targetWalletNonceStart = await provider.getTransactionCount(targetWallet.address, 'pending');
558
- console.log(`[sweep] targetWallet nonce 起点: ${targetWalletNonceStart}`);
559
- }
560
- // ✅ 贿赂交易放在最前面(由 targetWallet 签名)
561
- if (needBribeTx && targetWallet && targetWalletNonceStart !== undefined) {
562
- const bribeGasPrice = await getOptimizedGasPrice(provider, getGasPriceConfig(config));
563
- const bribeNonce = targetWalletNonceStart + targetWalletNonceUsed;
564
- targetWalletNonceUsed += 1; // ✅ 递增 nonce 计数
565
- const bribeTx = await targetWallet.signTransaction({
566
- to: BLOCKRAZOR_BUILDER_EOA,
567
- value: bribeAmount,
568
- nonce: bribeNonce,
569
- gasPrice: bribeGasPrice,
570
- gasLimit: BRIBE_GAS_LIMIT,
571
- chainId: chainIdNum,
572
- type: txType
573
- });
574
- bribeSignedTx.push(bribeTx);
575
- console.log(`[sweep] 贿赂交易已添加: ${ethers.formatEther(bribeAmount)} BNB (by targetWallet, nonce=${bribeNonce})`);
576
- }
577
- if (!preparedHops) {
578
- // ========== 无多跳:直接批量归集 ==========
579
- const wallets = actualKeys.map(pk => new Wallet(pk, provider));
580
- const addresses = wallets.map(w => w.address);
581
- const nonceManager = new NonceManager(provider);
582
- // ✅ 优化:并行获取 gasPrice 和余额
583
- if (isNative) {
584
- // ✅ 原生币:并行获取 gasPrice 和余额
585
- const [gasPrice, balances] = await Promise.all([
586
- getOptimizedGasPrice(provider, getGasPriceConfig(config)),
587
- _batchGetBalances(provider, addresses)
588
- ]);
589
- const gasCostBase = nativeGasLimit * gasPrice;
590
- // ✅ 利润多跳需要 PROFIT_HOP_COUNT + 1 笔交易的 gas(payer → hop1 → hop2 → 利润地址)
591
- const profitTxGas = PROFIT_HOP_GAS_LIMIT * gasPrice * BigInt(PROFIT_HOP_COUNT + 1);
592
- // ✅ 第一步:计算所有钱包的归集金额和利润,找出归集金额最大的钱包
593
- const sweepAmounts = [];
594
- let maxSweepIndex = -1;
595
- let maxSweepAmount = 0n;
596
- for (let i = 0; i < wallets.length; i++) {
597
- const bal = balances[i];
598
- let toSend = 0n;
599
- const ratioForI = (() => {
600
- if (sources && sources[i] && sources[i].ratioPct !== undefined)
601
- return clamp(sources[i].ratioPct);
602
- if (ratios && ratios[i] !== undefined)
603
- return clamp(ratios[i]);
604
- return ratio;
605
- })();
606
- const amountStrForI = (() => {
607
- if (sources && sources[i] && sources[i].amount !== undefined)
608
- return String(sources[i].amount);
609
- if (amounts && amounts[i] !== undefined)
610
- return String(amounts[i]);
611
- return amount !== undefined ? String(amount) : undefined;
612
- })();
613
- // ✅ 只有支付者需要 2 笔交易的 gas,其他钱包只需要 1 笔
614
- const gasCost = gasCostBase; // 所有钱包都只计算主转账的 gas
615
- if (ratioForI !== undefined) {
616
- const want = (bal * BigInt(ratioForI)) / 100n;
617
- const maxSendable = bal > gasCost ? (bal - gasCost) : 0n;
618
- toSend = want > maxSendable ? maxSendable : want;
619
- }
620
- else if (amountStrForI && amountStrForI.trim().length > 0) {
621
- const amt = ethers.parseEther(amountStrForI);
622
- const need = amt + gasCost;
623
- if (!skipIfInsufficient || bal >= need)
624
- toSend = amt;
625
- }
626
- sweepAmounts.push(toSend);
627
- totalAmountBeforeProfit += toSend;
628
- // 找出归集金额最大的钱包
629
- if (toSend > maxSweepAmount) {
630
- maxSweepAmount = toSend;
631
- maxSweepIndex = i;
632
- }
633
- }
634
- // ✅ 按地址数量收取固定费用(原生代币)
635
- const activeNativeAddressCount = sweepAmounts.filter(a => a > 0n).length;
636
- if (extractProfit && activeNativeAddressCount > 0) {
637
- totalProfit = calculateTransferFee(chainIdNum, activeNativeAddressCount);
638
- console.log(`[sweep Native] 按地址收费: ${activeNativeAddressCount} 个地址 × ${ethers.formatEther(calculateTransferFee(chainIdNum, 1))} = ${ethers.formatEther(totalProfit)} 原生币`);
639
- }
640
- // ✅ 如果需要提取费用,检查支付者是否有足够余额
641
- if (extractProfit && totalProfit > 0n && maxSweepIndex >= 0) {
642
- const payerBalance = balances[maxSweepIndex];
643
- const payerSweepAmount = sweepAmounts[maxSweepIndex];
644
- const payerNeedGas = gasCostBase + profitTxGas + totalProfit;
645
- if (payerBalance < payerSweepAmount + payerNeedGas) {
646
- const maxPayerSweep = payerBalance > payerNeedGas ? payerBalance - payerNeedGas : 0n;
647
- sweepAmounts[maxSweepIndex] = maxPayerSweep;
648
- totalAmountBeforeProfit = sweepAmounts.reduce((sum, amt) => sum + amt, 0n);
649
- }
650
- }
651
- // ✅ 第二步:生成归集交易
652
- // ✅ 确定利润支付者:优先使用 targetWallet,否则使用归集金额最大的源钱包
653
- const useTargetAsPayer = targetWallet !== null;
654
- const profitPayerWallet = useTargetAsPayer ? targetWallet : (maxSweepIndex >= 0 ? wallets[maxSweepIndex] : null);
655
- // ✅ 修复 nonce 冲突:统一管理 targetWallet 的 nonce
656
- // 如果 targetWallet 作为利润支付者,使用预先获取的 nonce 起点 + 偏移量
657
- let payerProfitNonce;
658
- if (extractProfit && totalProfit > 0n && profitPayerWallet) {
659
- if (useTargetAsPayer && targetWalletNonceStart !== undefined) {
660
- // ✅ targetWallet:使用统一管理的 nonce(贿赂交易已使用 targetWalletNonceUsed 个)
661
- payerProfitNonce = targetWalletNonceStart + targetWalletNonceUsed;
662
- console.log(`[sweep] targetWallet 利润交易 nonce: ${payerProfitNonce} (起点=${targetWalletNonceStart}, 已用=${targetWalletNonceUsed})`);
663
- }
664
- else {
665
- // ✅ 源钱包支付利润:使用 NonceManager 获取 2 个 nonce(归集 + 利润)
666
- const nonces = await nonceManager.getNextNonceBatch(profitPayerWallet, 2);
667
- payerProfitNonce = nonces[1];
668
- }
669
- }
670
- // ✅ 优化:批量获取所有钱包的 nonce(JSON-RPC 批量请求)
671
- // 过滤出需要归集的钱包(如果用 targetWallet 支付利润,则不排除 maxSweepIndex)
672
- const walletsToSweep = wallets.filter((_, i) => sweepAmounts[i] > 0n && (useTargetAsPayer || i !== maxSweepIndex));
673
- const nonces = walletsToSweep.length > 0
674
- ? await nonceManager.getNextNoncesForWallets(walletsToSweep)
675
- : [];
676
- let nonceIdx = 0;
677
- const txPromises = wallets.map(async (w, i) => {
678
- const toSend = sweepAmounts[i];
679
- if (toSend <= 0n)
680
- return null;
681
- // ✅ 全额归集,费用由支付者额外支付原生代币
682
- const actualToSend = toSend;
683
- // ✅ 支付者使用预留的第一个 nonce,其他钱包使用批量获取的 nonce
684
- let nonce;
685
- if (!useTargetAsPayer && i === maxSweepIndex && payerProfitNonce !== undefined) {
686
- nonce = payerProfitNonce - 1; // 使用预留的第一个 nonce
687
- }
688
- else {
689
- nonce = nonces[nonceIdx++];
690
- }
691
- const mainTx = await w.signTransaction({
692
- to: target,
693
- value: actualToSend,
694
- nonce,
695
- gasPrice,
696
- gasLimit: nativeGasLimit,
697
- chainId: chainIdNum,
698
- type: txType
699
- });
700
- return mainTx;
701
- });
702
- const allTxs = (await Promise.all(txPromises)).filter(tx => tx !== null);
703
- signedTxs.push(...allTxs);
704
- // ✅ 第三步:利润多跳转账(强制 2 跳中转)
705
- if (extractProfit && totalProfit > 0n && profitPayerWallet && payerProfitNonce !== undefined) {
706
- const profitHopResult = await buildProfitHopTransactions({
707
- provider,
708
- payerWallet: profitPayerWallet,
709
- profitAmount: totalProfit,
710
- profitRecipient: profitAddr,
711
- hopCount: PROFIT_HOP_COUNT,
712
- gasPrice,
713
- chainId: chainIdNum,
714
- txType,
715
- startNonce: payerProfitNonce
716
- });
717
- signedTxs.push(...profitHopResult.signedTransactions);
718
- profitHopWallets = profitHopResult.hopWallets; // ✅ 收集利润多跳钱包
719
- }
720
- }
721
- else {
722
- // ✅ ERC20:并行获取 gasPrice、decimals、余额(传入 chainIdNum 避免 NETWORK_ERROR)
723
- const [gasPrice, decimals, balances, bnbBalances] = await Promise.all([
724
- getOptimizedGasPrice(provider, getGasPriceConfig(config)),
725
- Promise.resolve(tokenDecimals ?? await _getErc20DecimalsMerkle(provider, tokenAddress, chainIdNum)),
726
- _batchGetBalances(provider, addresses, tokenAddress),
727
- config.checkBnbForErc20NoHop ? _batchGetBalances(provider, addresses) : Promise.resolve([])
728
- ]);
729
- const iface = new ethers.Interface(['function transfer(address,uint256) returns (bool)']);
730
- // ✅ 利润多跳需要 PROFIT_HOP_COUNT + 1 笔交易的 gas
731
- const profitTxGas = PROFIT_HOP_GAS_LIMIT * gasPrice * BigInt(PROFIT_HOP_COUNT + 1);
732
- // ✅ 第一步:计算所有钱包的归集金额和利润,找出归集金额最大的钱包
733
- const sweepAmounts = [];
734
- let maxSweepIndex = -1;
735
- let maxSweepAmount = 0n;
736
- for (let i = 0; i < wallets.length; i++) {
737
- const bal = balances[i];
738
- let toSend = 0n;
739
- const ratioForI = (() => {
740
- if (sources && sources[i] && sources[i].ratioPct !== undefined)
741
- return clamp(sources[i].ratioPct);
742
- if (ratios && ratios[i] !== undefined)
743
- return clamp(ratios[i]);
744
- return ratio;
745
- })();
746
- const amountStrForI = (() => {
747
- if (sources && sources[i] && sources[i].amount !== undefined)
748
- return String(sources[i].amount);
749
- if (amounts && amounts[i] !== undefined)
750
- return String(amounts[i]);
751
- return amount !== undefined ? String(amount) : undefined;
752
- })();
753
- if (ratioForI !== undefined) {
754
- toSend = (bal * BigInt(ratioForI)) / 100n;
755
- }
756
- else if (amountStrForI && amountStrForI.trim().length > 0) {
757
- toSend = ethers.parseUnits(amountStrForI, decimals);
758
- }
759
- if (toSend <= 0n || (skipIfInsufficient && bal < toSend)) {
760
- sweepAmounts.push(0n);
761
- continue;
762
- }
763
- // ✅ 检查 BNB 余额(只需主转账的 gas,支付者后面单独检查)
764
- const totalGasNeeded = finalGasLimit * gasPrice;
765
- if (config.checkBnbForErc20NoHop) {
766
- const bnb = bnbBalances[i] ?? 0n;
767
- if (skipIfInsufficient && bnb < totalGasNeeded) {
768
- sweepAmounts.push(0n);
769
- continue;
770
- }
771
- }
772
- sweepAmounts.push(toSend);
773
- totalAmountBeforeProfit += toSend;
774
- // 找出归集金额最大的钱包
775
- if (toSend > maxSweepAmount) {
776
- maxSweepAmount = toSend;
777
- maxSweepIndex = i;
778
- }
779
- }
780
- // ✅ 按地址数量收取固定费用(原生代币支付,不受转账金额影响)
781
- const activeAddressCountErc20 = sweepAmounts.filter(a => a > 0n).length;
782
- let nativeProfitAmount = 0n;
783
- if (extractProfit && activeAddressCountErc20 > 0) {
784
- nativeProfitAmount = calculateTransferFee(chainIdNum, activeAddressCountErc20);
785
- totalProfit = nativeProfitAmount;
786
- console.log(`[sweep ERC20] 按地址收费: ${activeAddressCountErc20} 个地址 × ${ethers.formatEther(calculateTransferFee(chainIdNum, 1))} = ${ethers.formatEther(nativeProfitAmount)} 原生币`);
787
- }
788
- // ✅ 确定费用支付者:优先使用 targetWallet,否则使用归集金额最大的源钱包
789
- const useTargetAsPayerErc20 = targetWallet !== null;
790
- const profitPayerWalletErc20 = useTargetAsPayerErc20 ? targetWallet : (maxSweepIndex >= 0 ? wallets[maxSweepIndex] : null);
791
- // ✅ 如果需要提取费用,检查支付者是否有足够原生代币支付
792
- if (extractProfit && nativeProfitAmount > 0n && profitPayerWalletErc20 && config.checkBnbForErc20NoHop) {
793
- const payerBnbBalance = useTargetAsPayerErc20
794
- ? await provider.getBalance(target)
795
- : (bnbBalances[maxSweepIndex] ?? 0n);
796
- const payerNeedGas = (useTargetAsPayerErc20 ? 0n : finalGasLimit * gasPrice) + profitTxGas + nativeProfitAmount;
797
- if (payerBnbBalance < payerNeedGas) {
798
- nativeProfitAmount = 0n;
799
- totalProfit = 0n;
800
- }
801
- }
802
- // ✅ 第二步:生成归集交易(ERC20 全额归集,费用以原生币单独支付)
803
- let payerProfitNonce;
804
- if (extractProfit && nativeProfitAmount > 0n && profitPayerWalletErc20) {
805
- if (useTargetAsPayerErc20 && targetWalletNonceStart !== undefined) {
806
- payerProfitNonce = targetWalletNonceStart + targetWalletNonceUsed;
807
- console.log(`[sweep ERC20] targetWallet 费用交易 nonce: ${payerProfitNonce} (起点=${targetWalletNonceStart}, 已用=${targetWalletNonceUsed})`);
808
- }
809
- else {
810
- const nonces = await nonceManager.getNextNonceBatch(profitPayerWalletErc20, 2);
811
- payerProfitNonce = nonces[1];
812
- }
813
- }
814
- // ✅ 优化:批量获取所有钱包的 nonce(JSON-RPC 批量请求)
815
- // 过滤出需要归集的钱包(如果用 targetWallet 支付利润,则不排除 maxSweepIndex)
816
- const walletsToSweepErc20 = wallets.filter((_, i) => sweepAmounts[i] > 0n && (useTargetAsPayerErc20 || i !== maxSweepIndex));
817
- const noncesErc20 = walletsToSweepErc20.length > 0
818
- ? await nonceManager.getNextNoncesForWallets(walletsToSweepErc20)
819
- : [];
820
- let nonceIdxErc20 = 0;
821
- const txPromises = wallets.map(async (w, i) => {
822
- const toSend = sweepAmounts[i];
823
- if (toSend <= 0n)
824
- return null;
825
- // ✅ ERC20 归集:全部归集,不扣除代币(利润从 BNB 支付)
826
- const actualToSend = toSend;
827
- // ✅ 支付者使用预留的第一个 nonce,其他钱包使用批量获取的 nonce
828
- let nonce;
829
- if (!useTargetAsPayerErc20 && i === maxSweepIndex && payerProfitNonce !== undefined) {
830
- nonce = payerProfitNonce - 1; // 使用预留的第一个 nonce
831
- }
832
- else {
833
- nonce = noncesErc20[nonceIdxErc20++];
834
- }
835
- const data = iface.encodeFunctionData('transfer', [target, actualToSend]);
836
- const mainTx = await w.signTransaction({
837
- to: tokenAddress,
838
- data,
839
- value: 0n,
840
- nonce,
841
- gasPrice,
842
- gasLimit: finalGasLimit,
843
- chainId: chainIdNum,
844
- type: txType
845
- });
846
- return mainTx;
847
- });
848
- const allTxs = (await Promise.all(txPromises)).filter(tx => tx !== null);
849
- signedTxs.push(...allTxs);
850
- // ✅ 第三步:费用多跳转账(强制 2 跳中转)
851
- if (extractProfit && nativeProfitAmount > 0n && profitPayerWalletErc20 && payerProfitNonce !== undefined) {
852
- const profitHopResult = await buildProfitHopTransactions({
853
- provider,
854
- payerWallet: profitPayerWalletErc20,
855
- profitAmount: nativeProfitAmount,
856
- profitRecipient: profitAddr,
857
- hopCount: PROFIT_HOP_COUNT,
858
- gasPrice,
859
- chainId: chainIdNum,
860
- txType,
861
- startNonce: payerProfitNonce
862
- });
863
- signedTxs.push(...profitHopResult.signedTransactions);
864
- profitHopWallets = profitHopResult.hopWallets; // ✅ 收集利润多跳钱包
865
- }
866
- }
867
- }
868
- else {
869
- // ========== 有多跳:构建跳转链归集 ==========
870
- // ✅ 优化版:批量计算 + 批量获取 nonce + 并行签名
871
- const sourceWallets = actualKeys.map(pk => new Wallet(pk, provider));
872
- const withHopIndexes = [];
873
- const withoutHopIndexes = [];
874
- for (let i = 0; i < preparedHops.length; i++) {
875
- if (preparedHops[i].length > 0) {
876
- withHopIndexes.push(i);
877
- }
878
- else {
879
- withoutHopIndexes.push(i);
880
- }
881
- }
882
- const sourceAddresses = sourceWallets.map(w => w.address);
883
- // ✅ 优化:并行获取 gasPrice、decimals、余额
884
- const [gasPrice, decimals, balances, bnbBalances] = await Promise.all([
885
- getOptimizedGasPrice(provider, getGasPriceConfig(config)),
886
- isNative ? Promise.resolve(18) : Promise.resolve(tokenDecimals ?? await _getErc20DecimalsMerkle(provider, tokenAddress, chainIdNum)),
887
- _batchGetBalances(provider, sourceAddresses, tokenAddress),
888
- isNative ? Promise.resolve([]) : _batchGetBalances(provider, sourceAddresses)
889
- ]);
890
- const iface = isNative ? null : new ethers.Interface(['function transfer(address,uint256) returns (bool)']);
891
- // ✅ Gas limit 设置(与分散函数保持一致)
892
- // - 原生代币转账:使用 GAS_LIMITS.NATIVE_TRANSFER(固定)
893
- // - ERC20 转账:使用 GAS_LIMITS.ERC20_TRANSFER(固定,因为 gas 波动较大)
894
- const nativeTransferGasLimit = NATIVE_TRANSFER_GAS_LIMIT;
895
- const erc20TransferGasLimit = GAS_LIMITS.ERC20_TRANSFER;
896
- // ✅ 原生代币多跳的 gas 费(每跳只需要 21000)
897
- const nativeHopGasFee = nativeTransferGasLimit * gasPrice;
898
- // ✅ ERC20 多跳时,中转钱包需要执行 2 笔交易(转 gas + 转 ERC20)
899
- const erc20HopGasFee = erc20TransferGasLimit * gasPrice;
900
- const nativeHopGasFeeForErc20 = nativeTransferGasLimit * gasPrice;
901
- const nonceManager = new NonceManager(provider);
902
- // ✅ 用于记录每个钱包的归集金额
903
- const sweepAmounts = new Array(sourceWallets.length).fill(0n);
904
- // ✅ 辅助函数:获取比例和金额
905
- const getRatioForI = (i) => {
906
- if (sources && sources[i] && sources[i].ratioPct !== undefined)
907
- return clamp(sources[i].ratioPct);
908
- if (ratios && ratios[i] !== undefined)
909
- return clamp(ratios[i]);
910
- return ratio;
911
- };
912
- const getAmountStrForI = (i) => {
913
- if (sources && sources[i] && sources[i].amount !== undefined)
914
- return String(sources[i].amount);
915
- if (amounts && amounts[i] !== undefined)
916
- return String(amounts[i]);
917
- return amount !== undefined ? String(amount) : undefined;
918
- };
919
- // ========== 第1步:计算所有钱包的归集金额(同步,无 RPC)==========
920
- const noHopTxDataList = [];
921
- for (const i of withoutHopIndexes) {
922
- const bal = balances[i];
923
- let toSend = 0n;
924
- const ratioForI = getRatioForI(i);
925
- const amountStrForI = getAmountStrForI(i);
926
- if (isNative) {
927
- const gasCost = nativeGasLimit * gasPrice;
928
- if (ratioForI !== undefined) {
929
- const want = (bal * BigInt(ratioForI)) / 100n;
930
- const maxSendable = bal > gasCost ? (bal - gasCost) : 0n;
931
- toSend = want > maxSendable ? maxSendable : want;
932
- }
933
- else if (amountStrForI && amountStrForI.trim().length > 0) {
934
- const amt = ethers.parseEther(amountStrForI);
935
- const need = amt + gasCost;
936
- if (!skipIfInsufficient || bal >= need)
937
- toSend = amt;
938
- }
939
- }
940
- else {
941
- if (ratioForI !== undefined) {
942
- toSend = (bal * BigInt(ratioForI)) / 100n;
943
- }
944
- else if (amountStrForI && amountStrForI.trim().length > 0) {
945
- toSend = ethers.parseUnits(amountStrForI, decimals);
946
- }
947
- if (skipIfInsufficient && bal < toSend)
948
- toSend = 0n;
949
- }
950
- if (toSend > 0n) {
951
- sweepAmounts[i] = toSend;
952
- totalAmountBeforeProfit += toSend;
953
- noHopTxDataList.push({ index: i, wallet: sourceWallets[i], toSend });
954
- }
955
- }
956
- // ========== 第2步:批量获取无跳转钱包的 nonces ==========
957
- const noHopWallets = noHopTxDataList.map(d => d.wallet);
958
- const noHopNonces = noHopWallets.length > 0
959
- ? await nonceManager.getNextNoncesForWallets(noHopWallets)
960
- : [];
961
- // ========== 第3步:并行签名无跳转交易 ==========
962
- const noHopTxPromises = noHopTxDataList.map((data, idx) => {
963
- const { wallet, toSend } = data;
964
- const nonce = noHopNonces[idx];
965
- if (isNative) {
966
- return wallet.signTransaction({
967
- to: target,
968
- value: toSend,
969
- nonce,
970
- gasPrice,
971
- gasLimit: nativeGasLimit,
972
- chainId: chainIdNum,
973
- type: txType
974
- });
975
- }
976
- else {
977
- const txData = iface.encodeFunctionData('transfer', [target, toSend]);
978
- return wallet.signTransaction({
979
- to: tokenAddress,
980
- data: txData,
981
- value: 0n,
982
- nonce,
983
- gasPrice,
984
- gasLimit: finalGasLimit,
985
- chainId: chainIdNum,
986
- type: txType
987
- });
988
- }
989
- });
990
- if (noHopTxPromises.length > 0) {
991
- const noHopSignedTxs = await Promise.all(noHopTxPromises);
992
- signedTxs.push(...noHopSignedTxs);
993
- }
994
- // ========== 第4步:预计算有跳转钱包的归集数据 ==========
995
- const hopTxDataList = [];
996
- for (const i of withHopIndexes) {
997
- const sourceWallet = sourceWallets[i];
998
- const hopChain = preparedHops[i];
999
- const bal = balances[i];
1000
- let toSend = 0n;
1001
- const ratioForI = getRatioForI(i);
1002
- const amountStrForI = getAmountStrForI(i);
1003
- if (isNative) {
1004
- // 原生代币多跳每跳只需要 21000 gas
1005
- const totalGasCost = nativeTransferGasLimit * gasPrice * BigInt(hopChain.length + 1);
1006
- if (ratioForI !== undefined) {
1007
- const want = (bal * BigInt(ratioForI)) / 100n;
1008
- const maxSendable = bal > totalGasCost ? (bal - totalGasCost) : 0n;
1009
- toSend = want > maxSendable ? maxSendable : want;
1010
- }
1011
- else if (amountStrForI && amountStrForI.trim().length > 0) {
1012
- const amt = ethers.parseEther(amountStrForI);
1013
- const need = amt + totalGasCost;
1014
- if (!skipIfInsufficient || bal >= need)
1015
- toSend = amt;
1016
- }
1017
- }
1018
- else {
1019
- const bnbBal = bnbBalances[i];
1020
- // 计算 ERC20 多跳所需的 BNB(逐层传递模式):
1021
- // - 源钱包执行 2 笔交易的 gas(转 gas 21000 + 转 ERC20)
1022
- // - 源钱包转给第一个中转钱包的 gas(包含后续所有)
1023
- // 简化计算:每个中转钱包 ≈ (21000 + erc20GasLimit) * gasPrice
1024
- const sourceGas = (nativeTransferGasLimit + erc20TransferGasLimit) * gasPrice;
1025
- const hopGas = (nativeHopGasFeeForErc20 + erc20HopGasFee) * BigInt(hopChain.length);
1026
- const bnbNeeded = sourceGas + hopGas;
1027
- if (bnbBal < bnbNeeded && skipIfInsufficient)
1028
- continue;
1029
- if (ratioForI !== undefined) {
1030
- toSend = (bal * BigInt(ratioForI)) / 100n;
1031
- }
1032
- else if (amountStrForI && amountStrForI.trim().length > 0) {
1033
- toSend = ethers.parseUnits(amountStrForI, decimals);
1034
- }
1035
- if (skipIfInsufficient && bal < toSend)
1036
- toSend = 0n;
1037
- }
1038
- if (toSend <= 0n)
1039
- continue;
1040
- sweepAmounts[i] = toSend;
1041
- totalAmountBeforeProfit += toSend;
1042
- // ✅ 支持 string 和 GeneratedWallet 两种类型
1043
- const fullChain = [sourceWallet, ...hopChain.map(w => new Wallet(typeof w === 'string' ? w : w.privateKey, provider))];
1044
- const addresses = [...fullChain.map(w => w.address), target];
1045
- hopTxDataList.push({ index: i, sourceWallet, toSend, hopChain, fullChain, addresses });
1046
- }
1047
- // ========== 第5步:计算每个有跳转钱包需要的 nonce 数量并批量获取 ==========
1048
- // 每个源钱包需要的 nonce 数量:
1049
- // - Native: 1(一笔转账包含后续所有 gas)
1050
- // - ERC20: 2(转 gas + 转 ERC20)
1051
- const hopNonceNeeds = hopTxDataList.map(() => isNative ? 1 : 2);
1052
- const hopSourceWallets = hopTxDataList.map(d => d.sourceWallet);
1053
- // ✅ 批量获取所有有跳转钱包的 nonces
1054
- const hopNoncesFlat = [];
1055
- if (hopSourceWallets.length > 0) {
1056
- const batchNoncePromises = hopSourceWallets.map((w, idx) => nonceManager.getNextNonceBatch(w, hopNonceNeeds[idx]));
1057
- const batchNonces = await Promise.all(batchNoncePromises);
1058
- batchNonces.forEach(nonces => hopNoncesFlat.push(...nonces));
1059
- }
1060
- // ========== 第6步:构建所有有跳转的交易并并行签名 ==========
1061
- const hopTxsToSign = [];
1062
- let nonceOffset = 0;
1063
- for (let dataIdx = 0; dataIdx < hopTxDataList.length; dataIdx++) {
1064
- const { sourceWallet, toSend, hopChain, fullChain, addresses } = hopTxDataList[dataIdx];
1065
- const nonceCount = hopNonceNeeds[dataIdx];
1066
- const nonces = hopNoncesFlat.slice(nonceOffset, nonceOffset + nonceCount);
1067
- nonceOffset += nonceCount;
1068
- if (isNative) {
1069
- // ========== 原生代币多跳:gas 包含在转账金额中逐层传递 ==========
1070
- for (let j = 0; j < addresses.length - 1; j++) {
1071
- const fromWallet = fullChain[j];
1072
- const toAddress = addresses[j + 1];
1073
- const nonce = j === 0 ? nonces[0] : 0;
1074
- const remainingHops = addresses.length - 2 - j;
1075
- const additionalGas = nativeHopGasFee * BigInt(remainingHops);
1076
- const valueToTransfer = toSend + additionalGas;
1077
- hopTxsToSign.push({
1078
- wallet: fromWallet,
1079
- tx: {
1080
- to: toAddress,
1081
- value: valueToTransfer,
1082
- nonce,
1083
- gasPrice,
1084
- gasLimit: nativeTransferGasLimit,
1085
- chainId: chainIdNum,
1086
- type: txType
1087
- }
1088
- });
1089
- }
1090
- }
1091
- else {
1092
- // ========== ERC20 多跳:gas 也逐层传递(保护隐私)==========
1093
- // 计算每个中转钱包需要的 gas(从后往前)
1094
- const hopGasNeeds = [];
1095
- for (let j = hopChain.length - 1; j >= 0; j--) {
1096
- if (j === hopChain.length - 1) {
1097
- // 最后一个中转钱包:只需要 ERC20 转账的 gas
1098
- hopGasNeeds.unshift(erc20HopGasFee);
1099
- }
1100
- else {
1101
- // 其他中转钱包:转 gas(21000) + 转 ERC20 + 后续的 gas
1102
- const nextHopGas = hopGasNeeds[0];
1103
- hopGasNeeds.unshift(nativeHopGasFeeForErc20 + erc20HopGasFee + nextHopGas);
1104
- }
1105
- }
1106
- // 第一步:源钱包给第一个中转钱包转 gas(包含所有后续的 gas)
1107
- const totalGasForFirstHop = hopGasNeeds[0];
1108
- hopTxsToSign.push({
1109
- wallet: sourceWallet,
1110
- tx: {
1111
- to: fullChain[1].address,
1112
- value: totalGasForFirstHop,
1113
- nonce: nonces[0],
1114
- gasPrice,
1115
- gasLimit: nativeTransferGasLimit,
1116
- chainId: chainIdNum,
1117
- type: txType
1118
- }
1119
- });
1120
- // 第二步:源钱包给第一个中转钱包转 ERC20
1121
- const sourceToFirstHopData = iface.encodeFunctionData('transfer', [fullChain[1].address, toSend]);
1122
- hopTxsToSign.push({
1123
- wallet: sourceWallet,
1124
- tx: {
1125
- to: tokenAddress,
1126
- data: sourceToFirstHopData,
1127
- value: 0n,
1128
- nonce: nonces[1],
1129
- gasPrice,
1130
- gasLimit: erc20TransferGasLimit,
1131
- chainId: chainIdNum,
1132
- type: txType
1133
- }
1134
- });
1135
- // 第三步:中转钱包逐层传递(gas 和 ERC20)
1136
- for (let j = 1; j < fullChain.length; j++) {
1137
- const fromWallet = fullChain[j];
1138
- const toAddress = addresses[j + 1]; // 下一个地址(可能是中转钱包或最终目标)
1139
- const isLastHop = j === fullChain.length - 1;
1140
- if (!isLastHop) {
1141
- // 非最后一个中转钱包:先转 gas 给下一个中转钱包
1142
- const gasToTransfer = hopGasNeeds[j]; // 下一个中转钱包需要的 gas
1143
- hopTxsToSign.push({
1144
- wallet: fromWallet,
1145
- tx: {
1146
- to: toAddress,
1147
- value: gasToTransfer,
1148
- nonce: 0, // 中转钱包的第一笔交易
1149
- gasPrice,
1150
- gasLimit: nativeTransferGasLimit,
1151
- chainId: chainIdNum,
1152
- type: txType
1153
- }
1154
- });
1155
- // 再转 ERC20
1156
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, toSend]);
1157
- hopTxsToSign.push({
1158
- wallet: fromWallet,
1159
- tx: {
1160
- to: tokenAddress,
1161
- data: erc20Data,
1162
- value: 0n,
1163
- nonce: 1, // 中转钱包的第二笔交易
1164
- gasPrice,
1165
- gasLimit: erc20TransferGasLimit,
1166
- chainId: chainIdNum,
1167
- type: txType
1168
- }
1169
- });
1170
- }
1171
- else {
1172
- // 最后一个中转钱包:只转 ERC20 给最终目标
1173
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, toSend]);
1174
- hopTxsToSign.push({
1175
- wallet: fromWallet,
1176
- tx: {
1177
- to: tokenAddress,
1178
- data: erc20Data,
1179
- value: 0n,
1180
- nonce: 0, // 最后一个中转钱包只有一笔交易
1181
- gasPrice,
1182
- gasLimit: erc20TransferGasLimit,
1183
- chainId: chainIdNum,
1184
- type: txType
1185
- }
1186
- });
1187
- }
1188
- }
1189
- }
1190
- }
1191
- // ✅ 并行签名所有有跳转的交易
1192
- if (hopTxsToSign.length > 0) {
1193
- const hopSignedTxs = await Promise.all(hopTxsToSign.map(({ wallet, tx }) => wallet.signTransaction(tx)));
1194
- signedTxs.push(...hopSignedTxs);
1195
- }
1196
- // ========== 第7步:按地址数量收取固定费用(原生代币) ==========
1197
- const activeHopAddressCount = sweepAmounts.filter(a => a > 0n).length;
1198
- if (extractProfit && activeHopAddressCount > 0) {
1199
- // ✅ 确定费用支付者:优先使用 targetWallet,否则使用归集金额最大的源钱包
1200
- let maxSweepIndex = -1;
1201
- let maxSweepAmount = 0n;
1202
- for (let i = 0; i < sweepAmounts.length; i++) {
1203
- if (sweepAmounts[i] > maxSweepAmount) {
1204
- maxSweepAmount = sweepAmounts[i];
1205
- maxSweepIndex = i;
1206
- }
1207
- }
1208
- const useTargetAsPayerHop = targetWallet !== null;
1209
- const profitPayerWalletHop = useTargetAsPayerHop ? targetWallet : (maxSweepIndex >= 0 ? sourceWallets[maxSweepIndex] : null);
1210
- // ✅ 按地址数量收取固定费用
1211
- const nativeProfitAmount = calculateTransferFee(chainIdNum, activeHopAddressCount);
1212
- totalProfit = nativeProfitAmount;
1213
- console.log(`[sweep with hops] 按地址收费: ${activeHopAddressCount} 个地址 × ${ethers.formatEther(calculateTransferFee(chainIdNum, 1))} = ${ethers.formatEther(nativeProfitAmount)} 原生币`);
1214
- // ✅ 费用多跳转账(强制 2 跳中转)
1215
- if (nativeProfitAmount > 0n && profitPayerWalletHop) {
1216
- let profitNonce;
1217
- if (useTargetAsPayerHop && targetWalletNonceStart !== undefined) {
1218
- profitNonce = targetWalletNonceStart + targetWalletNonceUsed;
1219
- targetWalletNonceUsed += 1;
1220
- console.log(`[sweep with hops] targetWallet 费用交易 nonce: ${profitNonce} (起点=${targetWalletNonceStart}, 已用=${targetWalletNonceUsed})`);
1221
- }
1222
- else {
1223
- profitNonce = await nonceManager.getNextNonce(profitPayerWalletHop);
1224
- }
1225
- const profitHopResult = await buildProfitHopTransactions({
1226
- provider,
1227
- payerWallet: profitPayerWalletHop,
1228
- profitAmount: nativeProfitAmount,
1229
- profitRecipient: profitAddr,
1230
- hopCount: PROFIT_HOP_COUNT,
1231
- gasPrice,
1232
- chainId: chainIdNum,
1233
- txType,
1234
- startNonce: profitNonce
1235
- });
1236
- signedTxs.push(...profitHopResult.signedTransactions);
1237
- profitHopWallets = profitHopResult.hopWallets;
1238
- }
1239
- }
1240
- }
1241
- // ✅ 简化返回:贿赂交易放在最前面,然后是签名交易、多跳钱包和元数据
1242
- return {
1243
- signedTransactions: [...bribeSignedTx, ...signedTxs],
1244
- hopWallets: preparedHops || undefined,
1245
- profitHopWallets, // ✅ 返回利润多跳钱包
1246
- metadata: extractProfit ? {
1247
- totalAmount: isNative ? ethers.formatEther(totalAmountBeforeProfit) : ethers.formatUnits(totalAmountBeforeProfit, tokenDecimals ?? 18),
1248
- profitAmount: ethers.formatEther(totalProfit), // ✅ 利润统一用原生代币(BNB/ETH)显示
1249
- profitRecipient: profitAddr,
1250
- sourceCount: actualKeys.length,
1251
- isNative,
1252
- tokenAddress: isNative ? undefined : tokenAddress,
1253
- hasBribeTx: bribeSignedTx.length > 0, // ✅ 标记是否有贿赂交易
1254
- bribeAmount: bribeSignedTx.length > 0 ? ethers.formatEther(bribeAmount) : undefined
1255
- } : undefined
1256
- };
1257
- }
1258
- /**
1259
- * 多对多(地址一一对应)转账(仅签名版本 - 不依赖 Merkle)
1260
- * - 支持原生币 / ERC20
1261
- * - 支持多跳(逐对)
1262
- * - 支持利润刮取:利润由第一个 sender 支付(作为额外费用,不扣减每对转账金额)
1263
- */
1264
- export async function pairwiseTransferWithBundleMerkle(params) {
1265
- const { senderPrivateKeys, receiverAddresses, amount, amounts, tokenAddress, tokenDecimals, hopCount = 0, hopPrivateKeys, config, startNonce, } = params;
1266
- if (!senderPrivateKeys || senderPrivateKeys.length === 0) {
1267
- return { signedTransactions: [], hopWallets: undefined };
1268
- }
1269
- if (!receiverAddresses || receiverAddresses.length === 0) {
1270
- return { signedTransactions: [], hopWallets: undefined };
1271
- }
1272
- if (senderPrivateKeys.length !== receiverAddresses.length) {
1273
- throw new Error(`senderPrivateKeys length (${senderPrivateKeys.length}) must match receiverAddresses length (${receiverAddresses.length})`);
1274
- }
1275
- const pairCount = senderPrivateKeys.length;
1276
- const normalizedAmounts = (() => {
1277
- if (amounts && amounts.length > 0) {
1278
- if (amounts.length !== pairCount) {
1279
- throw new Error(`amounts length (${amounts.length}) must match pair count (${pairCount})`);
1280
- }
1281
- return amounts.map(a => (typeof a === 'bigint' ? a.toString() : String(a)));
1282
- }
1283
- if (amount !== undefined && String(amount).trim().length > 0) {
1284
- const v = typeof amount === 'bigint' ? amount.toString() : String(amount);
1285
- return new Array(pairCount).fill(v);
1286
- }
1287
- throw new Error('Either amount or amounts must be provided');
1288
- })();
1289
- const chainIdNum = config.chainId ?? CHAINS.BSC.chainId;
1290
- const chainName = chainIdNum === CHAINS.MONAD.chainId ? 'Monad' : chainIdNum === CHAINS.BSC.chainId ? 'BSC' : `Chain-${chainIdNum}`;
1291
- const provider = new ethers.JsonRpcProvider(config.rpcUrl, { chainId: chainIdNum, name: chainName });
1292
- const txType = getTxType(config);
1293
- const isNative = _isNativeTokenAddress(tokenAddress);
1294
- const nonceManager = new NonceManager(provider);
1295
- // hop 私钥链优先使用传入
1296
- const providedHops = (() => {
1297
- if (hopPrivateKeys && hopPrivateKeys.length > 0) {
1298
- if (hopPrivateKeys.length !== pairCount) {
1299
- throw new Error(`hopPrivateKeys length (${hopPrivateKeys.length}) must match pair count (${pairCount})`);
1300
- }
1301
- return hopPrivateKeys.every(h => h.length === 0) ? null : hopPrivateKeys;
1302
- }
1303
- return null;
1304
- })();
1305
- const preparedHops = providedHops ?? _generateHopWallets(pairCount, hopCount);
1306
- const hasHops = preparedHops !== null;
1307
- const maxHopCount = hasHops ? Math.max(...preparedHops.map(h => h.length)) : 0;
1308
- const finalGasLimit = _calculateGasLimit(config, isNative, hasHops, maxHopCount);
1309
- const nativeGasLimit = (config.prefer21000ForNative ?? false) ? BRIBE_GAS_LIMIT : finalGasLimit;
1310
- // 与 disperse/swap.ts 保持一致:多跳场景固定 gas limit
1311
- const nativeTransferGasLimit = NATIVE_TRANSFER_GAS_LIMIT;
1312
- const erc20TransferGasLimit = GAS_LIMITS.ERC20_TRANSFER;
1313
- const [gasPrice, decimals] = await Promise.all([
1314
- getOptimizedGasPrice(provider, getGasPriceConfig(config)),
1315
- isNative ? Promise.resolve(18) : Promise.resolve(tokenDecimals ?? await _getErc20DecimalsMerkle(provider, tokenAddress, chainIdNum))
1316
- ]);
1317
- const gasFields = buildGasFields(txType, gasPrice);
1318
- const iface = isNative ? null : new ethers.Interface(['function transfer(address,uint256) returns (bool)']);
1319
- // ✅ 费用:按地址数量收取固定费用(原生代币),由第一个 sender 支付
1320
- const extractProfit = shouldExtractProfit(config);
1321
- const profitAddr = getProfitRecipient();
1322
- let totalAmountBeforeProfit = 0n;
1323
- let totalProfitNative = 0n;
1324
- const parsedAmountsWei = normalizedAmounts.map(v => {
1325
- const amt = isNative ? ethers.parseEther(v) : ethers.parseUnits(v, decimals);
1326
- totalAmountBeforeProfit += amt;
1327
- return amt;
1328
- });
1329
- // ✅ 按地址数量收取固定费用
1330
- if (extractProfit && pairCount > 0) {
1331
- totalProfitNative = calculateTransferFee(chainIdNum, pairCount);
1332
- console.log(`[pairwise] 按地址收费: ${pairCount} 个地址 × ${ethers.formatEther(calculateTransferFee(chainIdNum, 1))} = ${ethers.formatEther(totalProfitNative)} 原生币`);
1333
- }
1334
- // ✅ BSC 链贿赂支持(由第一个 sender 支付)
1335
- const bribeAmount = chainIdNum === CHAINS.BSC.chainId ? getBribeAmount(config) : 0n;
1336
- const needBribeTx = bribeAmount > 0n;
1337
- const bribeSignedTx = [];
1338
- // 计算每个 sender 需要的 nonce 数量(聚合到地址)
1339
- const senderWallets = senderPrivateKeys.map(pk => new Wallet(pk, provider));
1340
- const senderAddrLowerList = senderWallets.map(w => w.address.toLowerCase());
1341
- const firstSenderAddrLower = senderAddrLowerList[0];
1342
- const nonceNeedBySender = new Map();
1343
- for (let i = 0; i < pairCount; i++) {
1344
- const addrLower = senderAddrLowerList[i];
1345
- const hopLen = preparedHops ? preparedHops[i].length : 0;
1346
- const perPairTxCount = (() => {
1347
- if (isNative)
1348
- return 1;
1349
- return hopLen > 0 ? 2 : 1;
1350
- })();
1351
- const cur = nonceNeedBySender.get(addrLower);
1352
- if (cur)
1353
- cur.count += perPairTxCount;
1354
- else
1355
- nonceNeedBySender.set(addrLower, { wallet: senderWallets[i], count: perPairTxCount });
1356
- }
1357
- // ✅ 贿赂交易需要 1 个额外的 nonce
1358
- if (needBribeTx) {
1359
- const cur = nonceNeedBySender.get(firstSenderAddrLower);
1360
- if (cur)
1361
- cur.count += 1;
1362
- }
1363
- if (extractProfit && totalProfitNative > 0n) {
1364
- const cur = nonceNeedBySender.get(firstSenderAddrLower);
1365
- if (cur)
1366
- cur.count += 1;
1367
- }
1368
- const nonceQueueBySender = new Map();
1369
- for (const [addrLower, entry] of nonceNeedBySender.entries()) {
1370
- const count = entry.count;
1371
- const nonces = (addrLower === firstSenderAddrLower && startNonce !== undefined)
1372
- ? Array.from({ length: count }, (_, i) => startNonce + i)
1373
- : await nonceManager.getNextNonceBatch(entry.wallet, count);
1374
- nonceQueueBySender.set(addrLower, nonces);
1375
- }
1376
- const popNonce = (addrLower) => {
1377
- const q = nonceQueueBySender.get(addrLower);
1378
- if (!q || q.length === 0)
1379
- throw new Error(`nonce queue empty for sender ${addrLower}`);
1380
- return q.shift();
1381
- };
1382
- const txsToSign = [];
1383
- const nativeHopGasFee = nativeTransferGasLimit * gasPrice;
1384
- const erc20HopGasFee = erc20TransferGasLimit * gasPrice;
1385
- const nativeHopGasFeeForErc20 = nativeTransferGasLimit * gasPrice;
1386
- for (let i = 0; i < pairCount; i++) {
1387
- const senderWallet = senderWallets[i];
1388
- const senderLower = senderAddrLowerList[i];
1389
- const to = receiverAddresses[i];
1390
- const amtWei = parsedAmountsWei[i];
1391
- const hopChain = preparedHops ? preparedHops[i] : [];
1392
- if (!hopChain || hopChain.length === 0) {
1393
- const nonce = popNonce(senderLower);
1394
- if (isNative) {
1395
- txsToSign.push({
1396
- wallet: senderWallet,
1397
- tx: { to, value: amtWei, nonce, gasLimit: nativeGasLimit, chainId: chainIdNum, ...gasFields }
1398
- });
1399
- }
1400
- else {
1401
- const data = iface.encodeFunctionData('transfer', [to, amtWei]);
1402
- txsToSign.push({
1403
- wallet: senderWallet,
1404
- tx: { to: tokenAddress, data, value: 0n, nonce, gasLimit: finalGasLimit, chainId: chainIdNum, ...gasFields }
1405
- });
1406
- }
1407
- continue;
1408
- }
1409
- const fullChain = [senderWallet, ...hopChain.map(w => new Wallet(typeof w === 'string' ? w : w.privateKey, provider))];
1410
- const addresses = [...fullChain.map(w => w.address), to];
1411
- if (isNative) {
1412
- for (let j = 0; j < addresses.length - 1; j++) {
1413
- const fromWallet = fullChain[j];
1414
- const toAddress = addresses[j + 1];
1415
- const nonce = j === 0 ? popNonce(senderLower) : 0;
1416
- const remainingHops = addresses.length - 2 - j;
1417
- const additionalGas = nativeHopGasFee * BigInt(remainingHops);
1418
- const transferValue = amtWei + additionalGas;
1419
- txsToSign.push({
1420
- wallet: fromWallet,
1421
- tx: { to: toAddress, value: transferValue, nonce, gasLimit: nativeTransferGasLimit, chainId: chainIdNum, ...gasFields }
1422
- });
1423
- }
1424
- }
1425
- else {
1426
- const hopGasNeeds = [];
1427
- for (let j = hopChain.length - 1; j >= 0; j--) {
1428
- if (j === hopChain.length - 1)
1429
- hopGasNeeds.unshift(erc20HopGasFee);
1430
- else {
1431
- const nextHopGas = hopGasNeeds[0];
1432
- hopGasNeeds.unshift(nativeHopGasFeeForErc20 + erc20HopGasFee + nextHopGas);
1433
- }
1434
- }
1435
- txsToSign.push({
1436
- wallet: senderWallet,
1437
- tx: {
1438
- to: fullChain[1].address,
1439
- value: hopGasNeeds[0],
1440
- nonce: popNonce(senderLower),
1441
- gasLimit: nativeTransferGasLimit,
1442
- chainId: chainIdNum,
1443
- ...gasFields
1444
- }
1445
- });
1446
- const mainToFirstHopData = iface.encodeFunctionData('transfer', [fullChain[1].address, amtWei]);
1447
- txsToSign.push({
1448
- wallet: senderWallet,
1449
- tx: {
1450
- to: tokenAddress,
1451
- data: mainToFirstHopData,
1452
- value: 0n,
1453
- nonce: popNonce(senderLower),
1454
- gasLimit: erc20TransferGasLimit,
1455
- chainId: chainIdNum,
1456
- ...gasFields
1457
- }
1458
- });
1459
- // hop wallets:逐层传递
1460
- for (let j = 1; j < fullChain.length; j++) {
1461
- const fromWallet = fullChain[j];
1462
- const toAddress = addresses[j + 1];
1463
- const isLastHop = j === fullChain.length - 1;
1464
- if (!isLastHop) {
1465
- const gasToTransfer = hopGasNeeds[j];
1466
- txsToSign.push({
1467
- wallet: fromWallet,
1468
- tx: {
1469
- to: toAddress,
1470
- value: gasToTransfer,
1471
- nonce: 0,
1472
- gasLimit: nativeTransferGasLimit,
1473
- chainId: chainIdNum,
1474
- ...gasFields
1475
- }
1476
- });
1477
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, amtWei]);
1478
- txsToSign.push({
1479
- wallet: fromWallet,
1480
- tx: {
1481
- to: tokenAddress,
1482
- data: erc20Data,
1483
- value: 0n,
1484
- nonce: 1,
1485
- gasLimit: erc20TransferGasLimit,
1486
- chainId: chainIdNum,
1487
- ...gasFields
1488
- }
1489
- });
1490
- }
1491
- else {
1492
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, amtWei]);
1493
- txsToSign.push({
1494
- wallet: fromWallet,
1495
- tx: {
1496
- to: tokenAddress,
1497
- data: erc20Data,
1498
- value: 0n,
1499
- nonce: 0,
1500
- gasLimit: erc20TransferGasLimit,
1501
- chainId: chainIdNum,
1502
- ...gasFields
1503
- }
1504
- });
1505
- }
1506
- }
1507
- }
1508
- }
1509
- if (needBribeTx) {
1510
- const firstSenderWallet = senderWallets[0];
1511
- const bribeNonce = popNonce(firstSenderAddrLower);
1512
- const bribeTx = await firstSenderWallet.signTransaction({
1513
- to: BLOCKRAZOR_BUILDER_EOA,
1514
- value: bribeAmount,
1515
- nonce: bribeNonce,
1516
- gasLimit: BRIBE_GAS_LIMIT,
1517
- chainId: chainIdNum,
1518
- ...gasFields
1519
- });
1520
- bribeSignedTx.push(bribeTx);
1521
- console.log(`[pairwise] 贿赂交易已添加: ${ethers.formatEther(bribeAmount)} BNB`);
1522
- }
1523
- const signedTxs = await Promise.all(txsToSign.map(({ wallet, tx }) => wallet.signTransaction(tx)));
1524
- // 利润多跳(固定 2 hop)
1525
- let profitHopWallets;
1526
- if (extractProfit && totalProfitNative > 0n) {
1527
- const firstSenderWallet = senderWallets[0];
1528
- const profitNonce = popNonce(firstSenderAddrLower);
1529
- const profitHopResult = await buildProfitHopTransactions({
1530
- provider,
1531
- payerWallet: firstSenderWallet,
1532
- profitAmount: totalProfitNative,
1533
- profitRecipient: profitAddr,
1534
- hopCount: PROFIT_HOP_COUNT,
1535
- gasPrice,
1536
- chainId: chainIdNum,
1537
- txType,
1538
- startNonce: profitNonce
1539
- });
1540
- signedTxs.push(...profitHopResult.signedTransactions);
1541
- profitHopWallets = profitHopResult.hopWallets;
1542
- }
1543
- return {
1544
- signedTransactions: [...bribeSignedTx, ...signedTxs], // ✅ 贿赂交易放在最前面
1545
- hopWallets: preparedHops || undefined,
1546
- profitHopWallets,
1547
- metadata: extractProfit ? {
1548
- pairCount,
1549
- isNative,
1550
- tokenAddress: isNative ? undefined : tokenAddress,
1551
- totalAmount: isNative ? ethers.formatEther(totalAmountBeforeProfit) : ethers.formatUnits(totalAmountBeforeProfit, decimals),
1552
- profitAmount: ethers.formatEther(totalProfitNative),
1553
- profitRecipient: profitAddr,
1554
- hasBribeTx: bribeSignedTx.length > 0, // ✅ 标记是否有贿赂交易
1555
- bribeAmount: bribeSignedTx.length > 0 ? ethers.formatEther(bribeAmount) : undefined
1556
- } : undefined
1557
- };
1558
- }