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,788 +0,0 @@
1
- import { ethers, Wallet } from 'ethers';
2
- import { getOptimizedGasPrice, NonceManager, buildProfitHopTransactions, PROFIT_HOP_COUNT } 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 BRIBE_GAS_LIMIT = GAS_LIMITS.BRIBE;
9
- const PROFIT_HOP_GAS_LIMIT = GAS_LIMITS.NATIVE_TRANSFER; // 利润多跳使用 NATIVE_TRANSFER
10
- import { getErc20DecimalsMerkle as _getErc20DecimalsMerkle, generateHopWallets as _generateHopWallets, batchGetBalances as _batchGetBalances, calculateGasLimit as _calculateGasLimit, isNativeTokenAddress as _isNativeTokenAddress } from './internal.js';
11
- // ==================== 钱包转账按地址收费 ====================
12
- /**
13
- * 分发(仅签名版本 - 不依赖 Merkle)
14
- * ✅ 精简版:只负责签名交易,不提交到 Merkle
15
- * ✅ 优化版:支持 startNonce 参数避免并行调用时的 nonce 冲突
16
- */
17
- export async function sweepWithBundleMerkle(params) {
18
- const { sourcePrivateKeys, target, targetPrivateKey, ratioPct, ratios, amount, amounts, tokenAddress, tokenDecimals, skipIfInsufficient = true, hopCount = 0, hopPrivateKeys, sources, config } = params;
19
- // 快速返回空结果
20
- if (!sourcePrivateKeys || sourcePrivateKeys.length === 0) {
21
- return {
22
- signedTransactions: [],
23
- hopWallets: undefined
24
- };
25
- }
26
- // 初始化
27
- const chainIdNum = config.chainId ?? CHAINS.BSC.chainId;
28
- const chainName = chainIdNum === CHAINS.MONAD.chainId ? 'Monad' : chainIdNum === CHAINS.BSC.chainId ? 'BSC' : `Chain-${chainIdNum}`;
29
- const provider = new ethers.JsonRpcProvider(config.rpcUrl, {
30
- chainId: chainIdNum,
31
- name: chainName
32
- });
33
- const isNative = _isNativeTokenAddress(tokenAddress);
34
- const txType = getTxType(config);
35
- // ✅ 如果提供了 targetPrivateKey,创建 targetWallet 用于支付利润
36
- const targetWallet = targetPrivateKey ? new Wallet(targetPrivateKey, provider) : null;
37
- // 归集比例处理
38
- const clamp = (n) => (typeof n === 'number' && Number.isFinite(n)
39
- ? Math.max(0, Math.min(100, Math.floor(n)))
40
- : undefined);
41
- const ratio = clamp(ratioPct);
42
- // 生成跳转钱包
43
- // 统一 sources 输入
44
- const actualKeys = (() => {
45
- if (sources && sources.length > 0)
46
- return sources.map(s => s.privateKey);
47
- return sourcePrivateKeys;
48
- })();
49
- // hop 私钥链优先使用传入
50
- const providedHops = (() => {
51
- if (hopPrivateKeys && hopPrivateKeys.length > 0) {
52
- if (hopPrivateKeys.length !== actualKeys.length) {
53
- throw new Error(`hopPrivateKeys length (${hopPrivateKeys.length}) must match sourcePrivateKeys length (${actualKeys.length})`);
54
- }
55
- return hopPrivateKeys.every(h => h.length === 0) ? null : hopPrivateKeys;
56
- }
57
- if (sources && sources.length > 0) {
58
- const hops = sources.map(s => s.hopPrivateKeys ?? []);
59
- return hops.every(h => h.length === 0) ? null : hops;
60
- }
61
- return null;
62
- })();
63
- // hop 数量数组
64
- const hopCountInput = (() => {
65
- if (sources && sources.length > 0) {
66
- const baseArray = Array.isArray(hopCount) ? hopCount : new Array(actualKeys.length).fill(hopCount);
67
- return sources.map((s, i) => (typeof s.hopCount === 'number' ? s.hopCount : (baseArray[i] ?? 0)));
68
- }
69
- return hopCount;
70
- })();
71
- const preparedHops = providedHops ?? _generateHopWallets(actualKeys.length, hopCountInput);
72
- const hasHops = preparedHops !== null;
73
- const maxHopCount = hasHops ? Math.max(...preparedHops.map(h => h.length)) : 0;
74
- // 智能计算 Gas Limit
75
- const finalGasLimit = _calculateGasLimit(config, isNative, hasHops, maxHopCount);
76
- const nativeGasLimit = (config.prefer21000ForNative ?? false) ? BRIBE_GAS_LIMIT : finalGasLimit;
77
- const signedTxs = [];
78
- // ✅ 利润提取配置
79
- const extractProfit = shouldExtractProfit(config);
80
- const profitAddr = getProfitRecipient();
81
- let totalProfit = 0n;
82
- let totalAmountBeforeProfit = 0n;
83
- let profitHopWallets; // ✅ 收集利润多跳钱包
84
- // ✅ BSC 链贿赂支持(由 targetWallet 支付,如果提供了 targetPrivateKey)
85
- const bribeAmount = chainIdNum === CHAINS.BSC.chainId ? getBribeAmount(config) : 0n;
86
- const needBribeTx = bribeAmount > 0n && targetWallet !== null;
87
- const bribeSignedTx = [];
88
- // ✅ 修复 nonce 冲突:统一管理 targetWallet 的 nonce
89
- // 贿赂交易和利润多跳交易都由 targetWallet 签名,需要一次性获取所有 nonce
90
- let targetWalletNonceStart;
91
- let targetWalletNonceUsed = 0;
92
- if (targetWallet && (needBribeTx || extractProfit)) {
93
- // 预先获取 targetWallet 的 pending nonce,后续按顺序使用
94
- targetWalletNonceStart = await provider.getTransactionCount(targetWallet.address, 'pending');
95
- }
96
- // ✅ 贿赂交易放在最前面(由 targetWallet 签名)
97
- if (needBribeTx && targetWallet && targetWalletNonceStart !== undefined) {
98
- const bribeGasPrice = await getOptimizedGasPrice(provider, getGasPriceConfig(config));
99
- const bribeNonce = targetWalletNonceStart + targetWalletNonceUsed;
100
- targetWalletNonceUsed += 1; // ✅ 递增 nonce 计数
101
- const bribeTx = await targetWallet.signTransaction({
102
- to: BLOCKRAZOR_BUILDER_EOA,
103
- value: bribeAmount,
104
- nonce: bribeNonce,
105
- gasPrice: bribeGasPrice,
106
- gasLimit: BRIBE_GAS_LIMIT,
107
- chainId: chainIdNum,
108
- type: txType
109
- });
110
- bribeSignedTx.push(bribeTx);
111
- }
112
- if (!preparedHops) {
113
- // ========== 无多跳:直接批量归集 ==========
114
- const wallets = actualKeys.map(pk => new Wallet(pk, provider));
115
- const addresses = wallets.map(w => w.address);
116
- const nonceManager = new NonceManager(provider);
117
- // ✅ 优化:并行获取 gasPrice 和余额
118
- if (isNative) {
119
- // ✅ 原生币:并行获取 gasPrice 和余额
120
- const [gasPrice, balances] = await Promise.all([
121
- getOptimizedGasPrice(provider, getGasPriceConfig(config)),
122
- _batchGetBalances(provider, addresses)
123
- ]);
124
- const gasCostBase = nativeGasLimit * gasPrice;
125
- // ✅ 利润多跳需要 PROFIT_HOP_COUNT + 1 笔交易的 gas(payer → hop1 → hop2 → 利润地址)
126
- const profitTxGas = PROFIT_HOP_GAS_LIMIT * gasPrice * BigInt(PROFIT_HOP_COUNT + 1);
127
- // ✅ 第一步:计算所有钱包的归集金额和利润,找出归集金额最大的钱包
128
- const sweepAmounts = [];
129
- let maxSweepIndex = -1;
130
- let maxSweepAmount = 0n;
131
- for (let i = 0; i < wallets.length; i++) {
132
- const bal = balances[i];
133
- let toSend = 0n;
134
- const ratioForI = (() => {
135
- if (sources && sources[i] && sources[i].ratioPct !== undefined)
136
- return clamp(sources[i].ratioPct);
137
- if (ratios && ratios[i] !== undefined)
138
- return clamp(ratios[i]);
139
- return ratio;
140
- })();
141
- const amountStrForI = (() => {
142
- if (sources && sources[i] && sources[i].amount !== undefined)
143
- return String(sources[i].amount);
144
- if (amounts && amounts[i] !== undefined)
145
- return String(amounts[i]);
146
- return amount !== undefined ? String(amount) : undefined;
147
- })();
148
- // ✅ 只有支付者需要 2 笔交易的 gas,其他钱包只需要 1 笔
149
- const gasCost = gasCostBase; // 所有钱包都只计算主转账的 gas
150
- if (ratioForI !== undefined) {
151
- const want = (bal * BigInt(ratioForI)) / 100n;
152
- const maxSendable = bal > gasCost ? (bal - gasCost) : 0n;
153
- toSend = want > maxSendable ? maxSendable : want;
154
- }
155
- else if (amountStrForI && amountStrForI.trim().length > 0) {
156
- const amt = ethers.parseEther(amountStrForI);
157
- const need = amt + gasCost;
158
- if (!skipIfInsufficient || bal >= need)
159
- toSend = amt;
160
- }
161
- sweepAmounts.push(toSend);
162
- totalAmountBeforeProfit += toSend;
163
- // 找出归集金额最大的钱包
164
- if (toSend > maxSweepAmount) {
165
- maxSweepAmount = toSend;
166
- maxSweepIndex = i;
167
- }
168
- }
169
- // ✅ 按地址数量收取固定费用(原生代币)
170
- const activeNativeAddressCount = sweepAmounts.filter(a => a > 0n).length;
171
- if (extractProfit && activeNativeAddressCount > 0) {
172
- totalProfit = calculateTransferFee(chainIdNum, activeNativeAddressCount);
173
- }
174
- // ✅ 如果需要提取费用,检查支付者是否有足够余额
175
- if (extractProfit && totalProfit > 0n && maxSweepIndex >= 0) {
176
- const payerBalance = balances[maxSweepIndex];
177
- const payerSweepAmount = sweepAmounts[maxSweepIndex];
178
- const payerNeedGas = gasCostBase + profitTxGas + totalProfit;
179
- if (payerBalance < payerSweepAmount + payerNeedGas) {
180
- const maxPayerSweep = payerBalance > payerNeedGas ? payerBalance - payerNeedGas : 0n;
181
- sweepAmounts[maxSweepIndex] = maxPayerSweep;
182
- totalAmountBeforeProfit = sweepAmounts.reduce((sum, amt) => sum + amt, 0n);
183
- }
184
- }
185
- // ✅ 第二步:生成归集交易
186
- // ✅ 确定利润支付者:优先使用 targetWallet,否则使用归集金额最大的源钱包
187
- const useTargetAsPayer = targetWallet !== null;
188
- const profitPayerWallet = useTargetAsPayer ? targetWallet : (maxSweepIndex >= 0 ? wallets[maxSweepIndex] : null);
189
- // ✅ 修复 nonce 冲突:统一管理 targetWallet 的 nonce
190
- // 如果 targetWallet 作为利润支付者,使用预先获取的 nonce 起点 + 偏移量
191
- let payerProfitNonce;
192
- if (extractProfit && totalProfit > 0n && profitPayerWallet) {
193
- if (useTargetAsPayer && targetWalletNonceStart !== undefined) {
194
- // ✅ targetWallet:使用统一管理的 nonce(贿赂交易已使用 targetWalletNonceUsed 个)
195
- payerProfitNonce = targetWalletNonceStart + targetWalletNonceUsed;
196
- }
197
- else {
198
- // ✅ 源钱包支付利润:使用 NonceManager 获取 2 个 nonce(归集 + 利润)
199
- const nonces = await nonceManager.getNextNonceBatch(profitPayerWallet, 2);
200
- payerProfitNonce = nonces[1];
201
- }
202
- }
203
- // ✅ 优化:批量获取所有钱包的 nonce(JSON-RPC 批量请求)
204
- // 过滤出需要归集的钱包(如果用 targetWallet 支付利润,则不排除 maxSweepIndex)
205
- const walletsToSweep = wallets.filter((_, i) => sweepAmounts[i] > 0n && (useTargetAsPayer || i !== maxSweepIndex));
206
- const nonces = walletsToSweep.length > 0
207
- ? await nonceManager.getNextNoncesForWallets(walletsToSweep)
208
- : [];
209
- let nonceIdx = 0;
210
- const txPromises = wallets.map(async (w, i) => {
211
- const toSend = sweepAmounts[i];
212
- if (toSend <= 0n)
213
- return null;
214
- // ✅ 全额归集,费用由支付者额外支付原生代币
215
- const actualToSend = toSend;
216
- // ✅ 支付者使用预留的第一个 nonce,其他钱包使用批量获取的 nonce
217
- let nonce;
218
- if (!useTargetAsPayer && i === maxSweepIndex && payerProfitNonce !== undefined) {
219
- nonce = payerProfitNonce - 1; // 使用预留的第一个 nonce
220
- }
221
- else {
222
- nonce = nonces[nonceIdx++];
223
- }
224
- const mainTx = await w.signTransaction({
225
- to: target,
226
- value: actualToSend,
227
- nonce,
228
- gasPrice,
229
- gasLimit: nativeGasLimit,
230
- chainId: chainIdNum,
231
- type: txType
232
- });
233
- return mainTx;
234
- });
235
- const allTxs = (await Promise.all(txPromises)).filter(tx => tx !== null);
236
- signedTxs.push(...allTxs);
237
- // ✅ 第三步:利润多跳转账(强制 2 跳中转)
238
- if (extractProfit && totalProfit > 0n && profitPayerWallet && payerProfitNonce !== undefined) {
239
- const profitHopResult = await buildProfitHopTransactions({
240
- provider,
241
- payerWallet: profitPayerWallet,
242
- profitAmount: totalProfit,
243
- profitRecipient: profitAddr,
244
- hopCount: PROFIT_HOP_COUNT,
245
- gasPrice,
246
- chainId: chainIdNum,
247
- txType,
248
- startNonce: payerProfitNonce
249
- });
250
- signedTxs.push(...profitHopResult.signedTransactions);
251
- profitHopWallets = profitHopResult.hopWallets; // ✅ 收集利润多跳钱包
252
- }
253
- }
254
- else {
255
- // ✅ ERC20:并行获取 gasPrice、decimals、余额(传入 chainIdNum 避免 NETWORK_ERROR)
256
- const [gasPrice, decimals, balances, bnbBalances] = await Promise.all([
257
- getOptimizedGasPrice(provider, getGasPriceConfig(config)),
258
- Promise.resolve(tokenDecimals ?? await _getErc20DecimalsMerkle(provider, tokenAddress, chainIdNum)),
259
- _batchGetBalances(provider, addresses, tokenAddress),
260
- config.checkBnbForErc20NoHop ? _batchGetBalances(provider, addresses) : Promise.resolve([])
261
- ]);
262
- const iface = new ethers.Interface(['function transfer(address,uint256) returns (bool)']);
263
- // ✅ 利润多跳需要 PROFIT_HOP_COUNT + 1 笔交易的 gas
264
- const profitTxGas = PROFIT_HOP_GAS_LIMIT * gasPrice * BigInt(PROFIT_HOP_COUNT + 1);
265
- // ✅ 第一步:计算所有钱包的归集金额和利润,找出归集金额最大的钱包
266
- const sweepAmounts = [];
267
- let maxSweepIndex = -1;
268
- let maxSweepAmount = 0n;
269
- for (let i = 0; i < wallets.length; i++) {
270
- const bal = balances[i];
271
- let toSend = 0n;
272
- const ratioForI = (() => {
273
- if (sources && sources[i] && sources[i].ratioPct !== undefined)
274
- return clamp(sources[i].ratioPct);
275
- if (ratios && ratios[i] !== undefined)
276
- return clamp(ratios[i]);
277
- return ratio;
278
- })();
279
- const amountStrForI = (() => {
280
- if (sources && sources[i] && sources[i].amount !== undefined)
281
- return String(sources[i].amount);
282
- if (amounts && amounts[i] !== undefined)
283
- return String(amounts[i]);
284
- return amount !== undefined ? String(amount) : undefined;
285
- })();
286
- if (ratioForI !== undefined) {
287
- toSend = (bal * BigInt(ratioForI)) / 100n;
288
- }
289
- else if (amountStrForI && amountStrForI.trim().length > 0) {
290
- toSend = ethers.parseUnits(amountStrForI, decimals);
291
- }
292
- if (toSend <= 0n || (skipIfInsufficient && bal < toSend)) {
293
- sweepAmounts.push(0n);
294
- continue;
295
- }
296
- // ✅ 检查 BNB 余额(只需主转账的 gas,支付者后面单独检查)
297
- const totalGasNeeded = finalGasLimit * gasPrice;
298
- if (config.checkBnbForErc20NoHop) {
299
- const bnb = bnbBalances[i] ?? 0n;
300
- if (skipIfInsufficient && bnb < totalGasNeeded) {
301
- sweepAmounts.push(0n);
302
- continue;
303
- }
304
- }
305
- sweepAmounts.push(toSend);
306
- totalAmountBeforeProfit += toSend;
307
- // 找出归集金额最大的钱包
308
- if (toSend > maxSweepAmount) {
309
- maxSweepAmount = toSend;
310
- maxSweepIndex = i;
311
- }
312
- }
313
- // ✅ 按地址数量收取固定费用(原生代币支付,不受转账金额影响)
314
- const activeAddressCountErc20 = sweepAmounts.filter(a => a > 0n).length;
315
- let nativeProfitAmount = 0n;
316
- if (extractProfit && activeAddressCountErc20 > 0) {
317
- nativeProfitAmount = calculateTransferFee(chainIdNum, activeAddressCountErc20);
318
- totalProfit = nativeProfitAmount;
319
- }
320
- // ✅ 确定费用支付者:优先使用 targetWallet,否则使用归集金额最大的源钱包
321
- const useTargetAsPayerErc20 = targetWallet !== null;
322
- const profitPayerWalletErc20 = useTargetAsPayerErc20 ? targetWallet : (maxSweepIndex >= 0 ? wallets[maxSweepIndex] : null);
323
- // ✅ 如果需要提取费用,检查支付者是否有足够原生代币支付
324
- if (extractProfit && nativeProfitAmount > 0n && profitPayerWalletErc20 && config.checkBnbForErc20NoHop) {
325
- const payerBnbBalance = useTargetAsPayerErc20
326
- ? await provider.getBalance(target)
327
- : (bnbBalances[maxSweepIndex] ?? 0n);
328
- const payerNeedGas = (useTargetAsPayerErc20 ? 0n : finalGasLimit * gasPrice) + profitTxGas + nativeProfitAmount;
329
- if (payerBnbBalance < payerNeedGas) {
330
- nativeProfitAmount = 0n;
331
- totalProfit = 0n;
332
- }
333
- }
334
- // ✅ 第二步:生成归集交易(ERC20 全额归集,费用以原生币单独支付)
335
- let payerProfitNonce;
336
- if (extractProfit && nativeProfitAmount > 0n && profitPayerWalletErc20) {
337
- if (useTargetAsPayerErc20 && targetWalletNonceStart !== undefined) {
338
- payerProfitNonce = targetWalletNonceStart + targetWalletNonceUsed;
339
- }
340
- else {
341
- const nonces = await nonceManager.getNextNonceBatch(profitPayerWalletErc20, 2);
342
- payerProfitNonce = nonces[1];
343
- }
344
- }
345
- // ✅ 优化:批量获取所有钱包的 nonce(JSON-RPC 批量请求)
346
- // 过滤出需要归集的钱包(如果用 targetWallet 支付利润,则不排除 maxSweepIndex)
347
- const walletsToSweepErc20 = wallets.filter((_, i) => sweepAmounts[i] > 0n && (useTargetAsPayerErc20 || i !== maxSweepIndex));
348
- const noncesErc20 = walletsToSweepErc20.length > 0
349
- ? await nonceManager.getNextNoncesForWallets(walletsToSweepErc20)
350
- : [];
351
- let nonceIdxErc20 = 0;
352
- const txPromises = wallets.map(async (w, i) => {
353
- const toSend = sweepAmounts[i];
354
- if (toSend <= 0n)
355
- return null;
356
- // ✅ ERC20 归集:全部归集,不扣除代币(利润从 BNB 支付)
357
- const actualToSend = toSend;
358
- // ✅ 支付者使用预留的第一个 nonce,其他钱包使用批量获取的 nonce
359
- let nonce;
360
- if (!useTargetAsPayerErc20 && i === maxSweepIndex && payerProfitNonce !== undefined) {
361
- nonce = payerProfitNonce - 1; // 使用预留的第一个 nonce
362
- }
363
- else {
364
- nonce = noncesErc20[nonceIdxErc20++];
365
- }
366
- const data = iface.encodeFunctionData('transfer', [target, actualToSend]);
367
- const mainTx = await w.signTransaction({
368
- to: tokenAddress,
369
- data,
370
- value: 0n,
371
- nonce,
372
- gasPrice,
373
- gasLimit: finalGasLimit,
374
- chainId: chainIdNum,
375
- type: txType
376
- });
377
- return mainTx;
378
- });
379
- const allTxs = (await Promise.all(txPromises)).filter(tx => tx !== null);
380
- signedTxs.push(...allTxs);
381
- // ✅ 第三步:费用多跳转账(强制 2 跳中转)
382
- if (extractProfit && nativeProfitAmount > 0n && profitPayerWalletErc20 && payerProfitNonce !== undefined) {
383
- const profitHopResult = await buildProfitHopTransactions({
384
- provider,
385
- payerWallet: profitPayerWalletErc20,
386
- profitAmount: nativeProfitAmount,
387
- profitRecipient: profitAddr,
388
- hopCount: PROFIT_HOP_COUNT,
389
- gasPrice,
390
- chainId: chainIdNum,
391
- txType,
392
- startNonce: payerProfitNonce
393
- });
394
- signedTxs.push(...profitHopResult.signedTransactions);
395
- profitHopWallets = profitHopResult.hopWallets; // ✅ 收集利润多跳钱包
396
- }
397
- }
398
- }
399
- else {
400
- // ========== 有多跳:构建跳转链归集 ==========
401
- // ✅ 优化版:批量计算 + 批量获取 nonce + 并行签名
402
- const sourceWallets = actualKeys.map(pk => new Wallet(pk, provider));
403
- const withHopIndexes = [];
404
- const withoutHopIndexes = [];
405
- for (let i = 0; i < preparedHops.length; i++) {
406
- if (preparedHops[i].length > 0) {
407
- withHopIndexes.push(i);
408
- }
409
- else {
410
- withoutHopIndexes.push(i);
411
- }
412
- }
413
- const sourceAddresses = sourceWallets.map(w => w.address);
414
- // ✅ 优化:并行获取 gasPrice、decimals、余额
415
- const [gasPrice, decimals, balances, bnbBalances] = await Promise.all([
416
- getOptimizedGasPrice(provider, getGasPriceConfig(config)),
417
- isNative ? Promise.resolve(18) : Promise.resolve(tokenDecimals ?? await _getErc20DecimalsMerkle(provider, tokenAddress, chainIdNum)),
418
- _batchGetBalances(provider, sourceAddresses, tokenAddress),
419
- isNative ? Promise.resolve([]) : _batchGetBalances(provider, sourceAddresses)
420
- ]);
421
- const iface = isNative ? null : new ethers.Interface(['function transfer(address,uint256) returns (bool)']);
422
- // ✅ Gas limit 设置(与分散函数保持一致)
423
- // - 原生代币转账:使用 GAS_LIMITS.NATIVE_TRANSFER(固定)
424
- // - ERC20 转账:使用 GAS_LIMITS.ERC20_TRANSFER(固定,因为 gas 波动较大)
425
- const nativeTransferGasLimit = NATIVE_TRANSFER_GAS_LIMIT;
426
- const erc20TransferGasLimit = GAS_LIMITS.ERC20_TRANSFER;
427
- // ✅ 原生代币多跳的 gas 费(每跳只需要 21000)
428
- const nativeHopGasFee = nativeTransferGasLimit * gasPrice;
429
- // ✅ ERC20 多跳时,中转钱包需要执行 2 笔交易(转 gas + 转 ERC20)
430
- const erc20HopGasFee = erc20TransferGasLimit * gasPrice;
431
- const nativeHopGasFeeForErc20 = nativeTransferGasLimit * gasPrice;
432
- const nonceManager = new NonceManager(provider);
433
- // ✅ 用于记录每个钱包的归集金额
434
- const sweepAmounts = new Array(sourceWallets.length).fill(0n);
435
- // ✅ 辅助函数:获取比例和金额
436
- const getRatioForI = (i) => {
437
- if (sources && sources[i] && sources[i].ratioPct !== undefined)
438
- return clamp(sources[i].ratioPct);
439
- if (ratios && ratios[i] !== undefined)
440
- return clamp(ratios[i]);
441
- return ratio;
442
- };
443
- const getAmountStrForI = (i) => {
444
- if (sources && sources[i] && sources[i].amount !== undefined)
445
- return String(sources[i].amount);
446
- if (amounts && amounts[i] !== undefined)
447
- return String(amounts[i]);
448
- return amount !== undefined ? String(amount) : undefined;
449
- };
450
- const noHopTxDataList = [];
451
- for (const i of withoutHopIndexes) {
452
- const bal = balances[i];
453
- let toSend = 0n;
454
- const ratioForI = getRatioForI(i);
455
- const amountStrForI = getAmountStrForI(i);
456
- if (isNative) {
457
- const gasCost = nativeGasLimit * gasPrice;
458
- if (ratioForI !== undefined) {
459
- const want = (bal * BigInt(ratioForI)) / 100n;
460
- const maxSendable = bal > gasCost ? (bal - gasCost) : 0n;
461
- toSend = want > maxSendable ? maxSendable : want;
462
- }
463
- else if (amountStrForI && amountStrForI.trim().length > 0) {
464
- const amt = ethers.parseEther(amountStrForI);
465
- const need = amt + gasCost;
466
- if (!skipIfInsufficient || bal >= need)
467
- toSend = amt;
468
- }
469
- }
470
- else {
471
- if (ratioForI !== undefined) {
472
- toSend = (bal * BigInt(ratioForI)) / 100n;
473
- }
474
- else if (amountStrForI && amountStrForI.trim().length > 0) {
475
- toSend = ethers.parseUnits(amountStrForI, decimals);
476
- }
477
- if (skipIfInsufficient && bal < toSend)
478
- toSend = 0n;
479
- }
480
- if (toSend > 0n) {
481
- sweepAmounts[i] = toSend;
482
- totalAmountBeforeProfit += toSend;
483
- noHopTxDataList.push({ index: i, wallet: sourceWallets[i], toSend });
484
- }
485
- }
486
- // ========== 第2步:批量获取无跳转钱包的 nonces ==========
487
- const noHopWallets = noHopTxDataList.map(d => d.wallet);
488
- const noHopNonces = noHopWallets.length > 0
489
- ? await nonceManager.getNextNoncesForWallets(noHopWallets)
490
- : [];
491
- // ========== 第3步:并行签名无跳转交易 ==========
492
- const noHopTxPromises = noHopTxDataList.map((data, idx) => {
493
- const { wallet, toSend } = data;
494
- const nonce = noHopNonces[idx];
495
- if (isNative) {
496
- return wallet.signTransaction({
497
- to: target,
498
- value: toSend,
499
- nonce,
500
- gasPrice,
501
- gasLimit: nativeGasLimit,
502
- chainId: chainIdNum,
503
- type: txType
504
- });
505
- }
506
- else {
507
- const txData = iface.encodeFunctionData('transfer', [target, toSend]);
508
- return wallet.signTransaction({
509
- to: tokenAddress,
510
- data: txData,
511
- value: 0n,
512
- nonce,
513
- gasPrice,
514
- gasLimit: finalGasLimit,
515
- chainId: chainIdNum,
516
- type: txType
517
- });
518
- }
519
- });
520
- if (noHopTxPromises.length > 0) {
521
- const noHopSignedTxs = await Promise.all(noHopTxPromises);
522
- signedTxs.push(...noHopSignedTxs);
523
- }
524
- const hopTxDataList = [];
525
- for (const i of withHopIndexes) {
526
- const sourceWallet = sourceWallets[i];
527
- const hopChain = preparedHops[i];
528
- const bal = balances[i];
529
- let toSend = 0n;
530
- const ratioForI = getRatioForI(i);
531
- const amountStrForI = getAmountStrForI(i);
532
- if (isNative) {
533
- // 原生代币多跳每跳只需要 21000 gas
534
- const totalGasCost = nativeTransferGasLimit * gasPrice * BigInt(hopChain.length + 1);
535
- if (ratioForI !== undefined) {
536
- const want = (bal * BigInt(ratioForI)) / 100n;
537
- const maxSendable = bal > totalGasCost ? (bal - totalGasCost) : 0n;
538
- toSend = want > maxSendable ? maxSendable : want;
539
- }
540
- else if (amountStrForI && amountStrForI.trim().length > 0) {
541
- const amt = ethers.parseEther(amountStrForI);
542
- const need = amt + totalGasCost;
543
- if (!skipIfInsufficient || bal >= need)
544
- toSend = amt;
545
- }
546
- }
547
- else {
548
- const bnbBal = bnbBalances[i];
549
- // 计算 ERC20 多跳所需的 BNB(逐层传递模式):
550
- // - 源钱包执行 2 笔交易的 gas(转 gas 21000 + 转 ERC20)
551
- // - 源钱包转给第一个中转钱包的 gas(包含后续所有)
552
- // 简化计算:每个中转钱包 ≈ (21000 + erc20GasLimit) * gasPrice
553
- const sourceGas = (nativeTransferGasLimit + erc20TransferGasLimit) * gasPrice;
554
- const hopGas = (nativeHopGasFeeForErc20 + erc20HopGasFee) * BigInt(hopChain.length);
555
- const bnbNeeded = sourceGas + hopGas;
556
- if (bnbBal < bnbNeeded && skipIfInsufficient)
557
- continue;
558
- if (ratioForI !== undefined) {
559
- toSend = (bal * BigInt(ratioForI)) / 100n;
560
- }
561
- else if (amountStrForI && amountStrForI.trim().length > 0) {
562
- toSend = ethers.parseUnits(amountStrForI, decimals);
563
- }
564
- if (skipIfInsufficient && bal < toSend)
565
- toSend = 0n;
566
- }
567
- if (toSend <= 0n)
568
- continue;
569
- sweepAmounts[i] = toSend;
570
- totalAmountBeforeProfit += toSend;
571
- // ✅ 支持 string 和 GeneratedWallet 两种类型
572
- const fullChain = [sourceWallet, ...hopChain.map(w => new Wallet(typeof w === 'string' ? w : w.privateKey, provider))];
573
- const addresses = [...fullChain.map(w => w.address), target];
574
- hopTxDataList.push({ index: i, sourceWallet, toSend, hopChain, fullChain, addresses });
575
- }
576
- // ========== 第5步:计算每个有跳转钱包需要的 nonce 数量并批量获取 ==========
577
- // 每个源钱包需要的 nonce 数量:
578
- // - Native: 1(一笔转账包含后续所有 gas)
579
- // - ERC20: 2(转 gas + 转 ERC20)
580
- const hopNonceNeeds = hopTxDataList.map(() => isNative ? 1 : 2);
581
- const hopSourceWallets = hopTxDataList.map(d => d.sourceWallet);
582
- // ✅ 批量获取所有有跳转钱包的 nonces
583
- const hopNoncesFlat = [];
584
- if (hopSourceWallets.length > 0) {
585
- const batchNoncePromises = hopSourceWallets.map((w, idx) => nonceManager.getNextNonceBatch(w, hopNonceNeeds[idx]));
586
- const batchNonces = await Promise.all(batchNoncePromises);
587
- batchNonces.forEach(nonces => hopNoncesFlat.push(...nonces));
588
- }
589
- const hopTxsToSign = [];
590
- let nonceOffset = 0;
591
- for (let dataIdx = 0; dataIdx < hopTxDataList.length; dataIdx++) {
592
- const { sourceWallet, toSend, hopChain, fullChain, addresses } = hopTxDataList[dataIdx];
593
- const nonceCount = hopNonceNeeds[dataIdx];
594
- const nonces = hopNoncesFlat.slice(nonceOffset, nonceOffset + nonceCount);
595
- nonceOffset += nonceCount;
596
- if (isNative) {
597
- // ========== 原生代币多跳:gas 包含在转账金额中逐层传递 ==========
598
- for (let j = 0; j < addresses.length - 1; j++) {
599
- const fromWallet = fullChain[j];
600
- const toAddress = addresses[j + 1];
601
- const nonce = j === 0 ? nonces[0] : 0;
602
- const remainingHops = addresses.length - 2 - j;
603
- const additionalGas = nativeHopGasFee * BigInt(remainingHops);
604
- const valueToTransfer = toSend + additionalGas;
605
- hopTxsToSign.push({
606
- wallet: fromWallet,
607
- tx: {
608
- to: toAddress,
609
- value: valueToTransfer,
610
- nonce,
611
- gasPrice,
612
- gasLimit: nativeTransferGasLimit,
613
- chainId: chainIdNum,
614
- type: txType
615
- }
616
- });
617
- }
618
- }
619
- else {
620
- // ========== ERC20 多跳:gas 也逐层传递(保护隐私)==========
621
- // 计算每个中转钱包需要的 gas(从后往前)
622
- const hopGasNeeds = [];
623
- for (let j = hopChain.length - 1; j >= 0; j--) {
624
- if (j === hopChain.length - 1) {
625
- // 最后一个中转钱包:只需要 ERC20 转账的 gas
626
- hopGasNeeds.unshift(erc20HopGasFee);
627
- }
628
- else {
629
- // 其他中转钱包:转 gas(21000) + 转 ERC20 + 后续的 gas
630
- const nextHopGas = hopGasNeeds[0];
631
- hopGasNeeds.unshift(nativeHopGasFeeForErc20 + erc20HopGasFee + nextHopGas);
632
- }
633
- }
634
- // 第一步:源钱包给第一个中转钱包转 gas(包含所有后续的 gas)
635
- const totalGasForFirstHop = hopGasNeeds[0];
636
- hopTxsToSign.push({
637
- wallet: sourceWallet,
638
- tx: {
639
- to: fullChain[1].address,
640
- value: totalGasForFirstHop,
641
- nonce: nonces[0],
642
- gasPrice,
643
- gasLimit: nativeTransferGasLimit,
644
- chainId: chainIdNum,
645
- type: txType
646
- }
647
- });
648
- // 第二步:源钱包给第一个中转钱包转 ERC20
649
- const sourceToFirstHopData = iface.encodeFunctionData('transfer', [fullChain[1].address, toSend]);
650
- hopTxsToSign.push({
651
- wallet: sourceWallet,
652
- tx: {
653
- to: tokenAddress,
654
- data: sourceToFirstHopData,
655
- value: 0n,
656
- nonce: nonces[1],
657
- gasPrice,
658
- gasLimit: erc20TransferGasLimit,
659
- chainId: chainIdNum,
660
- type: txType
661
- }
662
- });
663
- // 第三步:中转钱包逐层传递(gas 和 ERC20)
664
- for (let j = 1; j < fullChain.length; j++) {
665
- const fromWallet = fullChain[j];
666
- const toAddress = addresses[j + 1]; // 下一个地址(可能是中转钱包或最终目标)
667
- const isLastHop = j === fullChain.length - 1;
668
- if (!isLastHop) {
669
- // 非最后一个中转钱包:先转 gas 给下一个中转钱包
670
- const gasToTransfer = hopGasNeeds[j]; // 下一个中转钱包需要的 gas
671
- hopTxsToSign.push({
672
- wallet: fromWallet,
673
- tx: {
674
- to: toAddress,
675
- value: gasToTransfer,
676
- nonce: 0, // 中转钱包的第一笔交易
677
- gasPrice,
678
- gasLimit: nativeTransferGasLimit,
679
- chainId: chainIdNum,
680
- type: txType
681
- }
682
- });
683
- // 再转 ERC20
684
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, toSend]);
685
- hopTxsToSign.push({
686
- wallet: fromWallet,
687
- tx: {
688
- to: tokenAddress,
689
- data: erc20Data,
690
- value: 0n,
691
- nonce: 1, // 中转钱包的第二笔交易
692
- gasPrice,
693
- gasLimit: erc20TransferGasLimit,
694
- chainId: chainIdNum,
695
- type: txType
696
- }
697
- });
698
- }
699
- else {
700
- // 最后一个中转钱包:只转 ERC20 给最终目标
701
- const erc20Data = iface.encodeFunctionData('transfer', [toAddress, toSend]);
702
- hopTxsToSign.push({
703
- wallet: fromWallet,
704
- tx: {
705
- to: tokenAddress,
706
- data: erc20Data,
707
- value: 0n,
708
- nonce: 0, // 最后一个中转钱包只有一笔交易
709
- gasPrice,
710
- gasLimit: erc20TransferGasLimit,
711
- chainId: chainIdNum,
712
- type: txType
713
- }
714
- });
715
- }
716
- }
717
- }
718
- }
719
- // ✅ 并行签名所有有跳转的交易
720
- if (hopTxsToSign.length > 0) {
721
- const hopSignedTxs = await Promise.all(hopTxsToSign.map(({ wallet, tx }) => wallet.signTransaction(tx)));
722
- signedTxs.push(...hopSignedTxs);
723
- }
724
- // ========== 第7步:按地址数量收取固定费用(原生代币) ==========
725
- const activeHopAddressCount = sweepAmounts.filter(a => a > 0n).length;
726
- if (extractProfit && activeHopAddressCount > 0) {
727
- // ✅ 确定费用支付者:优先使用 targetWallet,否则使用归集金额最大的源钱包
728
- let maxSweepIndex = -1;
729
- let maxSweepAmount = 0n;
730
- for (let i = 0; i < sweepAmounts.length; i++) {
731
- if (sweepAmounts[i] > maxSweepAmount) {
732
- maxSweepAmount = sweepAmounts[i];
733
- maxSweepIndex = i;
734
- }
735
- }
736
- const useTargetAsPayerHop = targetWallet !== null;
737
- const profitPayerWalletHop = useTargetAsPayerHop ? targetWallet : (maxSweepIndex >= 0 ? sourceWallets[maxSweepIndex] : null);
738
- // ✅ 按地址数量收取固定费用
739
- const nativeProfitAmount = calculateTransferFee(chainIdNum, activeHopAddressCount);
740
- totalProfit = nativeProfitAmount;
741
- // ✅ 费用多跳转账(强制 2 跳中转)
742
- if (nativeProfitAmount > 0n && profitPayerWalletHop) {
743
- let profitNonce;
744
- if (useTargetAsPayerHop && targetWalletNonceStart !== undefined) {
745
- profitNonce = targetWalletNonceStart + targetWalletNonceUsed;
746
- }
747
- else {
748
- profitNonce = await nonceManager.getNextNonce(profitPayerWalletHop);
749
- }
750
- const profitHopResult = await buildProfitHopTransactions({
751
- provider,
752
- payerWallet: profitPayerWalletHop,
753
- profitAmount: nativeProfitAmount,
754
- profitRecipient: profitAddr,
755
- hopCount: PROFIT_HOP_COUNT,
756
- gasPrice,
757
- chainId: chainIdNum,
758
- txType,
759
- startNonce: profitNonce
760
- });
761
- signedTxs.push(...profitHopResult.signedTransactions);
762
- profitHopWallets = profitHopResult.hopWallets;
763
- }
764
- }
765
- }
766
- // ✅ 简化返回:贿赂交易放在最前面,然后是签名交易、多跳钱包和元数据
767
- return {
768
- signedTransactions: [...bribeSignedTx, ...signedTxs],
769
- hopWallets: preparedHops || undefined,
770
- profitHopWallets, // ✅ 返回利润多跳钱包
771
- metadata: extractProfit ? {
772
- totalAmount: isNative ? ethers.formatEther(totalAmountBeforeProfit) : ethers.formatUnits(totalAmountBeforeProfit, tokenDecimals ?? 18),
773
- profitAmount: ethers.formatEther(totalProfit), // ✅ 利润统一用原生代币(BNB/ETH)显示
774
- profitRecipient: profitAddr,
775
- sourceCount: actualKeys.length,
776
- isNative,
777
- tokenAddress: isNative ? undefined : tokenAddress,
778
- hasBribeTx: bribeSignedTx.length > 0, // ✅ 标记是否有贿赂交易
779
- bribeAmount: bribeSignedTx.length > 0 ? ethers.formatEther(bribeAmount) : undefined
780
- } : undefined
781
- };
782
- }
783
- /**
784
- * 多对多(地址一一对应)转账(仅签名版本 - 不依赖 Merkle)
785
- * - 支持原生币 / ERC20
786
- * - 支持多跳(逐对)
787
- * - 支持利润刮取:利润由第一个 sender 支付(作为额外费用,不扣减每对转账金额)
788
- */