@humanode-hyperlane/rebalancer 0.0.0-stage → 27.2.2-humanode.1

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 (439) hide show
  1. package/LICENSE.md +193 -0
  2. package/README.md +297 -2
  3. package/dist/bridges/LiFiBridge.d.ts +93 -0
  4. package/dist/bridges/LiFiBridge.d.ts.map +1 -0
  5. package/dist/bridges/LiFiBridge.js +527 -0
  6. package/dist/bridges/LiFiBridge.js.map +1 -0
  7. package/dist/bridges/LiFiBridge.test.d.ts +2 -0
  8. package/dist/bridges/LiFiBridge.test.d.ts.map +1 -0
  9. package/dist/bridges/LiFiBridge.test.js +504 -0
  10. package/dist/bridges/LiFiBridge.test.js.map +1 -0
  11. package/dist/config/RebalancerConfig.d.ts +20 -0
  12. package/dist/config/RebalancerConfig.d.ts.map +1 -0
  13. package/dist/config/RebalancerConfig.js +35 -0
  14. package/dist/config/RebalancerConfig.js.map +1 -0
  15. package/dist/config/RebalancerConfig.test.d.ts +2 -0
  16. package/dist/config/RebalancerConfig.test.d.ts.map +1 -0
  17. package/dist/config/RebalancerConfig.test.js +798 -0
  18. package/dist/config/RebalancerConfig.test.js.map +1 -0
  19. package/dist/config/types.d.ts +3008 -0
  20. package/dist/config/types.d.ts.map +1 -0
  21. package/dist/config/types.js +451 -0
  22. package/dist/config/types.js.map +1 -0
  23. package/dist/core/InventoryRebalancer.d.ts +201 -0
  24. package/dist/core/InventoryRebalancer.d.ts.map +1 -0
  25. package/dist/core/InventoryRebalancer.js +994 -0
  26. package/dist/core/InventoryRebalancer.js.map +1 -0
  27. package/dist/core/InventoryRebalancer.test.d.ts +2 -0
  28. package/dist/core/InventoryRebalancer.test.d.ts.map +1 -0
  29. package/dist/core/InventoryRebalancer.test.js +1511 -0
  30. package/dist/core/InventoryRebalancer.test.js.map +1 -0
  31. package/dist/core/Rebalancer.d.ts +37 -0
  32. package/dist/core/Rebalancer.d.ts.map +1 -0
  33. package/dist/core/Rebalancer.js +433 -0
  34. package/dist/core/Rebalancer.js.map +1 -0
  35. package/dist/core/Rebalancer.test.d.ts +2 -0
  36. package/dist/core/Rebalancer.test.d.ts.map +1 -0
  37. package/dist/core/Rebalancer.test.js +424 -0
  38. package/dist/core/Rebalancer.test.js.map +1 -0
  39. package/dist/core/RebalancerOrchestrator.d.ts +56 -0
  40. package/dist/core/RebalancerOrchestrator.d.ts.map +1 -0
  41. package/dist/core/RebalancerOrchestrator.js +154 -0
  42. package/dist/core/RebalancerOrchestrator.js.map +1 -0
  43. package/dist/core/RebalancerOrchestrator.test.d.ts +2 -0
  44. package/dist/core/RebalancerOrchestrator.test.d.ts.map +1 -0
  45. package/dist/core/RebalancerOrchestrator.test.js +721 -0
  46. package/dist/core/RebalancerOrchestrator.test.js.map +1 -0
  47. package/dist/core/RebalancerService.d.ts +127 -0
  48. package/dist/core/RebalancerService.d.ts.map +1 -0
  49. package/dist/core/RebalancerService.js +270 -0
  50. package/dist/core/RebalancerService.js.map +1 -0
  51. package/dist/core/RebalancerService.test.d.ts +2 -0
  52. package/dist/core/RebalancerService.test.d.ts.map +1 -0
  53. package/dist/core/RebalancerService.test.js +777 -0
  54. package/dist/core/RebalancerService.test.js.map +1 -0
  55. package/dist/e2e/collateral-deficit.e2e-test.d.ts +2 -0
  56. package/dist/e2e/collateral-deficit.e2e-test.d.ts.map +1 -0
  57. package/dist/e2e/collateral-deficit.e2e-test.js +227 -0
  58. package/dist/e2e/collateral-deficit.e2e-test.js.map +1 -0
  59. package/dist/e2e/composite.e2e-test.d.ts +2 -0
  60. package/dist/e2e/composite.e2e-test.d.ts.map +1 -0
  61. package/dist/e2e/composite.e2e-test.js +666 -0
  62. package/dist/e2e/composite.e2e-test.js.map +1 -0
  63. package/dist/e2e/fixtures/routes.d.ts +89 -0
  64. package/dist/e2e/fixtures/routes.d.ts.map +1 -0
  65. package/dist/e2e/fixtures/routes.js +420 -0
  66. package/dist/e2e/fixtures/routes.js.map +1 -0
  67. package/dist/e2e/harness/BaseLocalDeploymentManager.d.ts +38 -0
  68. package/dist/e2e/harness/BaseLocalDeploymentManager.d.ts.map +1 -0
  69. package/dist/e2e/harness/BaseLocalDeploymentManager.js +144 -0
  70. package/dist/e2e/harness/BaseLocalDeploymentManager.js.map +1 -0
  71. package/dist/e2e/harness/BridgeSetup.d.ts +11 -0
  72. package/dist/e2e/harness/BridgeSetup.d.ts.map +1 -0
  73. package/dist/e2e/harness/BridgeSetup.js +50 -0
  74. package/dist/e2e/harness/BridgeSetup.js.map +1 -0
  75. package/dist/e2e/harness/Erc20InventoryLocalDeploymentManager.d.ts +13 -0
  76. package/dist/e2e/harness/Erc20InventoryLocalDeploymentManager.d.ts.map +1 -0
  77. package/dist/e2e/harness/Erc20InventoryLocalDeploymentManager.js +105 -0
  78. package/dist/e2e/harness/Erc20InventoryLocalDeploymentManager.js.map +1 -0
  79. package/dist/e2e/harness/Erc20LocalDeploymentManager.d.ts +11 -0
  80. package/dist/e2e/harness/Erc20LocalDeploymentManager.d.ts.map +1 -0
  81. package/dist/e2e/harness/Erc20LocalDeploymentManager.js +105 -0
  82. package/dist/e2e/harness/Erc20LocalDeploymentManager.js.map +1 -0
  83. package/dist/e2e/harness/ForkIndexer.d.ts +23 -0
  84. package/dist/e2e/harness/ForkIndexer.d.ts.map +1 -0
  85. package/dist/e2e/harness/ForkIndexer.js +127 -0
  86. package/dist/e2e/harness/ForkIndexer.js.map +1 -0
  87. package/dist/e2e/harness/ForkIndexer.test.d.ts +2 -0
  88. package/dist/e2e/harness/ForkIndexer.test.d.ts.map +1 -0
  89. package/dist/e2e/harness/ForkIndexer.test.js +257 -0
  90. package/dist/e2e/harness/ForkIndexer.test.js.map +1 -0
  91. package/dist/e2e/harness/MixedLocalDeploymentManager.d.ts +21 -0
  92. package/dist/e2e/harness/MixedLocalDeploymentManager.d.ts.map +1 -0
  93. package/dist/e2e/harness/MixedLocalDeploymentManager.js +115 -0
  94. package/dist/e2e/harness/MixedLocalDeploymentManager.js.map +1 -0
  95. package/dist/e2e/harness/MockExplorerClient.d.ts +23 -0
  96. package/dist/e2e/harness/MockExplorerClient.d.ts.map +1 -0
  97. package/dist/e2e/harness/MockExplorerClient.js +57 -0
  98. package/dist/e2e/harness/MockExplorerClient.js.map +1 -0
  99. package/dist/e2e/harness/MockExternalBridge.d.ts +32 -0
  100. package/dist/e2e/harness/MockExternalBridge.d.ts.map +1 -0
  101. package/dist/e2e/harness/MockExternalBridge.js +247 -0
  102. package/dist/e2e/harness/MockExternalBridge.js.map +1 -0
  103. package/dist/e2e/harness/NativeLocalDeploymentManager.d.ts +13 -0
  104. package/dist/e2e/harness/NativeLocalDeploymentManager.d.ts.map +1 -0
  105. package/dist/e2e/harness/NativeLocalDeploymentManager.js +91 -0
  106. package/dist/e2e/harness/NativeLocalDeploymentManager.js.map +1 -0
  107. package/dist/e2e/harness/SnapshotHelper.d.ts +13 -0
  108. package/dist/e2e/harness/SnapshotHelper.d.ts.map +1 -0
  109. package/dist/e2e/harness/SnapshotHelper.js +36 -0
  110. package/dist/e2e/harness/SnapshotHelper.js.map +1 -0
  111. package/dist/e2e/harness/TestHelpers.d.ts +25 -0
  112. package/dist/e2e/harness/TestHelpers.d.ts.map +1 -0
  113. package/dist/e2e/harness/TestHelpers.js +103 -0
  114. package/dist/e2e/harness/TestHelpers.js.map +1 -0
  115. package/dist/e2e/harness/TestRebalancer.d.ts +85 -0
  116. package/dist/e2e/harness/TestRebalancer.d.ts.map +1 -0
  117. package/dist/e2e/harness/TestRebalancer.js +427 -0
  118. package/dist/e2e/harness/TestRebalancer.js.map +1 -0
  119. package/dist/e2e/harness/TransferHelper.d.ts +34 -0
  120. package/dist/e2e/harness/TransferHelper.d.ts.map +1 -0
  121. package/dist/e2e/harness/TransferHelper.js +93 -0
  122. package/dist/e2e/harness/TransferHelper.js.map +1 -0
  123. package/dist/e2e/inventory-erc20-minAmount.e2e-test.d.ts +2 -0
  124. package/dist/e2e/inventory-erc20-minAmount.e2e-test.d.ts.map +1 -0
  125. package/dist/e2e/inventory-erc20-minAmount.e2e-test.js +411 -0
  126. package/dist/e2e/inventory-erc20-minAmount.e2e-test.js.map +1 -0
  127. package/dist/e2e/inventory-erc20-weighted.e2e-test.d.ts +2 -0
  128. package/dist/e2e/inventory-erc20-weighted.e2e-test.d.ts.map +1 -0
  129. package/dist/e2e/inventory-erc20-weighted.e2e-test.js +408 -0
  130. package/dist/e2e/inventory-erc20-weighted.e2e-test.js.map +1 -0
  131. package/dist/e2e/inventory-minAmount.e2e-test.d.ts +2 -0
  132. package/dist/e2e/inventory-minAmount.e2e-test.d.ts.map +1 -0
  133. package/dist/e2e/inventory-minAmount.e2e-test.js +411 -0
  134. package/dist/e2e/inventory-minAmount.e2e-test.js.map +1 -0
  135. package/dist/e2e/inventory-weighted.e2e-test.d.ts +2 -0
  136. package/dist/e2e/inventory-weighted.e2e-test.d.ts.map +1 -0
  137. package/dist/e2e/inventory-weighted.e2e-test.js +409 -0
  138. package/dist/e2e/inventory-weighted.e2e-test.js.map +1 -0
  139. package/dist/e2e/minAmount.e2e-test.d.ts +2 -0
  140. package/dist/e2e/minAmount.e2e-test.d.ts.map +1 -0
  141. package/dist/e2e/minAmount.e2e-test.js +203 -0
  142. package/dist/e2e/minAmount.e2e-test.js.map +1 -0
  143. package/dist/e2e/mixed-weighted.e2e-test.d.ts +2 -0
  144. package/dist/e2e/mixed-weighted.e2e-test.d.ts.map +1 -0
  145. package/dist/e2e/mixed-weighted.e2e-test.js +189 -0
  146. package/dist/e2e/mixed-weighted.e2e-test.js.map +1 -0
  147. package/dist/e2e/weighted.e2e-test.d.ts +2 -0
  148. package/dist/e2e/weighted.e2e-test.d.ts.map +1 -0
  149. package/dist/e2e/weighted.e2e-test.js +198 -0
  150. package/dist/e2e/weighted.e2e-test.js.map +1 -0
  151. package/dist/factories/RebalancerContextFactory.d.ts +89 -0
  152. package/dist/factories/RebalancerContextFactory.d.ts.map +1 -0
  153. package/dist/factories/RebalancerContextFactory.js +420 -0
  154. package/dist/factories/RebalancerContextFactory.js.map +1 -0
  155. package/dist/factories/RebalancerContextFactory.test.d.ts +2 -0
  156. package/dist/factories/RebalancerContextFactory.test.d.ts.map +1 -0
  157. package/dist/factories/RebalancerContextFactory.test.js +270 -0
  158. package/dist/factories/RebalancerContextFactory.test.js.map +1 -0
  159. package/dist/index.d.ts +37 -0
  160. package/dist/index.d.ts.map +1 -0
  161. package/dist/index.js +37 -0
  162. package/dist/index.js.map +1 -0
  163. package/dist/interfaces/IExternalBridge.d.ts +103 -0
  164. package/dist/interfaces/IExternalBridge.d.ts.map +1 -0
  165. package/dist/interfaces/IExternalBridge.js +2 -0
  166. package/dist/interfaces/IExternalBridge.js.map +1 -0
  167. package/dist/interfaces/IMetrics.d.ts +5 -0
  168. package/dist/interfaces/IMetrics.d.ts.map +1 -0
  169. package/dist/interfaces/IMetrics.js +2 -0
  170. package/dist/interfaces/IMetrics.js.map +1 -0
  171. package/dist/interfaces/IMonitor.d.ts +50 -0
  172. package/dist/interfaces/IMonitor.d.ts.map +1 -0
  173. package/dist/interfaces/IMonitor.js +14 -0
  174. package/dist/interfaces/IMonitor.js.map +1 -0
  175. package/dist/interfaces/IRebalancer.d.ts +31 -0
  176. package/dist/interfaces/IRebalancer.d.ts.map +1 -0
  177. package/dist/interfaces/IRebalancer.js +2 -0
  178. package/dist/interfaces/IRebalancer.js.map +1 -0
  179. package/dist/interfaces/IStrategy.d.ts +60 -0
  180. package/dist/interfaces/IStrategy.d.ts.map +1 -0
  181. package/dist/interfaces/IStrategy.js +13 -0
  182. package/dist/interfaces/IStrategy.js.map +1 -0
  183. package/dist/metrics/Metrics.d.ts +25 -0
  184. package/dist/metrics/Metrics.d.ts.map +1 -0
  185. package/dist/metrics/Metrics.js +164 -0
  186. package/dist/metrics/Metrics.js.map +1 -0
  187. package/dist/metrics/PriceGetter.d.ts +10 -0
  188. package/dist/metrics/PriceGetter.d.ts.map +1 -0
  189. package/dist/metrics/PriceGetter.js +41 -0
  190. package/dist/metrics/PriceGetter.js.map +1 -0
  191. package/dist/metrics/scripts/metrics.d.ts +28 -0
  192. package/dist/metrics/scripts/metrics.d.ts.map +1 -0
  193. package/dist/metrics/scripts/metrics.js +61 -0
  194. package/dist/metrics/scripts/metrics.js.map +1 -0
  195. package/dist/monitor/Monitor.d.ts +40 -0
  196. package/dist/monitor/Monitor.d.ts.map +1 -0
  197. package/dist/monitor/Monitor.js +211 -0
  198. package/dist/monitor/Monitor.js.map +1 -0
  199. package/dist/service.d.ts +3 -0
  200. package/dist/service.d.ts.map +1 -0
  201. package/dist/service.js +205 -0
  202. package/dist/service.js.map +1 -0
  203. package/dist/strategy/BaseStrategy.d.ts +86 -0
  204. package/dist/strategy/BaseStrategy.d.ts.map +1 -0
  205. package/dist/strategy/BaseStrategy.js +342 -0
  206. package/dist/strategy/BaseStrategy.js.map +1 -0
  207. package/dist/strategy/CollateralDeficitStrategy.d.ts +65 -0
  208. package/dist/strategy/CollateralDeficitStrategy.d.ts.map +1 -0
  209. package/dist/strategy/CollateralDeficitStrategy.js +253 -0
  210. package/dist/strategy/CollateralDeficitStrategy.js.map +1 -0
  211. package/dist/strategy/CollateralDeficitStrategy.test.d.ts +2 -0
  212. package/dist/strategy/CollateralDeficitStrategy.test.d.ts.map +1 -0
  213. package/dist/strategy/CollateralDeficitStrategy.test.js +497 -0
  214. package/dist/strategy/CollateralDeficitStrategy.test.js.map +1 -0
  215. package/dist/strategy/CompositeStrategy.d.ts +18 -0
  216. package/dist/strategy/CompositeStrategy.d.ts.map +1 -0
  217. package/dist/strategy/CompositeStrategy.js +63 -0
  218. package/dist/strategy/CompositeStrategy.js.map +1 -0
  219. package/dist/strategy/CompositeStrategy.test.d.ts +2 -0
  220. package/dist/strategy/CompositeStrategy.test.d.ts.map +1 -0
  221. package/dist/strategy/CompositeStrategy.test.js +278 -0
  222. package/dist/strategy/CompositeStrategy.test.js.map +1 -0
  223. package/dist/strategy/MinAmountStrategy.d.ts +35 -0
  224. package/dist/strategy/MinAmountStrategy.d.ts.map +1 -0
  225. package/dist/strategy/MinAmountStrategy.js +112 -0
  226. package/dist/strategy/MinAmountStrategy.js.map +1 -0
  227. package/dist/strategy/MinAmountStrategy.test.d.ts +2 -0
  228. package/dist/strategy/MinAmountStrategy.test.d.ts.map +1 -0
  229. package/dist/strategy/MinAmountStrategy.test.js +547 -0
  230. package/dist/strategy/MinAmountStrategy.test.js.map +1 -0
  231. package/dist/strategy/StrategyFactory.d.ts +27 -0
  232. package/dist/strategy/StrategyFactory.d.ts.map +1 -0
  233. package/dist/strategy/StrategyFactory.js +79 -0
  234. package/dist/strategy/StrategyFactory.js.map +1 -0
  235. package/dist/strategy/StrategyFactory.test.d.ts +2 -0
  236. package/dist/strategy/StrategyFactory.test.d.ts.map +1 -0
  237. package/dist/strategy/StrategyFactory.test.js +81 -0
  238. package/dist/strategy/StrategyFactory.test.js.map +1 -0
  239. package/dist/strategy/WeightedStrategy.d.ts +32 -0
  240. package/dist/strategy/WeightedStrategy.d.ts.map +1 -0
  241. package/dist/strategy/WeightedStrategy.js +73 -0
  242. package/dist/strategy/WeightedStrategy.js.map +1 -0
  243. package/dist/strategy/WeightedStrategy.test.d.ts +2 -0
  244. package/dist/strategy/WeightedStrategy.test.d.ts.map +1 -0
  245. package/dist/strategy/WeightedStrategy.test.js +403 -0
  246. package/dist/strategy/WeightedStrategy.test.js.map +1 -0
  247. package/dist/strategy/index.d.ts +7 -0
  248. package/dist/strategy/index.d.ts.map +1 -0
  249. package/dist/strategy/index.js +7 -0
  250. package/dist/strategy/index.js.map +1 -0
  251. package/dist/test/helpers.d.ts +99 -0
  252. package/dist/test/helpers.d.ts.map +1 -0
  253. package/dist/test/helpers.js +311 -0
  254. package/dist/test/helpers.js.map +1 -0
  255. package/dist/test/lifiMocks.d.ts +52 -0
  256. package/dist/test/lifiMocks.d.ts.map +1 -0
  257. package/dist/test/lifiMocks.js +160 -0
  258. package/dist/test/lifiMocks.js.map +1 -0
  259. package/dist/tracking/ActionTracker.d.ts +90 -0
  260. package/dist/tracking/ActionTracker.d.ts.map +1 -0
  261. package/dist/tracking/ActionTracker.js +678 -0
  262. package/dist/tracking/ActionTracker.js.map +1 -0
  263. package/dist/tracking/ActionTracker.test.d.ts +2 -0
  264. package/dist/tracking/ActionTracker.test.d.ts.map +1 -0
  265. package/dist/tracking/ActionTracker.test.js +1351 -0
  266. package/dist/tracking/ActionTracker.test.js.map +1 -0
  267. package/dist/tracking/IActionTracker.d.ts +157 -0
  268. package/dist/tracking/IActionTracker.d.ts.map +1 -0
  269. package/dist/tracking/IActionTracker.js +2 -0
  270. package/dist/tracking/IActionTracker.js.map +1 -0
  271. package/dist/tracking/InflightContextAdapter.d.ts +18 -0
  272. package/dist/tracking/InflightContextAdapter.d.ts.map +1 -0
  273. package/dist/tracking/InflightContextAdapter.js +52 -0
  274. package/dist/tracking/InflightContextAdapter.js.map +1 -0
  275. package/dist/tracking/InflightContextAdapter.test.d.ts +2 -0
  276. package/dist/tracking/InflightContextAdapter.test.d.ts.map +1 -0
  277. package/dist/tracking/InflightContextAdapter.test.js +175 -0
  278. package/dist/tracking/InflightContextAdapter.test.js.map +1 -0
  279. package/dist/tracking/store/IStore.d.ts +41 -0
  280. package/dist/tracking/store/IStore.d.ts.map +1 -0
  281. package/dist/tracking/store/IStore.js +2 -0
  282. package/dist/tracking/store/IStore.js.map +1 -0
  283. package/dist/tracking/store/InMemoryStore.d.ts +21 -0
  284. package/dist/tracking/store/InMemoryStore.d.ts.map +1 -0
  285. package/dist/tracking/store/InMemoryStore.js +40 -0
  286. package/dist/tracking/store/InMemoryStore.js.map +1 -0
  287. package/dist/tracking/store/InMemoryStore.test.d.ts +2 -0
  288. package/dist/tracking/store/InMemoryStore.test.d.ts.map +1 -0
  289. package/dist/tracking/store/InMemoryStore.test.js +290 -0
  290. package/dist/tracking/store/InMemoryStore.test.js.map +1 -0
  291. package/dist/tracking/store/index.d.ts +3 -0
  292. package/dist/tracking/store/index.d.ts.map +1 -0
  293. package/dist/tracking/store/index.js +2 -0
  294. package/dist/tracking/store/index.js.map +1 -0
  295. package/dist/tracking/types.d.ts +77 -0
  296. package/dist/tracking/types.d.ts.map +1 -0
  297. package/dist/tracking/types.js +2 -0
  298. package/dist/tracking/types.js.map +1 -0
  299. package/dist/utils/ExplorerClient.d.ts +68 -0
  300. package/dist/utils/ExplorerClient.d.ts.map +1 -0
  301. package/dist/utils/ExplorerClient.js +324 -0
  302. package/dist/utils/ExplorerClient.js.map +1 -0
  303. package/dist/utils/ExplorerClient.test.d.ts +2 -0
  304. package/dist/utils/ExplorerClient.test.d.ts.map +1 -0
  305. package/dist/utils/ExplorerClient.test.js +261 -0
  306. package/dist/utils/ExplorerClient.test.js.map +1 -0
  307. package/dist/utils/balanceUtils.d.ts +12 -0
  308. package/dist/utils/balanceUtils.d.ts.map +1 -0
  309. package/dist/utils/balanceUtils.js +40 -0
  310. package/dist/utils/balanceUtils.js.map +1 -0
  311. package/dist/utils/balanceUtils.test.d.ts +2 -0
  312. package/dist/utils/balanceUtils.test.d.ts.map +1 -0
  313. package/dist/utils/balanceUtils.test.js +55 -0
  314. package/dist/utils/balanceUtils.test.js.map +1 -0
  315. package/dist/utils/blockTag.d.ts +14 -0
  316. package/dist/utils/blockTag.d.ts.map +1 -0
  317. package/dist/utils/blockTag.js +46 -0
  318. package/dist/utils/blockTag.js.map +1 -0
  319. package/dist/utils/bridgeUtils.d.ts +40 -0
  320. package/dist/utils/bridgeUtils.d.ts.map +1 -0
  321. package/dist/utils/bridgeUtils.js +54 -0
  322. package/dist/utils/bridgeUtils.js.map +1 -0
  323. package/dist/utils/bridgeUtils.test.d.ts +2 -0
  324. package/dist/utils/bridgeUtils.test.d.ts.map +1 -0
  325. package/dist/utils/bridgeUtils.test.js +163 -0
  326. package/dist/utils/bridgeUtils.test.js.map +1 -0
  327. package/dist/utils/errors.d.ts +4 -0
  328. package/dist/utils/errors.d.ts.map +1 -0
  329. package/dist/utils/errors.js +6 -0
  330. package/dist/utils/errors.js.map +1 -0
  331. package/dist/utils/gasEstimation.d.ts +65 -0
  332. package/dist/utils/gasEstimation.d.ts.map +1 -0
  333. package/dist/utils/gasEstimation.js +206 -0
  334. package/dist/utils/gasEstimation.js.map +1 -0
  335. package/dist/utils/solanaKeyParser.d.ts +10 -0
  336. package/dist/utils/solanaKeyParser.d.ts.map +1 -0
  337. package/dist/utils/solanaKeyParser.js +87 -0
  338. package/dist/utils/solanaKeyParser.js.map +1 -0
  339. package/dist/utils/solanaKeyParser.test.d.ts +2 -0
  340. package/dist/utils/solanaKeyParser.test.d.ts.map +1 -0
  341. package/dist/utils/solanaKeyParser.test.js +71 -0
  342. package/dist/utils/solanaKeyParser.test.js.map +1 -0
  343. package/dist/utils/tokenUtils.d.ts +38 -0
  344. package/dist/utils/tokenUtils.d.ts.map +1 -0
  345. package/dist/utils/tokenUtils.js +65 -0
  346. package/dist/utils/tokenUtils.js.map +1 -0
  347. package/dist/utils/transactionUtils.d.ts +22 -0
  348. package/dist/utils/transactionUtils.d.ts.map +1 -0
  349. package/dist/utils/transactionUtils.js +26 -0
  350. package/dist/utils/transactionUtils.js.map +1 -0
  351. package/package.json +87 -3
  352. package/src/bridges/LiFiBridge.test.ts +615 -0
  353. package/src/bridges/LiFiBridge.ts +731 -0
  354. package/src/config/RebalancerConfig.test.ts +921 -0
  355. package/src/config/RebalancerConfig.ts +63 -0
  356. package/src/config/types.ts +613 -0
  357. package/src/core/InventoryRebalancer.test.ts +1858 -0
  358. package/src/core/InventoryRebalancer.ts +1455 -0
  359. package/src/core/Rebalancer.test.ts +686 -0
  360. package/src/core/Rebalancer.ts +686 -0
  361. package/src/core/RebalancerOrchestrator.test.ts +871 -0
  362. package/src/core/RebalancerOrchestrator.ts +273 -0
  363. package/src/core/RebalancerService.test.ts +1094 -0
  364. package/src/core/RebalancerService.ts +412 -0
  365. package/src/e2e/E2E_TEST_CONVENTIONS.md +222 -0
  366. package/src/e2e/collateral-deficit.e2e-test.ts +403 -0
  367. package/src/e2e/composite.e2e-test.ts +1008 -0
  368. package/src/e2e/fixtures/routes.ts +532 -0
  369. package/src/e2e/harness/BaseLocalDeploymentManager.ts +246 -0
  370. package/src/e2e/harness/BridgeSetup.ts +95 -0
  371. package/src/e2e/harness/Erc20InventoryLocalDeploymentManager.ts +183 -0
  372. package/src/e2e/harness/Erc20LocalDeploymentManager.ts +190 -0
  373. package/src/e2e/harness/ForkIndexer.test.ts +448 -0
  374. package/src/e2e/harness/ForkIndexer.ts +183 -0
  375. package/src/e2e/harness/MixedLocalDeploymentManager.ts +196 -0
  376. package/src/e2e/harness/MockExplorerClient.ts +94 -0
  377. package/src/e2e/harness/MockExternalBridge.ts +411 -0
  378. package/src/e2e/harness/NativeLocalDeploymentManager.ts +138 -0
  379. package/src/e2e/harness/SnapshotHelper.ts +56 -0
  380. package/src/e2e/harness/TestHelpers.ts +169 -0
  381. package/src/e2e/harness/TestRebalancer.ts +758 -0
  382. package/src/e2e/harness/TransferHelper.ts +188 -0
  383. package/src/e2e/inventory-erc20-minAmount.e2e-test.ts +735 -0
  384. package/src/e2e/inventory-erc20-weighted.e2e-test.ts +733 -0
  385. package/src/e2e/inventory-minAmount.e2e-test.ts +734 -0
  386. package/src/e2e/inventory-weighted.e2e-test.ts +734 -0
  387. package/src/e2e/minAmount.e2e-test.ts +313 -0
  388. package/src/e2e/mixed-weighted.e2e-test.ts +267 -0
  389. package/src/e2e/weighted.e2e-test.ts +304 -0
  390. package/src/factories/RebalancerContextFactory.test.ts +394 -0
  391. package/src/factories/RebalancerContextFactory.ts +771 -0
  392. package/src/index.ts +125 -0
  393. package/src/interfaces/IExternalBridge.ts +117 -0
  394. package/src/interfaces/IMetrics.ts +5 -0
  395. package/src/interfaces/IMonitor.ts +71 -0
  396. package/src/interfaces/IRebalancer.ts +57 -0
  397. package/src/interfaces/IStrategy.ts +81 -0
  398. package/src/metrics/Metrics.ts +335 -0
  399. package/src/metrics/PriceGetter.ts +74 -0
  400. package/src/metrics/scripts/metrics.ts +139 -0
  401. package/src/monitor/Monitor.ts +324 -0
  402. package/src/service.ts +285 -0
  403. package/src/strategy/BaseStrategy.ts +553 -0
  404. package/src/strategy/CollateralDeficitStrategy.test.ts +728 -0
  405. package/src/strategy/CollateralDeficitStrategy.ts +421 -0
  406. package/src/strategy/CompositeStrategy.test.ts +418 -0
  407. package/src/strategy/CompositeStrategy.ts +102 -0
  408. package/src/strategy/MinAmountStrategy.test.ts +732 -0
  409. package/src/strategy/MinAmountStrategy.ts +200 -0
  410. package/src/strategy/StrategyFactory.test.ts +108 -0
  411. package/src/strategy/StrategyFactory.ts +157 -0
  412. package/src/strategy/WeightedStrategy.test.ts +529 -0
  413. package/src/strategy/WeightedStrategy.ts +126 -0
  414. package/src/strategy/index.ts +6 -0
  415. package/src/test/helpers.ts +477 -0
  416. package/src/test/lifiMocks.ts +211 -0
  417. package/src/tracking/ActionTracker.test.ts +1625 -0
  418. package/src/tracking/ActionTracker.ts +1019 -0
  419. package/src/tracking/IActionTracker.ts +213 -0
  420. package/src/tracking/InflightContextAdapter.test.ts +206 -0
  421. package/src/tracking/InflightContextAdapter.ts +75 -0
  422. package/src/tracking/store/IStore.ts +48 -0
  423. package/src/tracking/store/InMemoryStore.test.ts +338 -0
  424. package/src/tracking/store/InMemoryStore.ts +59 -0
  425. package/src/tracking/store/index.ts +2 -0
  426. package/src/tracking/types.ts +118 -0
  427. package/src/utils/ExplorerClient.test.ts +386 -0
  428. package/src/utils/ExplorerClient.ts +439 -0
  429. package/src/utils/balanceUtils.test.ts +79 -0
  430. package/src/utils/balanceUtils.ts +65 -0
  431. package/src/utils/blockTag.ts +68 -0
  432. package/src/utils/bridgeUtils.test.ts +193 -0
  433. package/src/utils/bridgeUtils.ts +101 -0
  434. package/src/utils/errors.ts +5 -0
  435. package/src/utils/gasEstimation.ts +306 -0
  436. package/src/utils/solanaKeyParser.test.ts +103 -0
  437. package/src/utils/solanaKeyParser.ts +117 -0
  438. package/src/utils/tokenUtils.ts +89 -0
  439. package/src/utils/transactionUtils.ts +41 -0
