four-flap-meme-sdk 2.2.7 → 2.2.10

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