@@ -0,0 +1,1511 @@
1
+ import chai, { expect } from 'chai';
2
+ import chaiAsPromised from 'chai-as-promised';
3
+ import { Wallet } from 'ethers';
4
+ import { pino } from 'pino';
5
+ import Sinon from 'sinon';
6
+ import { ProviderType, TokenStandard, WarpTxCategory, } from '@humanode-hyperlane/sdk';
7
+ import { ProtocolType } from '@humanode-hyperlane/utils';
8
+ import { ExternalBridgeType } from '../config/types.js';
9
+ import { createMockBridgeQuote } from '../test/lifiMocks.js';
10
+ import { InventoryRebalancer, } from './InventoryRebalancer.js';
11
+ chai.use(chaiAsPromised);
12
+ const testLogger = pino({ level: 'silent' });
13
+ describe('InventoryRebalancer E2E', () => {
14
+ let inventoryRebalancer;
15
+ let config;
16
+ let actionTracker;
17
+ let bridge;
18
+ let warpCore;
19
+ let multiProvider;
20
+ let adapterStub;
21
+ // Test constants
22
+ const ARBITRUM_CHAIN = 'arbitrum';
23
+ const SOLANA_CHAIN = 'solanamainnet';
24
+ const ARBITRUM_DOMAIN = 42161;
25
+ const SOLANA_DOMAIN = 1399811149;
26
+ const TEST_PRIVATE_KEY = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
27
+ const TEST_WALLET = new Wallet(TEST_PRIVATE_KEY);
28
+ const INVENTORY_SIGNER = TEST_WALLET.address;
29
+ beforeEach(() => {
30
+ // Config
31
+ config = {
32
+ inventorySigners: {
33
+ [ProtocolType.Ethereum]: {
34
+ address: INVENTORY_SIGNER,
35
+ key: TEST_PRIVATE_KEY,
36
+ },
37
+ },
38
+ inventoryChains: [ARBITRUM_CHAIN, SOLANA_CHAIN],
39
+ };
40
+ // Mock IActionTracker
41
+ actionTracker = {
42
+ initialize: Sinon.stub(),
43
+ syncTransfers: Sinon.stub(),
44
+ syncRebalanceIntents: Sinon.stub(),
45
+ syncRebalanceActions: Sinon.stub(),
46
+ syncInventoryMovementActions: Sinon.stub(),
47
+ getInProgressTransfers: Sinon.stub(),
48
+ getTransfersByDestination: Sinon.stub(),
49
+ getActiveRebalanceIntents: Sinon.stub(),
50
+ getRebalanceIntentsByDestination: Sinon.stub(),
51
+ createRebalanceIntent: Sinon.stub(),
52
+ completeRebalanceIntent: Sinon.stub(),
53
+ cancelRebalanceIntent: Sinon.stub(),
54
+ failRebalanceIntent: Sinon.stub(),
55
+ getActionsByType: Sinon.stub(),
56
+ getInflightInventoryMovements: Sinon.stub(),
57
+ getPartiallyFulfilledInventoryIntents: Sinon.stub(),
58
+ createRebalanceAction: Sinon.stub(),
59
+ completeRebalanceAction: Sinon.stub(),
60
+ failRebalanceAction: Sinon.stub(),
61
+ logStoreContents: Sinon.stub(),
62
+ };
63
+ // Default: No active (partial) inventory intents
64
+ actionTracker.getPartiallyFulfilledInventoryIntents.resolves([]);
65
+ bridge = {
66
+ bridgeId: 'lifi',
67
+ quote: Sinon.stub(),
68
+ execute: Sinon.stub(),
69
+ getStatus: Sinon.stub(),
70
+ getNativeTokenAddress: Sinon.stub().returns('0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'),
71
+ };
72
+ // Mock adapter for WarpCore tokens
73
+ adapterStub = {
74
+ quoteTransferRemoteGas: Sinon.stub().resolves({
75
+ igpQuote: { amount: 1000000n },
76
+ }),
77
+ populateTransferRemoteTx: Sinon.stub().resolves({
78
+ to: '0xRouterAddress',
79
+ data: '0xTransferRemoteData',
80
+ value: 1000000n,
81
+ }),
82
+ isApproveRequired: Sinon.stub().resolves(false),
83
+ isRevokeApprovalRequired: Sinon.stub().resolves(false),
84
+ populateApproveTx: Sinon.stub().resolves({
85
+ to: '0xTokenAddress',
86
+ data: '0xApproveData',
87
+ value: 0n,
88
+ }),
89
+ };
90
+ // Mock WarpCore with tokens for both chains
91
+ // Note: We need tokens for both origin (surplus) and destination (deficit) chains
92
+ // because transferRemote is called FROM destination (after direction swap)
93
+ const arbitrumToken = {
94
+ chainName: ARBITRUM_CHAIN,
95
+ standard: TokenStandard.EvmHypCollateral, // Non-native: no IGP reservation needed
96
+ addressOrDenom: '0xArbitrumToken',
97
+ collateralAddressOrDenom: '0xArbitrumCollateralERC20',
98
+ getHypAdapter: Sinon.stub().returns(adapterStub),
99
+ amount: Sinon.stub().callsFake((amt) => ({ amount: amt })),
100
+ };
101
+ const solanaToken = {
102
+ chainName: SOLANA_CHAIN,
103
+ standard: TokenStandard.EvmHypCollateral, // Non-native: no IGP reservation needed
104
+ addressOrDenom: '0xSolanaToken',
105
+ collateralAddressOrDenom: '0xSolanaCollateralERC20',
106
+ getHypAdapter: Sinon.stub().returns(adapterStub),
107
+ amount: Sinon.stub().callsFake((amt) => ({ amount: amt })),
108
+ };
109
+ warpCore = {
110
+ tokens: [arbitrumToken, solanaToken],
111
+ multiProvider: {
112
+ getProvider: Sinon.stub(),
113
+ getSigner: Sinon.stub(),
114
+ getChainMetadata: Sinon.stub().callsFake((chain) => ({
115
+ name: chain,
116
+ protocol: ProtocolType.Ethereum,
117
+ })),
118
+ getEthersV5Provider: Sinon.stub().returns({
119
+ getTransactionReceipt: Sinon.stub().resolves({
120
+ transactionHash: '0xTransferRemoteTxHash',
121
+ logs: [],
122
+ }),
123
+ }),
124
+ },
125
+ findToken: Sinon.stub().returns(null),
126
+ getTransferRemoteTxs: Sinon.stub().resolves([
127
+ {
128
+ category: 'transfer',
129
+ type: ProviderType.EthersV5,
130
+ transaction: {
131
+ to: '0xRouterAddress',
132
+ data: '0xTransferRemoteData',
133
+ value: 1000000n,
134
+ },
135
+ },
136
+ ]),
137
+ };
138
+ // Mock provider with getFeeData for gas estimation, estimateGas for actual gas estimation,
139
+ // and waitForTransaction for confirmations
140
+ const mockProvider = {
141
+ getFeeData: Sinon.stub().resolves({
142
+ maxFeePerGas: 10000000000n, // 10 gwei
143
+ gasPrice: 10000000000n,
144
+ }),
145
+ estimateGas: Sinon.stub().resolves(300000n), // Mock gas estimate for transferRemote
146
+ waitForTransaction: Sinon.stub().resolves({
147
+ blockNumber: 100,
148
+ status: 1,
149
+ }),
150
+ };
151
+ // Mock MultiProvider
152
+ multiProvider = {
153
+ getDomainId: Sinon.stub().callsFake((chain) => {
154
+ if (chain === ARBITRUM_CHAIN)
155
+ return ARBITRUM_DOMAIN;
156
+ if (chain === SOLANA_CHAIN)
157
+ return SOLANA_DOMAIN;
158
+ return 0;
159
+ }),
160
+ getChainId: Sinon.stub().callsFake((chain) => {
161
+ if (chain === ARBITRUM_CHAIN)
162
+ return 42161;
163
+ if (chain === SOLANA_CHAIN)
164
+ return 1399811149;
165
+ return 0;
166
+ }),
167
+ getChainName: Sinon.stub().callsFake((domain) => {
168
+ if (domain === ARBITRUM_DOMAIN)
169
+ return ARBITRUM_CHAIN;
170
+ if (domain === SOLANA_DOMAIN)
171
+ return SOLANA_CHAIN;
172
+ return 'unknown';
173
+ }),
174
+ getChainMetadata: Sinon.stub().callsFake((chain) => ({
175
+ name: chain,
176
+ protocol: ProtocolType.Ethereum,
177
+ blocks: { reorgPeriod: 1 }, // Quick confirmations for tests
178
+ })),
179
+ getProtocol: Sinon.stub().callsFake((_) => {
180
+ // Return Ethereum protocol for all chains in tests
181
+ return 'ethereum';
182
+ }),
183
+ getProvider: Sinon.stub().returns(mockProvider),
184
+ getSigner: Sinon.stub().returns(TEST_WALLET),
185
+ sendTransaction: Sinon.stub().resolves({
186
+ transactionHash: '0xTransferRemoteTxHash',
187
+ logs: [], // Required for HyperlaneCore.getDispatchedMessages
188
+ }),
189
+ setSigner: Sinon.stub(),
190
+ };
191
+ // Wire toMultiProvider so EvmMultiProtocolSignerAdapter returns our mock multiProvider
192
+ warpCore.multiProvider.toMultiProvider =
193
+ Sinon.stub().returns(multiProvider);
194
+ // Create InventoryRebalancer
195
+ inventoryRebalancer = new InventoryRebalancer(config, actionTracker, { lifi: bridge }, warpCore, multiProvider, testLogger);
196
+ // Set default high inventory balances - tests can override via setInventoryBalances
197
+ inventoryRebalancer.setInventoryBalances({
198
+ [ARBITRUM_CHAIN]: BigInt('1000000000000000000000'),
199
+ [SOLANA_CHAIN]: BigInt('1000000000000000000000'),
200
+ });
201
+ });
202
+ afterEach(() => {
203
+ Sinon.restore();
204
+ });
205
+ // Helper to create test routes and intents
206
+ function createTestRoute(overrides) {
207
+ return {
208
+ origin: ARBITRUM_CHAIN,
209
+ destination: SOLANA_CHAIN,
210
+ amount: 10000000000n, // 10k USDC (6 decimals)
211
+ executionType: 'inventory',
212
+ externalBridge: ExternalBridgeType.LiFi,
213
+ ...overrides,
214
+ };
215
+ }
216
+ function createTestIntent(overrides) {
217
+ const now = Date.now();
218
+ const intent = {
219
+ id: 'intent-1',
220
+ status: 'not_started',
221
+ origin: ARBITRUM_DOMAIN,
222
+ destination: SOLANA_DOMAIN,
223
+ amount: 10000000000n,
224
+ executionMethod: 'inventory',
225
+ createdAt: now,
226
+ updatedAt: now,
227
+ ...overrides,
228
+ };
229
+ // Configure mock to return this intent when createRebalanceIntent is called
230
+ actionTracker.createRebalanceIntent.resolves(intent);
231
+ return intent;
232
+ }
233
+ describe('Basic Inventory Rebalance (Sufficient Inventory)', () => {
234
+ // NOTE: Strategy route is arbitrum (surplus) → solana (deficit)
235
+ // But execution calls transferRemote FROM solana TO arbitrum (swapped direction)
236
+ // This ADDS collateral to solana (filling deficit) and RELEASES from arbitrum (has surplus)
237
+ it('executes transferRemote when inventory is available on destination chain', async () => {
238
+ // Setup: Strategy says move from arbitrum→solana
239
+ // We need inventory on SOLANA (destination/deficit) to call transferRemote FROM there
240
+ const route = createTestRoute();
241
+ createTestIntent();
242
+ // Inventory is checked on DESTINATION (solana), not origin
243
+ inventoryRebalancer.setInventoryBalances({
244
+ [SOLANA_CHAIN]: 10000000000n,
245
+ [ARBITRUM_CHAIN]: 0n,
246
+ });
247
+ // Execute
248
+ const results = await inventoryRebalancer.rebalance([route]);
249
+ // Verify: Single successful result
250
+ expect(results).to.have.lengthOf(1);
251
+ expect(results[0].success).to.be.true;
252
+ expect(results[0].route).to.deep.equal(route);
253
+ // Verify: transferRemote was called via adapter
254
+ expect(adapterStub.quoteTransferRemoteGas.calledOnce).to.be.true;
255
+ expect(warpCore.getTransferRemoteTxs.calledOnce).to.be.true;
256
+ // Verify: Transaction was sent FROM SOLANA (destination chain, swapped)
257
+ expect(multiProvider.sendTransaction.calledOnce).to.be.true;
258
+ const [chainArg, txArg] = multiProvider.sendTransaction.firstCall.args;
259
+ expect(chainArg).to.equal(SOLANA_CHAIN); // Called FROM destination (swapped)
260
+ expect(txArg.to).to.equal('0xRouterAddress');
261
+ // Verify: inventory_deposit action was created
262
+ expect(actionTracker.createRebalanceAction.calledOnce).to.be.true;
263
+ const actionParams = actionTracker.createRebalanceAction.firstCall.args[0];
264
+ expect(actionParams.intentId).to.equal('intent-1');
265
+ expect(actionParams.type).to.equal('inventory_deposit');
266
+ expect(actionParams.amount).to.equal(10000000000n);
267
+ expect(actionParams.txHash).to.equal('0xTransferRemoteTxHash');
268
+ });
269
+ it('executes transferRemote with correct parameters (swapped direction)', async () => {
270
+ const route = createTestRoute({ amount: 5000000000n }); // 5k USDC
271
+ createTestIntent({ amount: 5000000000n });
272
+ // Inventory checked on DESTINATION (solana)
273
+ inventoryRebalancer.setInventoryBalances({
274
+ [SOLANA_CHAIN]: 5000000000n,
275
+ [ARBITRUM_CHAIN]: 0n,
276
+ });
277
+ await inventoryRebalancer.rebalance([route]);
278
+ // Direction is SWAPPED: transferRemote from solana TO arbitrum
279
+ const txParams = warpCore.getTransferRemoteTxs.firstCall.args[0];
280
+ expect(txParams.destination).to.equal(ARBITRUM_CHAIN); // Goes TO arbitrum (swapped)
281
+ expect(txParams.sender).to.equal(INVENTORY_SIGNER);
282
+ expect(txParams.recipient).to.equal(INVENTORY_SIGNER);
283
+ expect(txParams.originTokenAmount.amount).to.equal(5000000000n);
284
+ });
285
+ it('uses IMultiProtocolSigner path for solana transfer txs', async () => {
286
+ const route = createTestRoute({ amount: 5000000000n });
287
+ createTestIntent({ amount: 5000000000n });
288
+ inventoryRebalancer.setInventoryBalances({
289
+ [SOLANA_CHAIN]: 5000000000n,
290
+ [ARBITRUM_CHAIN]: 0n,
291
+ });
292
+ config.inventorySigners[ProtocolType.Sealevel] = {
293
+ address: INVENTORY_SIGNER,
294
+ key: '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32',
295
+ };
296
+ warpCore.multiProvider.getChainMetadata.callsFake((chain) => ({
297
+ name: chain,
298
+ protocol: chain === SOLANA_CHAIN
299
+ ? ProtocolType.Sealevel
300
+ : ProtocolType.Ethereum,
301
+ blocks: { reorgPeriod: 1 },
302
+ }));
303
+ const sendAndConfirmStub = Sinon.stub(InventoryRebalancer.prototype, 'sendAndConfirmInventoryTx').resolves({ txHash: '0xSolanaTxHash' });
304
+ warpCore.multiProvider.getSolanaWeb3Provider = Sinon.stub().returns({
305
+ getTransaction: Sinon.stub().resolves({
306
+ meta: { logMessages: [] },
307
+ }),
308
+ });
309
+ multiProvider.sendTransaction.resetHistory();
310
+ warpCore.getTransferRemoteTxs.resolves([
311
+ {
312
+ category: WarpTxCategory.Transfer,
313
+ type: ProviderType.SolanaWeb3,
314
+ transaction: {},
315
+ },
316
+ ]);
317
+ const results = await inventoryRebalancer.rebalance([route]);
318
+ expect(results).to.have.lengthOf(1);
319
+ expect(results[0].success).to.be.true;
320
+ expect(sendAndConfirmStub.calledOnce).to.be.true;
321
+ expect(sendAndConfirmStub.firstCall.args[0]).to.equal(SOLANA_CHAIN);
322
+ expect(multiProvider.sendTransaction.called).to.be.false;
323
+ const actionParams = actionTracker.createRebalanceAction.lastCall.args[0];
324
+ expect(actionParams.txHash).to.equal('0xSolanaTxHash');
325
+ });
326
+ });
327
+ describe('Partial Fulfillment (Insufficient Inventory)', () => {
328
+ // Partial transfers happen when maxTransferable >= minViableTransfer
329
+ // For non-native tokens (EvmHypCollateral), minViableTransfer = 0, so partial always viable
330
+ const PARTIAL_AMOUNT = BigInt(5e15); // 0.005 ETH - above threshold
331
+ const FULL_AMOUNT = BigInt(1e16); // 0.01 ETH
332
+ it('executes partial transferRemote when maxTransferable >= minViableTransfer', async () => {
333
+ // Setup: Need 0.01 ETH, but only 0.005 ETH available on destination
334
+ // For non-native tokens, minViableTransfer = 0, so partial transfer is viable
335
+ const route = createTestRoute({ amount: FULL_AMOUNT });
336
+ createTestIntent({ amount: FULL_AMOUNT });
337
+ // Inventory checked on DESTINATION (solana) - Only 0.005 ETH available
338
+ inventoryRebalancer.setInventoryBalances({
339
+ [SOLANA_CHAIN]: PARTIAL_AMOUNT,
340
+ [ARBITRUM_CHAIN]: 0n,
341
+ });
342
+ // Execute
343
+ const results = await inventoryRebalancer.rebalance([route]);
344
+ // Verify: Success with partial amount
345
+ expect(results).to.have.lengthOf(1);
346
+ expect(results[0].success).to.be.true;
347
+ // Verify: transferRemote was called with available amount (0.005 ETH), not full amount (0.01 ETH)
348
+ const txParams = warpCore.getTransferRemoteTxs.firstCall.args[0];
349
+ expect(txParams.originTokenAmount.amount).to.equal(PARTIAL_AMOUNT);
350
+ // Verify: Action created for partial amount
351
+ const actionParams = actionTracker.createRebalanceAction.firstCall.args[0];
352
+ expect(actionParams.amount).to.equal(PARTIAL_AMOUNT);
353
+ });
354
+ it('intent remains in_progress after partial fulfillment', async () => {
355
+ const route = createTestRoute({ amount: FULL_AMOUNT });
356
+ createTestIntent({ amount: FULL_AMOUNT });
357
+ // Inventory checked on DESTINATION (solana)
358
+ inventoryRebalancer.setInventoryBalances({
359
+ [SOLANA_CHAIN]: PARTIAL_AMOUNT,
360
+ [ARBITRUM_CHAIN]: 0n,
361
+ });
362
+ const results = await inventoryRebalancer.rebalance([route]);
363
+ // Verify: Partial transfer succeeded
364
+ expect(results[0].success).to.be.true;
365
+ });
366
+ });
367
+ describe('No Inventory Available', () => {
368
+ it('returns failure when no inventory on destination chain and no other source available', async () => {
369
+ const route = createTestRoute();
370
+ createTestIntent();
371
+ // No inventory anywhere
372
+ inventoryRebalancer.setInventoryBalances({
373
+ [SOLANA_CHAIN]: 0n,
374
+ [ARBITRUM_CHAIN]: 0n,
375
+ });
376
+ // Execute
377
+ const results = await inventoryRebalancer.rebalance([route]);
378
+ // Verify: Failure result
379
+ expect(results).to.have.lengthOf(1);
380
+ expect(results[0].success).to.be.false;
381
+ expect(results[0].error).to.include('No inventory available');
382
+ // Verify: No transferRemote attempted
383
+ expect(warpCore.getTransferRemoteTxs.called).to.be.false;
384
+ expect(multiProvider.sendTransaction.called).to.be.false;
385
+ expect(actionTracker.createRebalanceAction.called).to.be.false;
386
+ });
387
+ });
388
+ describe('Single Intent Architecture', () => {
389
+ it('takes only first route when multiple routes provided', async () => {
390
+ // Route 1: arbitrum → solana (check inventory on solana)
391
+ const route1 = createTestRoute({ amount: 5000000000n });
392
+ // Route 2: solana → arbitrum (would check inventory on arbitrum if processed)
393
+ const route2 = createTestRoute({
394
+ origin: SOLANA_CHAIN,
395
+ destination: ARBITRUM_CHAIN,
396
+ amount: 3000000000n,
397
+ });
398
+ createTestIntent({ id: 'intent-1', amount: 5000000000n });
399
+ // Inventory on DESTINATION of first route (solana)
400
+ inventoryRebalancer.setInventoryBalances({
401
+ [SOLANA_CHAIN]: 5000000000n,
402
+ [ARBITRUM_CHAIN]: 0n,
403
+ });
404
+ // Execute with multiple routes
405
+ const results = await inventoryRebalancer.rebalance([route1, route2]);
406
+ // Verify: Only ONE route processed (single-intent architecture)
407
+ expect(results).to.have.lengthOf(1);
408
+ expect(results[0].success).to.be.true;
409
+ // Verify: Only one intent created
410
+ expect(actionTracker.createRebalanceIntent.calledOnce).to.be.true;
411
+ // Verify: Only one action created
412
+ expect(actionTracker.createRebalanceAction.calledOnce).to.be.true;
413
+ });
414
+ it('continues existing intent instead of processing new routes', async () => {
415
+ // Setup: existing partial intent
416
+ const existingIntent = createTestIntent({
417
+ id: 'existing-intent',
418
+ status: 'in_progress',
419
+ amount: 10000000000n,
420
+ });
421
+ // Configure mock to return existing partial intent
422
+ actionTracker.getPartiallyFulfilledInventoryIntents.resolves([
423
+ {
424
+ intent: existingIntent,
425
+ completedAmount: 3000000000n,
426
+ remaining: 7000000000n, // 7k remaining
427
+ hasInflightDeposit: false,
428
+ },
429
+ ]);
430
+ // New route that would be ignored
431
+ const newRoute = createTestRoute({ amount: 5000000000n });
432
+ // Inventory on DESTINATION of existing intent (solana) - Plenty of inventory
433
+ inventoryRebalancer.setInventoryBalances({
434
+ [SOLANA_CHAIN]: 10000000000n,
435
+ [ARBITRUM_CHAIN]: 0n,
436
+ });
437
+ // Execute with new route (should be ignored in favor of existing intent)
438
+ const results = await inventoryRebalancer.rebalance([newRoute]);
439
+ // Verify: Existing intent was continued (not new route)
440
+ expect(results).to.have.lengthOf(1);
441
+ expect(results[0].success).to.be.true;
442
+ // Verify: No new intent was created (existing was used)
443
+ expect(actionTracker.createRebalanceIntent.called).to.be.false;
444
+ });
445
+ it('returns empty when active intent has in-flight deposit (prevents oscillation)', async () => {
446
+ const existingIntent = createTestIntent({
447
+ id: 'inflight-deposit-intent',
448
+ status: 'in_progress',
449
+ amount: 10000000000n,
450
+ });
451
+ // Configure mock: active intent WITH in-flight deposit
452
+ actionTracker.getPartiallyFulfilledInventoryIntents.resolves([
453
+ {
454
+ intent: existingIntent,
455
+ completedAmount: 3000000000n,
456
+ remaining: 7000000000n,
457
+ hasInflightDeposit: true,
458
+ },
459
+ ]);
460
+ // New routes that WOULD create a new intent or continue
461
+ const newRoute = createTestRoute({ amount: 5000000000n });
462
+ inventoryRebalancer.setInventoryBalances({
463
+ [SOLANA_CHAIN]: 10000000000n,
464
+ [ARBITRUM_CHAIN]: 0n,
465
+ });
466
+ const results = await inventoryRebalancer.rebalance([newRoute]);
467
+ // Must return empty — wait for in-flight deposit to complete
468
+ expect(results).to.have.lengthOf(0);
469
+ // Must NOT create a new intent
470
+ expect(actionTracker.createRebalanceIntent.called).to.be.false;
471
+ // Must NOT call createRebalanceAction (proves continueIntent was never reached)
472
+ expect(actionTracker.createRebalanceAction.called).to.be.false;
473
+ });
474
+ it('returns empty results when no routes provided and no active intent', async () => {
475
+ const results = await inventoryRebalancer.rebalance([]);
476
+ expect(results).to.have.lengthOf(0);
477
+ expect(actionTracker.createRebalanceIntent.called).to.be.false;
478
+ });
479
+ it('continues existing not_started intent instead of creating new one', async () => {
480
+ // Setup: Create an intent that stays 'not_started' (simulating failed bridges)
481
+ const existingIntent = createTestIntent({
482
+ id: 'stuck-not-started-intent',
483
+ status: 'not_started', // Never transitioned to in_progress
484
+ amount: 10000000000n,
485
+ });
486
+ // Configure mock to return the not_started intent as a partial intent
487
+ // (this is the fix - getPartiallyFulfilledInventoryIntents now includes not_started)
488
+ actionTracker.getPartiallyFulfilledInventoryIntents.resolves([
489
+ {
490
+ intent: existingIntent,
491
+ completedAmount: 0n,
492
+ remaining: 10000000000n,
493
+ hasInflightDeposit: false,
494
+ },
495
+ ]);
496
+ // New route that would be ignored in favor of existing intent
497
+ const newRoute = createTestRoute({ amount: 5000000000n });
498
+ // Provide sufficient inventory for execution
499
+ inventoryRebalancer.setInventoryBalances({
500
+ [SOLANA_CHAIN]: 10000000000n,
501
+ [ARBITRUM_CHAIN]: 0n,
502
+ });
503
+ const results = await inventoryRebalancer.rebalance([newRoute]);
504
+ // Verify: Existing not_started intent was continued (not new route)
505
+ expect(results).to.have.lengthOf(1);
506
+ expect(results[0].success).to.be.true;
507
+ // Verify: No new intent was created (existing was continued)
508
+ expect(actionTracker.createRebalanceIntent.called).to.be.false;
509
+ });
510
+ });
511
+ describe('Error Handling', () => {
512
+ it('handles transaction send failure', async () => {
513
+ const route = createTestRoute();
514
+ createTestIntent();
515
+ // Inventory on DESTINATION (solana)
516
+ inventoryRebalancer.setInventoryBalances({
517
+ [SOLANA_CHAIN]: 10000000000n,
518
+ [ARBITRUM_CHAIN]: 0n,
519
+ });
520
+ multiProvider.sendTransaction.rejects(new Error('Transaction failed'));
521
+ const results = await inventoryRebalancer.rebalance([route]);
522
+ expect(results).to.have.lengthOf(1);
523
+ expect(results[0].success).to.be.false;
524
+ expect(results[0].error).to.include('Transaction failed');
525
+ });
526
+ it('handles missing token for chain', async () => {
527
+ // Clear tokens to simulate missing token
528
+ warpCore.tokens = [];
529
+ const route = createTestRoute();
530
+ createTestIntent();
531
+ // Even with inventory, if no token for destination, it should fail
532
+ inventoryRebalancer.setInventoryBalances({
533
+ [SOLANA_CHAIN]: 10000000000n,
534
+ [ARBITRUM_CHAIN]: 0n,
535
+ });
536
+ const results = await inventoryRebalancer.rebalance([route]);
537
+ expect(results).to.have.lengthOf(1);
538
+ expect(results[0].success).to.be.false;
539
+ expect(results[0].error).to.include('No token found');
540
+ });
541
+ it('handles adapter quoteTransferRemoteGas failure', async () => {
542
+ const route = createTestRoute();
543
+ createTestIntent();
544
+ // Inventory on DESTINATION (solana)
545
+ inventoryRebalancer.setInventoryBalances({
546
+ [SOLANA_CHAIN]: 10000000000n,
547
+ [ARBITRUM_CHAIN]: 0n,
548
+ });
549
+ adapterStub.quoteTransferRemoteGas.rejects(new Error('Gas quote failed'));
550
+ const results = await inventoryRebalancer.rebalance([route]);
551
+ expect(results).to.have.lengthOf(1);
552
+ expect(results[0].success).to.be.false;
553
+ expect(results[0].error).to.include('Gas quote failed');
554
+ });
555
+ it('throws when inventory signer key is missing', async () => {
556
+ // Config without signer keys (no key field)
557
+ const configWithoutKeys = {
558
+ inventorySigners: {
559
+ [ProtocolType.Ethereum]: { address: INVENTORY_SIGNER },
560
+ },
561
+ inventoryChains: [ARBITRUM_CHAIN, SOLANA_CHAIN],
562
+ };
563
+ inventoryRebalancer = new InventoryRebalancer(configWithoutKeys, actionTracker, { lifi: bridge }, warpCore, multiProvider, testLogger);
564
+ const route = createTestRoute({ amount: BigInt(1e18) });
565
+ createTestIntent({ amount: BigInt(1e18) });
566
+ inventoryRebalancer.setInventoryBalances({
567
+ [ARBITRUM_CHAIN]: BigInt(10e18),
568
+ [SOLANA_CHAIN]: 0n,
569
+ });
570
+ bridge.quote.resolves(createMockBridgeQuote({
571
+ fromAmount: BigInt(1e18),
572
+ toAmount: BigInt(0.98e18),
573
+ }));
574
+ const results = await inventoryRebalancer.rebalance([route]);
575
+ expect(results).to.have.lengthOf(1);
576
+ expect(results[0].success).to.be.false;
577
+ expect(results[0].error).to.include('Missing inventory signer key');
578
+ expect(bridge.execute.called).to.be.false;
579
+ });
580
+ });
581
+ describe('Native Token IGP Reservation', () => {
582
+ // Gas estimation: 300,000 gas × 10 gwei = 3,000,000,000,000 wei
583
+ // Buffered gas limit (10%): 330,000 gas
584
+ // Buffered gas cost: 330,000 × 10 gwei = 3,300,000,000,000 wei
585
+ // IGP quote: 1,000,000 wei
586
+ // Total reservation: IGP + buffered gas = 3,300,001,000,000 wei (~0.0033 ETH)
587
+ // Total cost (for min viable): IGP + buffered gas = 3,300,001,000,000 wei
588
+ // Min viable transfer (2x total cost): 6,600,002,000,000 wei (~0.0066 ETH)
589
+ const GAS_LIMIT = 300000n;
590
+ const BUFFERED_GAS_LIMIT = (GAS_LIMIT * 110n) / 100n; // 10% buffer
591
+ const GAS_PRICE = 10000000000n; // 10 gwei
592
+ const BUFFERED_GAS_COST = GAS_PRICE * BUFFERED_GAS_LIMIT;
593
+ const IGP_COST = 1000000n;
594
+ const TOTAL_RESERVATION = IGP_COST + BUFFERED_GAS_COST;
595
+ // Note: MIN_VIABLE_TRANSFER = TOTAL_COST * 2n = ~6.6e12 wei (~0.0066 ETH)
596
+ it('reserves IGP and gas cost when transferring native tokens', async () => {
597
+ // Setup: Native token on DESTINATION (solana) where IGP and gas must be reserved
598
+ // Strategy: arbitrum → solana, so transferRemote is called FROM solana
599
+ const arbitrumToken = {
600
+ chainName: ARBITRUM_CHAIN,
601
+ standard: TokenStandard.EvmHypNative,
602
+ getHypAdapter: Sinon.stub().returns(adapterStub),
603
+ amount: Sinon.stub().callsFake((amt) => ({
604
+ amount: amt,
605
+ })),
606
+ };
607
+ const solanaToken = {
608
+ chainName: SOLANA_CHAIN,
609
+ standard: TokenStandard.EvmHypNative, // Native token: reservation needed
610
+ getHypAdapter: Sinon.stub().returns(adapterStub),
611
+ amount: Sinon.stub().callsFake((amt) => ({
612
+ amount: amt,
613
+ })),
614
+ };
615
+ warpCore.tokens = [arbitrumToken, solanaToken];
616
+ const requestedAmount = 10000000000000000n; // 0.01 ETH
617
+ const availableInventory = requestedAmount + TOTAL_RESERVATION; // Enough for amount + costs
618
+ const route = createTestRoute({ amount: requestedAmount });
619
+ createTestIntent({ amount: requestedAmount });
620
+ // Inventory on DESTINATION (solana) where transferRemote is called FROM
621
+ inventoryRebalancer.setInventoryBalances({
622
+ [SOLANA_CHAIN]: availableInventory,
623
+ [ARBITRUM_CHAIN]: 0n,
624
+ });
625
+ // Execute
626
+ const results = await inventoryRebalancer.rebalance([route]);
627
+ // Verify: Success with full requested amount (since we have enough for amount + costs)
628
+ expect(results).to.have.lengthOf(1);
629
+ expect(results[0].success).to.be.true;
630
+ const txParams = warpCore.getTransferRemoteTxs.lastCall.args[0];
631
+ expect(txParams.originTokenAmount.amount).to.equal(requestedAmount);
632
+ });
633
+ it('reduces transfer amount when inventory is limited', async () => {
634
+ // Setup: Native token on DESTINATION where we have less inventory than needed
635
+ const arbitrumToken = {
636
+ chainName: ARBITRUM_CHAIN,
637
+ standard: TokenStandard.EvmHypNative,
638
+ getHypAdapter: Sinon.stub().returns(adapterStub),
639
+ amount: Sinon.stub().callsFake((amt) => ({
640
+ amount: amt,
641
+ })),
642
+ };
643
+ const solanaToken = {
644
+ chainName: SOLANA_CHAIN,
645
+ standard: TokenStandard.EvmHypNative,
646
+ getHypAdapter: Sinon.stub().returns(adapterStub),
647
+ amount: Sinon.stub().callsFake((amt) => ({
648
+ amount: amt,
649
+ })),
650
+ };
651
+ warpCore.tokens = [arbitrumToken, solanaToken];
652
+ // Request more than we have available
653
+ const requestedAmount = 20000000000000000n; // 0.02 ETH
654
+ // Have enough for costs + partial transfer that exceeds min viable threshold
655
+ // availableInventory = TOTAL_RESERVATION + partialAmount
656
+ // where partialAmount >= MIN_VIABLE_TRANSFER (2x base cost)
657
+ const partialAmount = 7000000000000000n; // 0.007 ETH (> MIN_VIABLE_TRANSFER of ~0.006 ETH)
658
+ const availableInventory = TOTAL_RESERVATION + partialAmount;
659
+ const route = createTestRoute({ amount: requestedAmount });
660
+ createTestIntent({ amount: requestedAmount });
661
+ // Inventory on DESTINATION (solana)
662
+ // Since 100% is consolidated on destination, partial transfer should happen
663
+ inventoryRebalancer.setInventoryBalances({
664
+ [SOLANA_CHAIN]: availableInventory,
665
+ [ARBITRUM_CHAIN]: 0n,
666
+ });
667
+ // Execute
668
+ const results = await inventoryRebalancer.rebalance([route]);
669
+ // Verify: Success with reduced amount
670
+ expect(results).to.have.lengthOf(1);
671
+ expect(results[0].success).to.be.true;
672
+ const txParams = warpCore.getTransferRemoteTxs.lastCall.args[0];
673
+ expect(txParams.originTokenAmount.amount).to.equal(partialAmount);
674
+ });
675
+ it('returns failure when inventory cannot cover costs', async () => {
676
+ // Setup: Native token on DESTINATION where inventory is less than total reservation
677
+ const arbitrumToken = {
678
+ chainName: ARBITRUM_CHAIN,
679
+ standard: TokenStandard.EvmHypNative,
680
+ getHypAdapter: Sinon.stub().returns(adapterStub),
681
+ amount: Sinon.stub().callsFake((amt) => ({
682
+ amount: amt,
683
+ })),
684
+ };
685
+ const solanaToken = {
686
+ chainName: SOLANA_CHAIN,
687
+ standard: TokenStandard.EvmHypNative,
688
+ getHypAdapter: Sinon.stub().returns(adapterStub),
689
+ amount: Sinon.stub().callsFake((amt) => ({
690
+ amount: amt,
691
+ })),
692
+ };
693
+ warpCore.tokens = [arbitrumToken, solanaToken];
694
+ const route = createTestRoute({ amount: 10000000000000000n });
695
+ createTestIntent({ amount: 10000000000000000n });
696
+ // Available inventory on DESTINATION (solana) is less than total reservation (IGP + gas)
697
+ // Just under the threshold, no inventory anywhere else
698
+ inventoryRebalancer.setInventoryBalances({
699
+ [SOLANA_CHAIN]: TOTAL_RESERVATION - 1n,
700
+ [ARBITRUM_CHAIN]: 0n,
701
+ });
702
+ // Execute
703
+ const results = await inventoryRebalancer.rebalance([route]);
704
+ // Verify: Failure due to insufficient funds
705
+ expect(results).to.have.lengthOf(1);
706
+ expect(results[0].success).to.be.false;
707
+ expect(results[0].error).to.include('No inventory available');
708
+ expect(warpCore.getTransferRemoteTxs.called).to.be.false;
709
+ expect(actionTracker.createRebalanceAction.called).to.be.false;
710
+ });
711
+ it('does not reserve IGP for non-native tokens', async () => {
712
+ // Setup: Collateral tokens on both chains (IGP paid separately)
713
+ const arbitrumToken = {
714
+ chainName: ARBITRUM_CHAIN,
715
+ standard: TokenStandard.EvmHypCollateral, // Non-native: no IGP reservation
716
+ collateralAddressOrDenom: '0xArbitrumCollateralERC20',
717
+ getHypAdapter: Sinon.stub().returns(adapterStub),
718
+ amount: Sinon.stub().callsFake((amt) => ({
719
+ amount: amt,
720
+ })),
721
+ };
722
+ const solanaToken = {
723
+ chainName: SOLANA_CHAIN,
724
+ standard: TokenStandard.EvmHypCollateral, // Non-native: no IGP reservation
725
+ collateralAddressOrDenom: '0xSolanaCollateralERC20',
726
+ getHypAdapter: Sinon.stub().returns(adapterStub),
727
+ amount: Sinon.stub().callsFake((amt) => ({
728
+ amount: amt,
729
+ })),
730
+ };
731
+ warpCore.tokens = [arbitrumToken, solanaToken];
732
+ const route = createTestRoute({ amount: 10000000000n });
733
+ createTestIntent({ amount: 10000000000n });
734
+ // Inventory on DESTINATION (solana)
735
+ inventoryRebalancer.setInventoryBalances({
736
+ [SOLANA_CHAIN]: 10000000000n,
737
+ [ARBITRUM_CHAIN]: 0n,
738
+ });
739
+ // Execute
740
+ const results = await inventoryRebalancer.rebalance([route]);
741
+ // Verify: Success with full amount (no IGP deduction)
742
+ expect(results).to.have.lengthOf(1);
743
+ expect(results[0].success).to.be.true;
744
+ const txParams = warpCore.getTransferRemoteTxs.firstCall.args[0];
745
+ expect(txParams.originTokenAmount.amount).to.equal(10000000000n); // Full amount
746
+ });
747
+ });
748
+ describe('Native Token Fee Quote Reservation', () => {
749
+ // Token fee quote scenarios: tests verify that tokenFeeQuote is properly deducted
750
+ // from maxTransferable when it represents a native token fee
751
+ const GAS_LIMIT = 300000n;
752
+ const BUFFERED_GAS_LIMIT = (GAS_LIMIT * 110n) / 100n; // 10% buffer
753
+ const GAS_PRICE = 10000000000n; // 10 gwei
754
+ const BUFFERED_GAS_COST = GAS_PRICE * BUFFERED_GAS_LIMIT;
755
+ const IGP_COST = 1000000n;
756
+ const TOKEN_FEE_AMOUNT = 500000n; // Significant token fee
757
+ const TOTAL_RESERVATION = IGP_COST + BUFFERED_GAS_COST;
758
+ it('deducts tokenFeeQuote when addressOrDenom is undefined (native token)', async () => {
759
+ // Setup: Native token with tokenFeeQuote but no addressOrDenom (undefined = native)
760
+ // Override the global adapterStub to include tokenFeeQuote
761
+ adapterStub.quoteTransferRemoteGas.resolves({
762
+ igpQuote: { amount: IGP_COST },
763
+ tokenFeeQuote: { amount: TOKEN_FEE_AMOUNT }, // No addressOrDenom = native
764
+ });
765
+ const arbitrumToken = {
766
+ chainName: ARBITRUM_CHAIN,
767
+ standard: TokenStandard.EvmHypNative,
768
+ getHypAdapter: Sinon.stub().returns(adapterStub),
769
+ amount: Sinon.stub().callsFake((amt) => ({
770
+ amount: amt,
771
+ })),
772
+ };
773
+ const solanaToken = {
774
+ chainName: SOLANA_CHAIN,
775
+ standard: TokenStandard.EvmHypNative,
776
+ getHypAdapter: Sinon.stub().returns(adapterStub),
777
+ amount: Sinon.stub().callsFake((amt) => ({
778
+ amount: amt,
779
+ })),
780
+ };
781
+ warpCore.tokens = [arbitrumToken, solanaToken];
782
+ const requestedAmount = 10000000000000000n; // 0.01 ETH
783
+ // Available = requested + IGP + gas + tokenFee (enough for full transfer)
784
+ const availableInventory = requestedAmount + TOTAL_RESERVATION + TOKEN_FEE_AMOUNT;
785
+ const route = createTestRoute({ amount: requestedAmount });
786
+ createTestIntent({ amount: requestedAmount });
787
+ inventoryRebalancer.setInventoryBalances({
788
+ [SOLANA_CHAIN]: availableInventory,
789
+ [ARBITRUM_CHAIN]: 0n,
790
+ });
791
+ const results = await inventoryRebalancer.rebalance([route]);
792
+ expect(results).to.have.lengthOf(1);
793
+ expect(results[0].success).to.be.true;
794
+ const txParams = warpCore.getTransferRemoteTxs.lastCall.args[0];
795
+ expect(txParams.originTokenAmount.amount).to.equal(requestedAmount);
796
+ });
797
+ it('deducts tokenFeeQuote when addressOrDenom is zero address', async () => {
798
+ // Setup: Native token with tokenFeeQuote and zero-address denom (isZeroishAddress)
799
+ const zeroAddressAdapter = {
800
+ quoteTransferRemoteGas: Sinon.stub().resolves({
801
+ igpQuote: { amount: IGP_COST },
802
+ tokenFeeQuote: {
803
+ addressOrDenom: '0x0000000000000000000000000000000000000000',
804
+ amount: TOKEN_FEE_AMOUNT,
805
+ },
806
+ }),
807
+ populateTransferRemoteTx: Sinon.stub().resolves({
808
+ to: '0xRouterAddress',
809
+ data: '0xTransferRemoteData',
810
+ value: 1000000n,
811
+ }),
812
+ };
813
+ const arbitrumToken = {
814
+ chainName: ARBITRUM_CHAIN,
815
+ standard: TokenStandard.EvmHypNative,
816
+ getHypAdapter: Sinon.stub().returns(zeroAddressAdapter),
817
+ amount: Sinon.stub().callsFake((amt) => ({
818
+ amount: amt,
819
+ })),
820
+ };
821
+ const solanaToken = {
822
+ chainName: SOLANA_CHAIN,
823
+ standard: TokenStandard.EvmHypNative,
824
+ getHypAdapter: Sinon.stub().returns(zeroAddressAdapter),
825
+ amount: Sinon.stub().callsFake((amt) => ({
826
+ amount: amt,
827
+ })),
828
+ };
829
+ warpCore.tokens = [arbitrumToken, solanaToken];
830
+ const requestedAmount = 10000000000000000n;
831
+ const availableInventory = requestedAmount + TOTAL_RESERVATION + TOKEN_FEE_AMOUNT;
832
+ const route = createTestRoute({ amount: requestedAmount });
833
+ createTestIntent({ amount: requestedAmount });
834
+ inventoryRebalancer.setInventoryBalances({
835
+ [SOLANA_CHAIN]: availableInventory,
836
+ [ARBITRUM_CHAIN]: 0n,
837
+ });
838
+ const results = await inventoryRebalancer.rebalance([route]);
839
+ expect(results).to.have.lengthOf(1);
840
+ expect(results[0].success).to.be.true;
841
+ const txParams = warpCore.getTransferRemoteTxs.lastCall.args[0];
842
+ expect(txParams.originTokenAmount.amount).to.equal(requestedAmount);
843
+ });
844
+ it('does NOT deduct tokenFeeQuote when addressOrDenom is ERC20 address', async () => {
845
+ // Setup: Native token with tokenFeeQuote but ERC20 denom (not native)
846
+ const erc20Address = '0x1234567890abcdef1234567890abcdef12345678';
847
+ const erc20Adapter = {
848
+ quoteTransferRemoteGas: Sinon.stub().resolves({
849
+ igpQuote: { amount: IGP_COST },
850
+ tokenFeeQuote: {
851
+ addressOrDenom: erc20Address,
852
+ amount: TOKEN_FEE_AMOUNT,
853
+ },
854
+ }),
855
+ populateTransferRemoteTx: Sinon.stub().resolves({
856
+ to: '0xRouterAddress',
857
+ data: '0xTransferRemoteData',
858
+ value: 1000000n,
859
+ }),
860
+ };
861
+ const arbitrumToken = {
862
+ chainName: ARBITRUM_CHAIN,
863
+ standard: TokenStandard.EvmHypNative,
864
+ getHypAdapter: Sinon.stub().returns(erc20Adapter),
865
+ amount: Sinon.stub().callsFake((amt) => ({
866
+ amount: amt,
867
+ })),
868
+ };
869
+ const solanaToken = {
870
+ chainName: SOLANA_CHAIN,
871
+ standard: TokenStandard.EvmHypNative,
872
+ getHypAdapter: Sinon.stub().returns(erc20Adapter),
873
+ amount: Sinon.stub().callsFake((amt) => ({
874
+ amount: amt,
875
+ })),
876
+ };
877
+ warpCore.tokens = [arbitrumToken, solanaToken];
878
+ const requestedAmount = 10000000000000000n;
879
+ // Available = requested + IGP + gas (NO tokenFee deduction since it's ERC20)
880
+ const availableInventory = requestedAmount + TOTAL_RESERVATION;
881
+ const route = createTestRoute({ amount: requestedAmount });
882
+ createTestIntent({ amount: requestedAmount });
883
+ inventoryRebalancer.setInventoryBalances({
884
+ [SOLANA_CHAIN]: availableInventory,
885
+ [ARBITRUM_CHAIN]: 0n,
886
+ });
887
+ const results = await inventoryRebalancer.rebalance([route]);
888
+ expect(results).to.have.lengthOf(1);
889
+ expect(results[0].success).to.be.true;
890
+ const txParams = warpCore.getTransferRemoteTxs.lastCall.args[0];
891
+ expect(txParams.originTokenAmount.amount).to.equal(requestedAmount);
892
+ });
893
+ it('handles undefined tokenFeeQuote (backward compatibility with v<10)', async () => {
894
+ // Setup: Native token without tokenFeeQuote (old contract version)
895
+ const oldAdapter = {
896
+ quoteTransferRemoteGas: Sinon.stub().resolves({
897
+ igpQuote: { amount: IGP_COST },
898
+ // No tokenFeeQuote field
899
+ }),
900
+ populateTransferRemoteTx: Sinon.stub().resolves({
901
+ to: '0xRouterAddress',
902
+ data: '0xTransferRemoteData',
903
+ value: 1000000n,
904
+ }),
905
+ };
906
+ const arbitrumToken = {
907
+ chainName: ARBITRUM_CHAIN,
908
+ standard: TokenStandard.EvmHypNative,
909
+ getHypAdapter: Sinon.stub().returns(oldAdapter),
910
+ amount: Sinon.stub().callsFake((amt) => ({
911
+ amount: amt,
912
+ })),
913
+ };
914
+ const solanaToken = {
915
+ chainName: SOLANA_CHAIN,
916
+ standard: TokenStandard.EvmHypNative,
917
+ getHypAdapter: Sinon.stub().returns(oldAdapter),
918
+ amount: Sinon.stub().callsFake((amt) => ({
919
+ amount: amt,
920
+ })),
921
+ };
922
+ warpCore.tokens = [arbitrumToken, solanaToken];
923
+ const requestedAmount = 10000000000000000n;
924
+ // Available = requested + IGP + gas (no tokenFee since undefined)
925
+ const availableInventory = requestedAmount + TOTAL_RESERVATION;
926
+ const route = createTestRoute({ amount: requestedAmount });
927
+ createTestIntent({ amount: requestedAmount });
928
+ inventoryRebalancer.setInventoryBalances({
929
+ [SOLANA_CHAIN]: availableInventory,
930
+ [ARBITRUM_CHAIN]: 0n,
931
+ });
932
+ const results = await inventoryRebalancer.rebalance([route]);
933
+ expect(results).to.have.lengthOf(1);
934
+ expect(results[0].success).to.be.true;
935
+ const txParams = warpCore.getTransferRemoteTxs.lastCall.args[0];
936
+ expect(txParams.originTokenAmount.amount).to.equal(requestedAmount);
937
+ });
938
+ it('reduces maxTransferable when large tokenFeeQuote is present', async () => {
939
+ // Setup: Native token with large tokenFeeQuote that significantly reduces maxTransferable
940
+ adapterStub.quoteTransferRemoteGas.resolves({
941
+ igpQuote: { amount: IGP_COST },
942
+ tokenFeeQuote: { amount: 5000000000000000n }, // Large fee (5e15 wei)
943
+ });
944
+ const arbitrumToken = {
945
+ chainName: ARBITRUM_CHAIN,
946
+ standard: TokenStandard.EvmHypNative,
947
+ getHypAdapter: Sinon.stub().returns(adapterStub),
948
+ };
949
+ const solanaToken = {
950
+ chainName: SOLANA_CHAIN,
951
+ standard: TokenStandard.EvmHypNative,
952
+ getHypAdapter: Sinon.stub().returns(adapterStub),
953
+ };
954
+ warpCore.tokens = [arbitrumToken, solanaToken];
955
+ const requestedAmount = 10000000000000000n; // 0.01 ETH
956
+ // Available = requested + IGP + gas + large tokenFee
957
+ const largeTokenFee = 5000000000000000n;
958
+ const availableInventory = requestedAmount + TOTAL_RESERVATION + largeTokenFee;
959
+ const route = createTestRoute({ amount: requestedAmount });
960
+ createTestIntent({ amount: requestedAmount });
961
+ inventoryRebalancer.setInventoryBalances({
962
+ [SOLANA_CHAIN]: availableInventory,
963
+ [ARBITRUM_CHAIN]: 0n,
964
+ });
965
+ const results = await inventoryRebalancer.rebalance([route]);
966
+ // Verify: Transfer succeeds with full amount (we have enough for amount + all costs)
967
+ // This demonstrates that tokenFeeQuote is properly deducted from maxTransferable
968
+ expect(results).to.have.lengthOf(1);
969
+ expect(results[0].success).to.be.true;
970
+ });
971
+ });
972
+ describe('LiFi Bridge Integration (for future inventory_movement)', () => {
973
+ // These tests validate the mock utilities are working correctly
974
+ // and prepare for when inventory_movement is implemented
975
+ it('mock utilities create valid quote', () => {
976
+ const quote = createMockBridgeQuote({
977
+ fromAmount: 10000000000n,
978
+ toAmount: 9950000000n,
979
+ });
980
+ expect(quote.id).to.equal('quote-123');
981
+ expect(quote.tool).to.equal('across');
982
+ expect(quote.fromAmount).to.equal(10000000000n);
983
+ expect(quote.toAmount).to.equal(9950000000n);
984
+ });
985
+ it('bridge mock can be configured for quote', async () => {
986
+ bridge.quote.resolves(createMockBridgeQuote({
987
+ fromAmount: 10000000000n,
988
+ toAmount: 9950000000n,
989
+ }));
990
+ const quote = await bridge.quote({
991
+ fromChain: ARBITRUM_DOMAIN,
992
+ toChain: SOLANA_DOMAIN,
993
+ fromToken: '0xUSDC',
994
+ toToken: '0xUSDC',
995
+ fromAmount: 10000000000n,
996
+ fromAddress: INVENTORY_SIGNER,
997
+ });
998
+ expect(quote.fromAmount).to.equal(10000000000n);
999
+ expect(quote.toAmount).to.equal(9950000000n);
1000
+ });
1001
+ });
1002
+ describe('Smart Partial Transfer Threshold', () => {
1003
+ // Test the 90% consolidation threshold for partial transfers
1004
+ // Tests use non-native tokens (EvmHypCollateral) so minViableTransfer = 0
1005
+ it('does partial transfer when inventory is available on destination', async () => {
1006
+ // amount = 1 ETH, availableOnDestination = 0.5 ETH
1007
+ // With simplified logic: if maxTransferable >= minViableTransfer, do partial transfer
1008
+ // For non-native tokens, minViableTransfer = 0, so partial transfer happens
1009
+ const amount = BigInt(1e18); // 1 ETH
1010
+ const availableOnDestination = BigInt(0.5e18); // 0.5 ETH on destination
1011
+ const route = createTestRoute({ amount });
1012
+ createTestIntent({ amount });
1013
+ // Inventory on destination (SOLANA)
1014
+ inventoryRebalancer.setInventoryBalances({
1015
+ [SOLANA_CHAIN]: availableOnDestination,
1016
+ [ARBITRUM_CHAIN]: 0n,
1017
+ });
1018
+ const results = await inventoryRebalancer.rebalance([route]);
1019
+ expect(results).to.have.lengthOf(1);
1020
+ expect(results[0].success).to.be.true;
1021
+ const txParams = warpCore.getTransferRemoteTxs.lastCall.args[0];
1022
+ expect(txParams.originTokenAmount.amount).to.equal(availableOnDestination);
1023
+ // Verify: Bridge was NOT called (no need to bridge when partial transfer is viable)
1024
+ expect(bridge.execute.called).to.be.false;
1025
+ });
1026
+ it('does partial transfer when maxTransferable >= minViableTransfer', async () => {
1027
+ // For non-native tokens (EvmHypCollateral), minViableTransfer = 0
1028
+ // So any positive maxTransferable triggers partial transfer
1029
+ const amount = BigInt(2e18); // 2 ETH requested
1030
+ const maxTransferable = BigInt(0.6e18); // 0.6 ETH available
1031
+ const route = createTestRoute({ amount });
1032
+ createTestIntent({ amount });
1033
+ // 0.6 ETH available on destination
1034
+ inventoryRebalancer.setInventoryBalances({
1035
+ [SOLANA_CHAIN]: maxTransferable,
1036
+ [ARBITRUM_CHAIN]: 0n,
1037
+ });
1038
+ const results = await inventoryRebalancer.rebalance([route]);
1039
+ expect(results).to.have.lengthOf(1);
1040
+ expect(results[0].success).to.be.true;
1041
+ const txParams = warpCore.getTransferRemoteTxs.lastCall.args[0];
1042
+ expect(txParams.originTokenAmount.amount).to.equal(maxTransferable);
1043
+ });
1044
+ it('does NOT do partial transfer when maxTransferable < minViableTransfer (native tokens)', async () => {
1045
+ // For native tokens (EvmHypNative), minViableTransfer = totalCost * 2
1046
+ // When available inventory minus costs is below minViableTransfer, falls through to bridging
1047
+ const arbitrumToken = {
1048
+ chainName: ARBITRUM_CHAIN,
1049
+ standard: TokenStandard.EvmHypNative,
1050
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1051
+ };
1052
+ const solanaToken = {
1053
+ chainName: SOLANA_CHAIN,
1054
+ standard: TokenStandard.EvmHypNative,
1055
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1056
+ };
1057
+ warpCore.tokens = [arbitrumToken, solanaToken];
1058
+ const amount = BigInt(2e18); // 2 ETH
1059
+ // Available inventory is small - after subtracting costs, maxTransferable < minViableTransfer
1060
+ // minViableTransfer = ~0.0066 ETH (totalCost * 2)
1061
+ // If available = 0.005 ETH, after costs ~0, maxTransferable < minViableTransfer
1062
+ const availableOnDestination = BigInt(0.003e18); // 0.003 ETH - below minViableTransfer
1063
+ const availableOnSource = BigInt(0.6e18); // 0.6 ETH on ARBITRUM
1064
+ const route = createTestRoute({ amount });
1065
+ createTestIntent({ amount });
1066
+ // Inventory on destination - too small after costs, but source has inventory
1067
+ inventoryRebalancer.setInventoryBalances({
1068
+ [SOLANA_CHAIN]: availableOnDestination,
1069
+ [ARBITRUM_CHAIN]: availableOnSource,
1070
+ });
1071
+ // Mock bridge
1072
+ bridge.quote.resolves(createMockBridgeQuote({
1073
+ fromAmount: BigInt(0.5e18),
1074
+ toAmount: BigInt(0.48e18),
1075
+ }));
1076
+ bridge.execute.resolves({
1077
+ txHash: '0xBridgeTxHash',
1078
+ fromChain: 42161,
1079
+ toChain: 1399811149,
1080
+ });
1081
+ const results = await inventoryRebalancer.rebalance([route]);
1082
+ expect(results).to.have.lengthOf(1);
1083
+ expect(results[0].success).to.be.true;
1084
+ // Verify: inventory movement via bridge happened (NOT partial transferRemote)
1085
+ expect(bridge.execute.called).to.be.true;
1086
+ });
1087
+ });
1088
+ describe('Early Exit for Small Amounts', () => {
1089
+ // Gas estimation: 300,000 gas × 10 gwei = 3,000,000,000,000 wei
1090
+ // Buffered gas limit (10%): 330,000 gas
1091
+ // Buffered gas cost: 330,000 × 10 gwei = 3,300,000,000,000 wei
1092
+ // IGP quote: 1,000,000 wei
1093
+ // Total cost: IGP + buffered gas = 3,300,001,000,000 wei (~0.0033 ETH)
1094
+ // Min viable transfer (2x total cost): ~0.0066 ETH
1095
+ const MIN_VIABLE = BigInt(6.6e12); // ~0.0066 ETH
1096
+ it('completes intent when amount < minViableTransfer', async () => {
1097
+ // Use native token to get non-zero minViableTransfer
1098
+ const arbitrumToken = {
1099
+ chainName: ARBITRUM_CHAIN,
1100
+ standard: TokenStandard.EvmHypNative,
1101
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1102
+ };
1103
+ const solanaToken = {
1104
+ chainName: SOLANA_CHAIN,
1105
+ standard: TokenStandard.EvmHypNative,
1106
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1107
+ };
1108
+ warpCore.tokens = [arbitrumToken, solanaToken];
1109
+ // Amount smaller than minViableTransfer
1110
+ const smallAmount = MIN_VIABLE / 2n; // 0.0033 ETH < minViable 0.0066 ETH
1111
+ const route = createTestRoute({ amount: smallAmount });
1112
+ createTestIntent({ amount: smallAmount });
1113
+ // Even with plenty of inventory, small amount triggers early exit
1114
+ inventoryRebalancer.setInventoryBalances({
1115
+ [SOLANA_CHAIN]: BigInt(10e18),
1116
+ [ARBITRUM_CHAIN]: BigInt(10e18),
1117
+ });
1118
+ const results = await inventoryRebalancer.rebalance([route]);
1119
+ expect(results).to.have.lengthOf(1);
1120
+ expect(results[0].success).to.be.true;
1121
+ expect(results[0].reason).to.equal('completed_with_acceptable_loss');
1122
+ // Verify: Intent was completed (not left in progress)
1123
+ expect(actionTracker.completeRebalanceIntent.calledOnce).to.be.true;
1124
+ expect(actionTracker.completeRebalanceIntent.calledWith('intent-1')).to.be
1125
+ .true;
1126
+ // Verify: No transferRemote was attempted
1127
+ expect(actionTracker.createRebalanceAction.called).to.be.false;
1128
+ });
1129
+ });
1130
+ describe('Parallel Multi-Source Bridging', () => {
1131
+ // Third chain for multi-source tests
1132
+ const BASE_CHAIN = 'base';
1133
+ const BASE_DOMAIN = 8453;
1134
+ beforeEach(() => {
1135
+ // Extend multiProvider to handle BASE_CHAIN
1136
+ multiProvider.getDomainId.callsFake((chain) => {
1137
+ if (chain === ARBITRUM_CHAIN)
1138
+ return ARBITRUM_DOMAIN;
1139
+ if (chain === SOLANA_CHAIN)
1140
+ return SOLANA_DOMAIN;
1141
+ if (chain === BASE_CHAIN)
1142
+ return BASE_DOMAIN;
1143
+ return 0;
1144
+ });
1145
+ multiProvider.getChainId = Sinon.stub().callsFake((chain) => {
1146
+ if (chain === ARBITRUM_CHAIN)
1147
+ return 42161;
1148
+ if (chain === SOLANA_CHAIN)
1149
+ return 1399811149;
1150
+ if (chain === BASE_CHAIN)
1151
+ return 8453;
1152
+ return 0;
1153
+ });
1154
+ // Add token for BASE_CHAIN
1155
+ const baseToken = {
1156
+ chainName: BASE_CHAIN,
1157
+ standard: TokenStandard.EvmHypCollateral,
1158
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1159
+ addressOrDenom: '0xBaseToken',
1160
+ collateralAddressOrDenom: '0xBaseCollateralERC20',
1161
+ };
1162
+ warpCore.tokens.push(baseToken);
1163
+ multiProvider.getSigner = Sinon.stub().returns(TEST_WALLET);
1164
+ });
1165
+ it('bridges from multiple sources in parallel', async () => {
1166
+ // Need 1 ETH on solana, have 0.6 ETH on arbitrum and 0.6 ETH on base
1167
+ const amount = BigInt(1e18);
1168
+ const perChainInventory = BigInt(0.6e18);
1169
+ const route = createTestRoute({ amount });
1170
+ createTestIntent({ amount });
1171
+ // No inventory on destination, inventory on sources
1172
+ inventoryRebalancer.setInventoryBalances({
1173
+ [SOLANA_CHAIN]: 0n,
1174
+ [ARBITRUM_CHAIN]: perChainInventory,
1175
+ [BASE_CHAIN]: perChainInventory,
1176
+ });
1177
+ // Mock bridge quotes and execution
1178
+ bridge.quote.resolves(createMockBridgeQuote({
1179
+ fromAmount: BigInt(0.55e18),
1180
+ toAmount: BigInt(0.525e18),
1181
+ }));
1182
+ bridge.execute.resolves({
1183
+ txHash: '0xBridgeTxHash',
1184
+ fromChain: 42161,
1185
+ toChain: 1399811149,
1186
+ });
1187
+ const results = await inventoryRebalancer.rebalance([route]);
1188
+ expect(results).to.have.lengthOf(1);
1189
+ expect(results[0].success).to.be.true;
1190
+ // Verify: Bridge was called twice (once for each source)
1191
+ expect(bridge.execute.callCount).to.equal(2);
1192
+ });
1193
+ it('applies 5% buffer to total bridge amount', async () => {
1194
+ // Need 1 ETH -> should plan to bridge 1.05 ETH total (with 5% buffer)
1195
+ const amount = BigInt(1e18); // 1 ETH
1196
+ const availableInventory = BigInt(2e18); // 2 ETH on source
1197
+ const route = createTestRoute({ amount });
1198
+ createTestIntent({ amount });
1199
+ // No inventory on destination, plenty on source
1200
+ inventoryRebalancer.setInventoryBalances({
1201
+ [SOLANA_CHAIN]: 0n,
1202
+ [ARBITRUM_CHAIN]: availableInventory,
1203
+ });
1204
+ // Capture the quote amount from executeInventoryMovement
1205
+ // (calculateMaxViableBridgeAmount doesn't quote for ERC20 tokens)
1206
+ let quotedFromAmount;
1207
+ bridge.quote.callsFake(async (params) => {
1208
+ quotedFromAmount = params.fromAmount;
1209
+ return createMockBridgeQuote({
1210
+ fromAmount: params.fromAmount ?? params.toAmount,
1211
+ toAmount: params.fromAmount ?? params.toAmount,
1212
+ });
1213
+ });
1214
+ bridge.execute.resolves({
1215
+ txHash: '0xBridgeTxHash',
1216
+ fromChain: 42161,
1217
+ toChain: 1399811149,
1218
+ });
1219
+ await inventoryRebalancer.rebalance([route]);
1220
+ // Verify: 5% buffer applied (1 ETH * 1.05 = 1.05 ETH)
1221
+ // The bridge plan uses pre-validated amounts (for ERC20, full inventory available)
1222
+ // But the target is (amount * 105%), so if source has >= target, we bridge exactly target
1223
+ const expectedWithBuffer = (amount * 105n) / 100n;
1224
+ expect(quotedFromAmount).to.equal(expectedWithBuffer);
1225
+ });
1226
+ it('continues when some bridges fail', async () => {
1227
+ const amount = BigInt(1e18);
1228
+ const perChainInventory = BigInt(0.6e18);
1229
+ const route = createTestRoute({ amount });
1230
+ createTestIntent({ amount });
1231
+ // No inventory on destination, inventory on sources
1232
+ inventoryRebalancer.setInventoryBalances({
1233
+ [SOLANA_CHAIN]: 0n,
1234
+ [ARBITRUM_CHAIN]: perChainInventory,
1235
+ [BASE_CHAIN]: perChainInventory,
1236
+ });
1237
+ bridge.quote.resolves(createMockBridgeQuote({
1238
+ fromAmount: BigInt(0.55e18),
1239
+ toAmount: BigInt(0.525e18),
1240
+ }));
1241
+ // First bridge succeeds, second fails
1242
+ bridge.execute
1243
+ .onFirstCall()
1244
+ .resolves({
1245
+ txHash: '0xSuccessTxHash',
1246
+ fromChain: 42161,
1247
+ toChain: 1399811149,
1248
+ })
1249
+ .onSecondCall()
1250
+ .rejects(new Error('Bridge execution failed'));
1251
+ const results = await inventoryRebalancer.rebalance([route]);
1252
+ // Verify: Overall success (at least one bridge succeeded)
1253
+ expect(results).to.have.lengthOf(1);
1254
+ expect(results[0].success).to.be.true;
1255
+ });
1256
+ it('returns failure when all bridges fail', async () => {
1257
+ const amount = BigInt(1e18);
1258
+ const perChainInventory = BigInt(0.6e18);
1259
+ const route = createTestRoute({ amount });
1260
+ createTestIntent({ amount });
1261
+ // No inventory on destination, inventory on sources
1262
+ inventoryRebalancer.setInventoryBalances({
1263
+ [SOLANA_CHAIN]: 0n,
1264
+ [ARBITRUM_CHAIN]: perChainInventory,
1265
+ [BASE_CHAIN]: perChainInventory,
1266
+ });
1267
+ bridge.quote.resolves(createMockBridgeQuote({
1268
+ fromAmount: BigInt(0.55e18),
1269
+ toAmount: BigInt(0.525e18),
1270
+ }));
1271
+ // All bridges fail
1272
+ bridge.execute.rejects(new Error('Bridge execution failed'));
1273
+ const results = await inventoryRebalancer.rebalance([route]);
1274
+ // Verify: Failure when all bridges fail
1275
+ expect(results).to.have.lengthOf(1);
1276
+ expect(results[0].success).to.be.false;
1277
+ expect(results[0].error).to.include('All inventory movements failed');
1278
+ });
1279
+ });
1280
+ describe('Bridge Viability Check', () => {
1281
+ // Tests for the gas-aware planning approach that prevents "insufficient funds for gas * price + value" errors
1282
+ // by calculating max viable bridge amounts BEFORE creating bridge plans.
1283
+ // Uses calculateMaxViableBridgeAmount which:
1284
+ // 1. Gets a quote to determine gas costs
1285
+ // 2. Applies 20x multiplier on quoted gas (LiFi underestimates)
1286
+ // 3. Returns 0 if gas exceeds 10% of inventory (not economically viable)
1287
+ it('filters out sources where gas cost exceeds 10% of inventory', async () => {
1288
+ // Setup: Native token bridge where gas cost is too high relative to balance
1289
+ // Scenario: Arbitrum has 0.00219 ETH, estimated gas (with 20x buffer) exceeds 10% threshold
1290
+ const arbitrumToken = {
1291
+ chainName: ARBITRUM_CHAIN,
1292
+ standard: TokenStandard.EvmHypNative, // Native token for gas check
1293
+ addressOrDenom: '0xArbitrumNative',
1294
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1295
+ };
1296
+ const solanaToken = {
1297
+ chainName: SOLANA_CHAIN,
1298
+ standard: TokenStandard.EvmHypNative,
1299
+ addressOrDenom: '0xSolanaNative',
1300
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1301
+ };
1302
+ warpCore.tokens = [arbitrumToken, solanaToken];
1303
+ const amount = BigInt(1e18); // 1 ETH requested on destination
1304
+ const route = createTestRoute({ amount });
1305
+ createTestIntent({ amount });
1306
+ // Raw balance on source chain (ARBITRUM) - the limiting factor
1307
+ const rawBalance = BigInt('2194632084196208'); // ~0.00219 ETH
1308
+ // No inventory on destination, low balance on source
1309
+ inventoryRebalancer.setInventoryBalances({
1310
+ [SOLANA_CHAIN]: 0n,
1311
+ [ARBITRUM_CHAIN]: rawBalance,
1312
+ });
1313
+ // Mock quote with gas costs that exceed 10% threshold when multiplied by 20
1314
+ // rawBalance = 0.00219 ETH
1315
+ // 10% threshold = 0.000219 ETH
1316
+ // gasCosts = 0.00005 ETH, estimated = 0.001 ETH (20x multiplier)
1317
+ // 0.001 > 0.000219 → not viable
1318
+ bridge.quote.resolves(createMockBridgeQuote({
1319
+ fromAmount: rawBalance,
1320
+ toAmount: rawBalance - BigInt(1e14), // Some output
1321
+ gasCosts: BigInt('50000000000000'), // 0.00005 ETH, becomes 0.001 ETH with 20x
1322
+ feeCosts: 0n,
1323
+ }));
1324
+ const results = await inventoryRebalancer.rebalance([route]);
1325
+ // Verify: Should fail because no sources pass viability check at planning time
1326
+ expect(results).to.have.lengthOf(1);
1327
+ expect(results[0].success).to.be.false;
1328
+ // New behavior: Error is "No viable bridge sources" (filtered at planning time)
1329
+ // rather than "Insufficient funds" (which was at execution time)
1330
+ expect(results[0].error).to.include('No viable bridge sources');
1331
+ // Verify: Bridge.execute should NOT have been called (filtered during planning)
1332
+ expect(bridge.execute.called).to.be.false;
1333
+ });
1334
+ it('proceeds with bridge when total cost is within available balance', async () => {
1335
+ // Setup: Native token bridge where we have enough balance
1336
+ const arbitrumToken = {
1337
+ chainName: ARBITRUM_CHAIN,
1338
+ standard: TokenStandard.EvmHypNative,
1339
+ addressOrDenom: '0xArbitrumNative',
1340
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1341
+ };
1342
+ const solanaToken = {
1343
+ chainName: SOLANA_CHAIN,
1344
+ standard: TokenStandard.EvmHypNative,
1345
+ addressOrDenom: '0xSolanaNative',
1346
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1347
+ };
1348
+ warpCore.tokens = [arbitrumToken, solanaToken];
1349
+ const amount = BigInt(1e18); // 1 ETH requested
1350
+ const route = createTestRoute({ amount });
1351
+ createTestIntent({ amount });
1352
+ // Plenty of balance on source chain
1353
+ const rawBalance = BigInt(2e18); // 2 ETH - more than enough
1354
+ inventoryRebalancer.setInventoryBalances({
1355
+ [SOLANA_CHAIN]: 0n,
1356
+ [ARBITRUM_CHAIN]: rawBalance,
1357
+ });
1358
+ // Quote with reasonable costs well under the balance
1359
+ bridge.quote.resolves(createMockBridgeQuote({
1360
+ fromAmount: BigInt(1.05e18), // 1.05 ETH (with buffer)
1361
+ toAmount: BigInt(1e18),
1362
+ gasCosts: BigInt(1e15), // 0.001 ETH gas
1363
+ feeCosts: 0n,
1364
+ }));
1365
+ // Mock successful execution
1366
+ bridge.execute.resolves({
1367
+ txHash: '0xSuccessBridgeTxHash',
1368
+ fromChain: 42161,
1369
+ toChain: 1399811149,
1370
+ });
1371
+ const results = await inventoryRebalancer.rebalance([route]);
1372
+ // Verify: Should succeed
1373
+ expect(results).to.have.lengthOf(1);
1374
+ expect(results[0].success).to.be.true;
1375
+ // Verify: Bridge.execute WAS called (not abandoned)
1376
+ expect(bridge.execute.calledOnce).to.be.true;
1377
+ });
1378
+ it('viability check only applies to native tokens (not ERC20)', async () => {
1379
+ // Setup: ERC20 token bridge - gas is paid separately in ETH, not from token balance
1380
+ const arbitrumToken = {
1381
+ chainName: ARBITRUM_CHAIN,
1382
+ standard: TokenStandard.EvmHypCollateral, // ERC20, not native
1383
+ addressOrDenom: '0xArbitrumToken',
1384
+ collateralAddressOrDenom: '0xArbitrumCollateralERC20',
1385
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1386
+ };
1387
+ const solanaToken = {
1388
+ chainName: SOLANA_CHAIN,
1389
+ standard: TokenStandard.EvmHypCollateral,
1390
+ addressOrDenom: '0xSolanaToken',
1391
+ collateralAddressOrDenom: '0xSolanaCollateralERC20',
1392
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1393
+ };
1394
+ warpCore.tokens = [arbitrumToken, solanaToken];
1395
+ const amount = BigInt(1e18); // 1 token
1396
+ const route = createTestRoute({ amount });
1397
+ createTestIntent({ amount });
1398
+ // Small token balance (but gas is paid in ETH, so this shouldn't matter for viability)
1399
+ const tokenBalance = BigInt(1e18);
1400
+ inventoryRebalancer.setInventoryBalances({
1401
+ [SOLANA_CHAIN]: 0n,
1402
+ [ARBITRUM_CHAIN]: tokenBalance,
1403
+ });
1404
+ // Quote with high gas costs (but for ERC20, this shouldn't trigger viability check)
1405
+ bridge.quote.resolves(createMockBridgeQuote({
1406
+ fromAmount: BigInt(1.05e18),
1407
+ toAmount: BigInt(1e18),
1408
+ gasCosts: BigInt(1e18), // Very high gas (would fail viability if this were native)
1409
+ feeCosts: 0n,
1410
+ }));
1411
+ bridge.execute.resolves({
1412
+ txHash: '0xERC20BridgeTxHash',
1413
+ fromChain: 42161,
1414
+ toChain: 1399811149,
1415
+ });
1416
+ const results = await inventoryRebalancer.rebalance([route]);
1417
+ // Verify: Should succeed because ERC20 viability check doesn't include gasCosts
1418
+ expect(results).to.have.lengthOf(1);
1419
+ expect(results[0].success).to.be.true;
1420
+ expect(bridge.execute.calledOnce).to.be.true;
1421
+ });
1422
+ it('calculates max viable amount as inventory minus (gasCosts * 20) for native tokens', async () => {
1423
+ // Setup: Native token with enough balance for viable bridge
1424
+ const arbitrumToken = {
1425
+ chainName: ARBITRUM_CHAIN,
1426
+ standard: TokenStandard.EvmHypNative,
1427
+ addressOrDenom: '0xArbitrumNative',
1428
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1429
+ };
1430
+ const solanaToken = {
1431
+ chainName: SOLANA_CHAIN,
1432
+ standard: TokenStandard.EvmHypNative,
1433
+ addressOrDenom: '0xSolanaNative',
1434
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1435
+ };
1436
+ warpCore.tokens = [arbitrumToken, solanaToken];
1437
+ const amount = BigInt(0.5e18); // 0.5 ETH requested
1438
+ const route = createTestRoute({ amount });
1439
+ createTestIntent({ amount });
1440
+ // Large balance - should be viable
1441
+ const rawBalance = BigInt(1e18); // 1 ETH
1442
+ inventoryRebalancer.setInventoryBalances({
1443
+ [SOLANA_CHAIN]: 0n,
1444
+ [ARBITRUM_CHAIN]: rawBalance,
1445
+ });
1446
+ // gasCosts = 0.001 ETH, estimated = 0.02 ETH (20x multiplier)
1447
+ // maxViable = 1 ETH - 0.02 ETH = 0.98 ETH
1448
+ // 10% threshold = 0.1 ETH, estimatedGas (0.02) < threshold → viable
1449
+ const gasCosts = BigInt(0.001e18); // 0.001 ETH
1450
+ bridge.quote.resolves(createMockBridgeQuote({
1451
+ fromAmount: rawBalance,
1452
+ toAmount: rawBalance - BigInt(1e15),
1453
+ gasCosts,
1454
+ feeCosts: 0n,
1455
+ }));
1456
+ bridge.execute.resolves({
1457
+ txHash: '0xSuccessBridgeTxHash',
1458
+ fromChain: 42161,
1459
+ toChain: 1399811149,
1460
+ });
1461
+ const results = await inventoryRebalancer.rebalance([route]);
1462
+ // Verify: Should succeed - bridge is viable
1463
+ expect(results).to.have.lengthOf(1);
1464
+ expect(results[0].success).to.be.true;
1465
+ expect(bridge.execute.calledOnce).to.be.true;
1466
+ // Verify: The quoted fromAmount should be the target (since maxViable > target)
1467
+ // For the execution quote (second quote call):
1468
+ // targetWithBuffer = (0.5 ETH) * 1.05 = 0.525 ETH (for non-inventory execution, costs are 0)
1469
+ const executionQuoteCall = bridge.quote
1470
+ .getCalls()
1471
+ .find((call) => call.args[0].fromAmount !== undefined &&
1472
+ call.args[0].fromAmount !== rawBalance);
1473
+ // Since maxViable (0.98 ETH) > targetWithBuffer (0.525 ETH), we bridge exactly targetWithBuffer
1474
+ expect(executionQuoteCall).to.exist;
1475
+ });
1476
+ it('handles quote failures gracefully by skipping the source chain', async () => {
1477
+ // Setup: Native token where quote fails
1478
+ const arbitrumToken = {
1479
+ chainName: ARBITRUM_CHAIN,
1480
+ standard: TokenStandard.EvmHypNative,
1481
+ addressOrDenom: '0xArbitrumNative',
1482
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1483
+ };
1484
+ const solanaToken = {
1485
+ chainName: SOLANA_CHAIN,
1486
+ standard: TokenStandard.EvmHypNative,
1487
+ addressOrDenom: '0xSolanaNative',
1488
+ getHypAdapter: Sinon.stub().returns(adapterStub),
1489
+ };
1490
+ warpCore.tokens = [arbitrumToken, solanaToken];
1491
+ const amount = BigInt(1e18);
1492
+ const route = createTestRoute({ amount });
1493
+ createTestIntent({ amount });
1494
+ const rawBalance = BigInt(2e18); // 2 ETH
1495
+ inventoryRebalancer.setInventoryBalances({
1496
+ [SOLANA_CHAIN]: 0n,
1497
+ [ARBITRUM_CHAIN]: rawBalance,
1498
+ });
1499
+ // Quote fails for viability check
1500
+ bridge.quote.rejects(new Error('LiFi API timeout'));
1501
+ const results = await inventoryRebalancer.rebalance([route]);
1502
+ // Verify: Should fail because quote error means no viable sources
1503
+ expect(results).to.have.lengthOf(1);
1504
+ expect(results[0].success).to.be.false;
1505
+ expect(results[0].error).to.include('No viable bridge sources');
1506
+ // Verify: Bridge.execute should NOT have been called
1507
+ expect(bridge.execute.called).to.be.false;
1508
+ });
1509
+ });
1510
+ });
1511
+ //# sourceMappingURL=InventoryRebalancer.test.js.map