0xtrails 0.16.2 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1341) hide show
  1. package/README.md +488 -3
  2. package/dist/BluvoExchangeSelection.lazy-D6ynQVSb.js +1 -0
  3. package/dist/BluvoOnrampFlow.lazy-BcDqhGLi.js +143 -0
  4. package/dist/ConnectWalletCard-BkbHCcWi.js +26 -0
  5. package/dist/actionBuilder-CAS2u5wu.js +2 -0
  6. package/dist/actions/index.d.ts +7 -23
  7. package/dist/actions/index.js +1 -37
  8. package/dist/contractConstants-CvJrYK9v.js +1 -0
  9. package/dist/defineProperty-BbfpZ9Tg.js +1 -0
  10. package/dist/edge-DmNcuJar.d.ts +121 -0
  11. package/dist/edge-L_Lk1K6j.js +1 -0
  12. package/dist/hooks/index.d.ts +6 -38
  13. package/dist/hooks/index.js +1 -67
  14. package/dist/hydrate/index.d.ts +196 -8
  15. package/dist/hydrate/index.js +1 -19
  16. package/dist/hydrate-QyWqQfec.js +1 -0
  17. package/dist/iife/trails.min.js +7324 -0
  18. package/dist/index-CMdwQmYL.d.ts +1044 -0
  19. package/dist/index.d.ts +1023 -114
  20. package/dist/index.js +1 -317
  21. package/dist/multicall-BCUHt_9t.d.ts +148 -0
  22. package/dist/offlineRecovery-BfgccnFf.d.ts +1232 -0
  23. package/dist/plugins/edge.d.ts +4 -0
  24. package/dist/plugins/edge.js +1 -0
  25. package/dist/quoteError-CmTH5Qm2.d.ts +24 -0
  26. package/dist/src-Cy3oxYgV.js +94 -0
  27. package/dist/sushiswapV3-D3h41LNZ.d.ts +723 -0
  28. package/dist/tokenTypes-D812t5L9.d.ts +31 -0
  29. package/dist/types-BK0WkVnx.d.ts +2161 -0
  30. package/dist/useViewManager-BeUH_k1s.d.ts +1224 -0
  31. package/dist/{actions/utils.d.ts → utils-KPnWBA9x.d.ts} +77 -52
  32. package/dist/widget/connect-showcase.d.ts +8 -0
  33. package/dist/widget/connect-showcase.js +1 -0
  34. package/dist/widget/index.d.ts +5 -21
  35. package/dist/widget/index.js +1 -33
  36. package/package.json +42 -42
  37. package/dist/_virtual/_@oxc-project_runtime@0.126.0/helpers/defineProperty.js +0 -12
  38. package/dist/_virtual/_@oxc-project_runtime@0.126.0/helpers/toPrimitive.js +0 -14
  39. package/dist/_virtual/_@oxc-project_runtime@0.126.0/helpers/toPropertyKey.js +0 -9
  40. package/dist/_virtual/_@oxc-project_runtime@0.126.0/helpers/typeof.js +0 -11
  41. package/dist/abi.d.ts +0 -37
  42. package/dist/abi.d.ts.map +0 -1
  43. package/dist/abis/erc20.d.ts +0 -19
  44. package/dist/abis/erc20.d.ts.map +0 -1
  45. package/dist/abis/requireUtils.d.ts +0 -134
  46. package/dist/abis/requireUtils.d.ts.map +0 -1
  47. package/dist/abis/requireUtils.js +0 -168
  48. package/dist/abis/trailsHydrate.d.ts +0 -7
  49. package/dist/abis/trailsHydrate.d.ts.map +0 -1
  50. package/dist/abis/trailsRouter.d.ts +0 -30
  51. package/dist/abis/trailsRouter.d.ts.map +0 -1
  52. package/dist/abis/trailsRouter.js +0 -66
  53. package/dist/abis/trailsSweep.d.ts +0 -7
  54. package/dist/abis/trailsSweep.d.ts.map +0 -1
  55. package/dist/abortController.d.ts +0 -8
  56. package/dist/abortController.d.ts.map +0 -1
  57. package/dist/abortController.js +0 -23
  58. package/dist/actions/actionBuilder.d.ts +0 -424
  59. package/dist/actions/actionBuilder.d.ts.map +0 -1
  60. package/dist/actions/actionBuilder.js +0 -173
  61. package/dist/actions/constants.d.ts +0 -1809
  62. package/dist/actions/constants.d.ts.map +0 -1
  63. package/dist/actions/constants.js +0 -37
  64. package/dist/actions/custom-integrations/sushiswapV3/addresses.d.ts +0 -4
  65. package/dist/actions/custom-integrations/sushiswapV3/addresses.d.ts.map +0 -1
  66. package/dist/actions/custom-integrations/sushiswapV3/addresses.js +0 -33
  67. package/dist/actions/custom-integrations/sushiswapV3/calldata.d.ts +0 -4
  68. package/dist/actions/custom-integrations/sushiswapV3/calldata.d.ts.map +0 -1
  69. package/dist/actions/custom-integrations/sushiswapV3/calldata.js +0 -124
  70. package/dist/actions/custom-integrations/sushiswapV3/calls.d.ts +0 -28
  71. package/dist/actions/custom-integrations/sushiswapV3/calls.d.ts.map +0 -1
  72. package/dist/actions/custom-integrations/sushiswapV3/calls.js +0 -27
  73. package/dist/actions/custom-integrations/sushiswapV3/helpers.d.ts +0 -15
  74. package/dist/actions/custom-integrations/sushiswapV3/helpers.d.ts.map +0 -1
  75. package/dist/actions/custom-integrations/sushiswapV3/helpers.js +0 -27
  76. package/dist/actions/custom-integrations/sushiswapV3/sushiswapV3.d.ts +0 -9
  77. package/dist/actions/custom-integrations/sushiswapV3/sushiswapV3.d.ts.map +0 -1
  78. package/dist/actions/custom-integrations/sushiswapV3/sushiswapV3.js +0 -246
  79. package/dist/actions/custom-integrations/sushiswapV3/types.d.ts +0 -95
  80. package/dist/actions/custom-integrations/sushiswapV3/types.d.ts.map +0 -1
  81. package/dist/actions/custom-integrations/uniswapV3/addresses.d.ts +0 -4
  82. package/dist/actions/custom-integrations/uniswapV3/addresses.d.ts.map +0 -1
  83. package/dist/actions/custom-integrations/uniswapV3/addresses.js +0 -33
  84. package/dist/actions/custom-integrations/uniswapV3/calldata.d.ts +0 -4
  85. package/dist/actions/custom-integrations/uniswapV3/calldata.d.ts.map +0 -1
  86. package/dist/actions/custom-integrations/uniswapV3/calldata.js +0 -190
  87. package/dist/actions/custom-integrations/uniswapV3/calls.d.ts +0 -50
  88. package/dist/actions/custom-integrations/uniswapV3/calls.d.ts.map +0 -1
  89. package/dist/actions/custom-integrations/uniswapV3/calls.js +0 -27
  90. package/dist/actions/custom-integrations/uniswapV3/helpers.d.ts +0 -23
  91. package/dist/actions/custom-integrations/uniswapV3/helpers.d.ts.map +0 -1
  92. package/dist/actions/custom-integrations/uniswapV3/helpers.js +0 -27
  93. package/dist/actions/custom-integrations/uniswapV3/types.d.ts +0 -90
  94. package/dist/actions/custom-integrations/uniswapV3/types.d.ts.map +0 -1
  95. package/dist/actions/custom-integrations/uniswapV3/uniswapV3.d.ts +0 -9
  96. package/dist/actions/custom-integrations/uniswapV3/uniswapV3.d.ts.map +0 -1
  97. package/dist/actions/custom-integrations/uniswapV3/uniswapV3.js +0 -244
  98. package/dist/actions/destinationCalls.d.ts +0 -17
  99. package/dist/actions/destinationCalls.d.ts.map +0 -1
  100. package/dist/actions/destinationCalls.js +0 -43
  101. package/dist/actions/dynamic.d.ts +0 -97
  102. package/dist/actions/dynamic.d.ts.map +0 -1
  103. package/dist/actions/dynamic.js +0 -27
  104. package/dist/actions/hooks/useEarnBalances.d.ts +0 -53
  105. package/dist/actions/hooks/useEarnBalances.d.ts.map +0 -1
  106. package/dist/actions/hooks/useEarnBalances.js +0 -37
  107. package/dist/actions/hooks/useEarnMarkets.d.ts +0 -29
  108. package/dist/actions/hooks/useEarnMarkets.d.ts.map +0 -1
  109. package/dist/actions/hooks/useEarnMarkets.js +0 -30
  110. package/dist/actions/hooks/useEarnProviders.d.ts +0 -18
  111. package/dist/actions/hooks/useEarnProviders.d.ts.map +0 -1
  112. package/dist/actions/hooks/useEarnProviders.js +0 -25
  113. package/dist/actions/hooks/useResolveActions.d.ts +0 -19
  114. package/dist/actions/hooks/useResolveActions.d.ts.map +0 -1
  115. package/dist/actions/hooks/useResolveActions.js +0 -56
  116. package/dist/actions/index.d.ts.map +0 -1
  117. package/dist/actions/resolveActions.d.ts +0 -13
  118. package/dist/actions/resolveActions.d.ts.map +0 -1
  119. package/dist/actions/resolveActions.js +0 -267
  120. package/dist/actions/resolvers.d.ts +0 -29
  121. package/dist/actions/resolvers.d.ts.map +0 -1
  122. package/dist/actions/resolvers.js +0 -161
  123. package/dist/actions/types/earn.d.ts +0 -51
  124. package/dist/actions/types/earn.d.ts.map +0 -1
  125. package/dist/actions/types.d.ts +0 -319
  126. package/dist/actions/types.d.ts.map +0 -1
  127. package/dist/actions/types.js +0 -24
  128. package/dist/actions/utils.d.ts.map +0 -1
  129. package/dist/actions/utils.js +0 -203
  130. package/dist/adapters/evmAdapter.d.ts +0 -10
  131. package/dist/adapters/evmAdapter.d.ts.map +0 -1
  132. package/dist/adapters/evmAdapter.js +0 -28
  133. package/dist/analytics/hooks/useWidgetAnalytics.d.ts +0 -8
  134. package/dist/analytics/hooks/useWidgetAnalytics.d.ts.map +0 -1
  135. package/dist/analytics/hooks/useWidgetAnalytics.js +0 -41
  136. package/dist/analytics.d.ts +0 -715
  137. package/dist/analytics.d.ts.map +0 -1
  138. package/dist/analytics.js +0 -881
  139. package/dist/chainRegistry.d.ts +0 -6
  140. package/dist/chainRegistry.d.ts.map +0 -1
  141. package/dist/chainRegistry.js +0 -47
  142. package/dist/chainResolution.d.ts +0 -6
  143. package/dist/chainResolution.d.ts.map +0 -1
  144. package/dist/chainResolution.js +0 -53
  145. package/dist/chainRpcClient.d.ts +0 -8
  146. package/dist/chainRpcClient.d.ts.map +0 -1
  147. package/dist/chainRpcClient.js +0 -67
  148. package/dist/chainSwitch.d.ts +0 -7
  149. package/dist/chainSwitch.d.ts.map +0 -1
  150. package/dist/chainSwitch.js +0 -66
  151. package/dist/chains.d.ts +0 -59
  152. package/dist/chains.d.ts.map +0 -1
  153. package/dist/chains.js +0 -152
  154. package/dist/committedIntentStore.d.ts +0 -5
  155. package/dist/committedIntentStore.d.ts.map +0 -1
  156. package/dist/committedIntentStore.js +0 -52
  157. package/dist/config.d.ts +0 -2
  158. package/dist/config.d.ts.map +0 -1
  159. package/dist/configDefaults.d.ts +0 -7
  160. package/dist/configDefaults.d.ts.map +0 -1
  161. package/dist/configDefaults.js +0 -9
  162. package/dist/configStore.d.ts +0 -31
  163. package/dist/configStore.d.ts.map +0 -1
  164. package/dist/configStore.js +0 -53
  165. package/dist/constants.d.ts +0 -176
  166. package/dist/constants.d.ts.map +0 -1
  167. package/dist/constants.js +0 -184
  168. package/dist/contractConstants.d.ts +0 -8
  169. package/dist/contractConstants.d.ts.map +0 -1
  170. package/dist/contractConstants.js +0 -9
  171. package/dist/contractUtils.d.ts +0 -6
  172. package/dist/contractUtils.d.ts.map +0 -1
  173. package/dist/contractUtils.js +0 -19
  174. package/dist/cssUtils.d.ts +0 -2
  175. package/dist/cssUtils.d.ts.map +0 -1
  176. package/dist/cssUtils.js +0 -7
  177. package/dist/customChains.d.ts +0 -24
  178. package/dist/customChains.d.ts.map +0 -1
  179. package/dist/customChains.js +0 -20
  180. package/dist/customTokens.d.ts +0 -12
  181. package/dist/customTokens.d.ts.map +0 -1
  182. package/dist/customTokens.js +0 -64
  183. package/dist/decoders.d.ts +0 -69
  184. package/dist/decoders.d.ts.map +0 -1
  185. package/dist/decoders.js +0 -181
  186. package/dist/ens.d.ts +0 -20
  187. package/dist/ens.d.ts.map +0 -1
  188. package/dist/ens.js +0 -92
  189. package/dist/error.d.ts +0 -97
  190. package/dist/error.d.ts.map +0 -1
  191. package/dist/error.js +0 -298
  192. package/dist/estimate.d.ts +0 -78
  193. package/dist/estimate.d.ts.map +0 -1
  194. package/dist/estimate.js +0 -147
  195. package/dist/explorer.d.ts +0 -12
  196. package/dist/explorer.d.ts.map +0 -1
  197. package/dist/explorer.js +0 -15
  198. package/dist/fees.d.ts +0 -65
  199. package/dist/fees.d.ts.map +0 -1
  200. package/dist/fees.js +0 -165
  201. package/dist/gasless.d.ts +0 -123
  202. package/dist/gasless.d.ts.map +0 -1
  203. package/dist/gasless.js +0 -314
  204. package/dist/hooks/index.d.ts.map +0 -1
  205. package/dist/hooks/persistedToken.d.ts +0 -22
  206. package/dist/hooks/persistedToken.d.ts.map +0 -1
  207. package/dist/hooks/persistedToken.js +0 -65
  208. package/dist/hooks/prepareTrailsSendTransactionDestination.d.ts +0 -26
  209. package/dist/hooks/prepareTrailsSendTransactionDestination.d.ts.map +0 -1
  210. package/dist/hooks/prepareTrailsSendTransactionDestination.js +0 -33
  211. package/dist/hooks/useAmountUsd.d.ts +0 -12
  212. package/dist/hooks/useAmountUsd.d.ts.map +0 -1
  213. package/dist/hooks/useAmountUsd.js +0 -21
  214. package/dist/hooks/useBalanceVisible.d.ts +0 -15
  215. package/dist/hooks/useBalanceVisible.d.ts.map +0 -1
  216. package/dist/hooks/useBalanceVisible.js +0 -46
  217. package/dist/hooks/useBluvoTokenList.d.ts +0 -13
  218. package/dist/hooks/useBluvoTokenList.d.ts.map +0 -1
  219. package/dist/hooks/useBluvoTokenList.js +0 -57
  220. package/dist/hooks/useChainFilter.d.ts +0 -14
  221. package/dist/hooks/useChainFilter.d.ts.map +0 -1
  222. package/dist/hooks/useChainFilter.js +0 -24
  223. package/dist/hooks/useCheckout.d.ts +0 -80
  224. package/dist/hooks/useCheckout.d.ts.map +0 -1
  225. package/dist/hooks/useCheckout.js +0 -118
  226. package/dist/hooks/useClickTracking.d.ts +0 -12
  227. package/dist/hooks/useClickTracking.d.ts.map +0 -1
  228. package/dist/hooks/useClickTracking.js +0 -37
  229. package/dist/hooks/useCombinedHistory.d.ts +0 -50
  230. package/dist/hooks/useCombinedHistory.d.ts.map +0 -1
  231. package/dist/hooks/useCombinedHistory.js +0 -168
  232. package/dist/hooks/useCustomTokenSearch.d.ts +0 -28
  233. package/dist/hooks/useCustomTokenSearch.d.ts.map +0 -1
  234. package/dist/hooks/useCustomTokenSearch.js +0 -165
  235. package/dist/hooks/useDebounce.d.ts +0 -10
  236. package/dist/hooks/useDebounce.d.ts.map +0 -1
  237. package/dist/hooks/useDebounce.js +0 -15
  238. package/dist/hooks/useDebugScreens.d.ts +0 -17
  239. package/dist/hooks/useDebugScreens.d.ts.map +0 -1
  240. package/dist/hooks/useDebugScreens.js +0 -412
  241. package/dist/hooks/useDefaultDestinationToken.d.ts +0 -20
  242. package/dist/hooks/useDefaultDestinationToken.d.ts.map +0 -1
  243. package/dist/hooks/useDefaultDestinationToken.js +0 -60
  244. package/dist/hooks/useDefaultOriginToken.d.ts +0 -26
  245. package/dist/hooks/useDefaultOriginToken.d.ts.map +0 -1
  246. package/dist/hooks/useDefaultOriginToken.js +0 -120
  247. package/dist/hooks/useDepositMonitor.d.ts +0 -20
  248. package/dist/hooks/useDepositMonitor.d.ts.map +0 -1
  249. package/dist/hooks/useDepositMonitor.js +0 -54
  250. package/dist/hooks/useDestinationSelectedToken.d.ts +0 -38
  251. package/dist/hooks/useDestinationSelectedToken.d.ts.map +0 -1
  252. package/dist/hooks/useDestinationSelectedToken.js +0 -178
  253. package/dist/hooks/useDisplayCurrencyPreference.d.ts +0 -15
  254. package/dist/hooks/useDisplayCurrencyPreference.d.ts.map +0 -1
  255. package/dist/hooks/useDisplayCurrencyPreference.js +0 -57
  256. package/dist/hooks/useEarnPool.d.ts +0 -12
  257. package/dist/hooks/useEarnPool.d.ts.map +0 -1
  258. package/dist/hooks/useEarnPool.js +0 -21
  259. package/dist/hooks/useEffectiveFundBalance.d.ts +0 -28
  260. package/dist/hooks/useEffectiveFundBalance.d.ts.map +0 -1
  261. package/dist/hooks/useEffectiveFundBalance.js +0 -24
  262. package/dist/hooks/useExchangeFundingSelection.d.ts +0 -17
  263. package/dist/hooks/useExchangeFundingSelection.d.ts.map +0 -1
  264. package/dist/hooks/useExchangeFundingSelection.js +0 -25
  265. package/dist/hooks/useExecutingIntentsCount.d.ts +0 -15
  266. package/dist/hooks/useExecutingIntentsCount.d.ts.map +0 -1
  267. package/dist/hooks/useExternalFundingReceiptSync.d.ts +0 -11
  268. package/dist/hooks/useExternalFundingReceiptSync.d.ts.map +0 -1
  269. package/dist/hooks/useExternalFundingReceiptSync.js +0 -32
  270. package/dist/hooks/useFiatOnRampCurrencies.d.ts +0 -15
  271. package/dist/hooks/useFiatOnRampCurrencies.d.ts.map +0 -1
  272. package/dist/hooks/useFiatOnRampCurrencies.js +0 -14
  273. package/dist/hooks/useFiatSelectedCurrency.d.ts +0 -19
  274. package/dist/hooks/useFiatSelectedCurrency.d.ts.map +0 -1
  275. package/dist/hooks/useFiatSelectedCurrency.js +0 -55
  276. package/dist/hooks/useGetIntent.d.ts +0 -19
  277. package/dist/hooks/useGetIntent.d.ts.map +0 -1
  278. package/dist/hooks/useGetIntent.js +0 -26
  279. package/dist/hooks/useIntentReceiptBalances.d.ts +0 -16
  280. package/dist/hooks/useIntentReceiptBalances.d.ts.map +0 -1
  281. package/dist/hooks/useIntentReceiptBalances.js +0 -77
  282. package/dist/hooks/useIntentTransactionHistory.d.ts +0 -25
  283. package/dist/hooks/useIntentTransactionHistory.d.ts.map +0 -1
  284. package/dist/hooks/useIntentTransactionHistory.js +0 -357
  285. package/dist/hooks/useIsMobile.d.ts +0 -5
  286. package/dist/hooks/useIsMobile.d.ts.map +0 -1
  287. package/dist/hooks/useIsMobile.js +0 -21
  288. package/dist/hooks/useLocalePreference.d.ts +0 -21
  289. package/dist/hooks/useLocalePreference.d.ts.map +0 -1
  290. package/dist/hooks/useLocalePreference.js +0 -193
  291. package/dist/hooks/useMeldTransactionHistory.d.ts +0 -49
  292. package/dist/hooks/useMeldTransactionHistory.d.ts.map +0 -1
  293. package/dist/hooks/useMeldTransactionHistory.js +0 -71
  294. package/dist/hooks/useMeldTransactionStatus.d.ts +0 -61
  295. package/dist/hooks/useMeldTransactionStatus.d.ts.map +0 -1
  296. package/dist/hooks/useMeldTransactionStatus.js +0 -284
  297. package/dist/hooks/useOnRampCountryDefaults.d.ts +0 -18
  298. package/dist/hooks/useOnRampCountryDefaults.d.ts.map +0 -1
  299. package/dist/hooks/useOnRampCountryDefaults.js +0 -20
  300. package/dist/hooks/useOnRampPaymentMethods.d.ts +0 -15
  301. package/dist/hooks/useOnRampPaymentMethods.d.ts.map +0 -1
  302. package/dist/hooks/useOnRampPaymentMethods.js +0 -27
  303. package/dist/hooks/useOnRampProviderWidget.d.ts +0 -40
  304. package/dist/hooks/useOnRampProviderWidget.d.ts.map +0 -1
  305. package/dist/hooks/useOnRampProviderWidget.js +0 -70
  306. package/dist/hooks/useOnRampQuote.d.ts +0 -38
  307. package/dist/hooks/useOnRampQuote.d.ts.map +0 -1
  308. package/dist/hooks/useOnRampQuote.js +0 -159
  309. package/dist/hooks/useOnRampTransactionStatus.d.ts +0 -73
  310. package/dist/hooks/useOnRampTransactionStatus.d.ts.map +0 -1
  311. package/dist/hooks/useOriginSelectedToken.d.ts +0 -22
  312. package/dist/hooks/useOriginSelectedToken.d.ts.map +0 -1
  313. package/dist/hooks/useOriginSelectedToken.js +0 -127
  314. package/dist/hooks/usePayMessage.d.ts +0 -35
  315. package/dist/hooks/usePayMessage.d.ts.map +0 -1
  316. package/dist/hooks/usePayMessage.js +0 -333
  317. package/dist/hooks/usePriceImpactWarning.d.ts +0 -8
  318. package/dist/hooks/usePriceImpactWarning.d.ts.map +0 -1
  319. package/dist/hooks/usePriceImpactWarning.js +0 -9
  320. package/dist/hooks/useQuote.d.ts +0 -611
  321. package/dist/hooks/useQuote.d.ts.map +0 -1
  322. package/dist/hooks/useQuote.js +0 -590
  323. package/dist/hooks/useRecentChains.d.ts +0 -7
  324. package/dist/hooks/useRecentChains.d.ts.map +0 -1
  325. package/dist/hooks/useRecentChains.js +0 -52
  326. package/dist/hooks/useRecentTokens.d.ts +0 -7
  327. package/dist/hooks/useRecentTokens.d.ts.map +0 -1
  328. package/dist/hooks/useRecentTokens.js +0 -82
  329. package/dist/hooks/useRecipients.d.ts +0 -17
  330. package/dist/hooks/useRecipients.d.ts.map +0 -1
  331. package/dist/hooks/useRecipients.js +0 -75
  332. package/dist/hooks/useSelectedFeeOption.d.ts +0 -31
  333. package/dist/hooks/useSelectedFeeOption.d.ts.map +0 -1
  334. package/dist/hooks/useSelectedFeeOption.js +0 -113
  335. package/dist/hooks/useSelectedFundMethod.d.ts +0 -73
  336. package/dist/hooks/useSelectedFundMethod.d.ts.map +0 -1
  337. package/dist/hooks/useSelectedFundMethod.js +0 -51
  338. package/dist/hooks/useSelectedRecipient.d.ts +0 -12
  339. package/dist/hooks/useSelectedRecipient.d.ts.map +0 -1
  340. package/dist/hooks/useSelectedRecipient.js +0 -39
  341. package/dist/hooks/useSendForm.d.ts +0 -141
  342. package/dist/hooks/useSendForm.d.ts.map +0 -1
  343. package/dist/hooks/useSendForm.js +0 -595
  344. package/dist/hooks/useSwapAmount.d.ts +0 -13
  345. package/dist/hooks/useSwapAmount.d.ts.map +0 -1
  346. package/dist/hooks/useSwapAmount.js +0 -24
  347. package/dist/hooks/useSwapState.d.ts +0 -21
  348. package/dist/hooks/useSwapState.d.ts.map +0 -1
  349. package/dist/hooks/useSwapState.js +0 -44
  350. package/dist/hooks/useTargetAmount.d.ts +0 -6
  351. package/dist/hooks/useTargetAmount.d.ts.map +0 -1
  352. package/dist/hooks/useTargetAmount.js +0 -17
  353. package/dist/hooks/useTheme.d.ts +0 -14
  354. package/dist/hooks/useTheme.d.ts.map +0 -1
  355. package/dist/hooks/useTheme.js +0 -47
  356. package/dist/hooks/useTokenList.d.ts +0 -43
  357. package/dist/hooks/useTokenList.d.ts.map +0 -1
  358. package/dist/hooks/useTokenList.js +0 -456
  359. package/dist/hooks/useTrailsSendTransaction.d.ts +0 -139
  360. package/dist/hooks/useTrailsSendTransaction.d.ts.map +0 -1
  361. package/dist/hooks/useTrailsSendTransaction.js +0 -418
  362. package/dist/hooks/useViewManager.d.ts +0 -89
  363. package/dist/hooks/useViewManager.d.ts.map +0 -1
  364. package/dist/hooks/useViewManager.js +0 -274
  365. package/dist/hooks/useWalletConnectionContext.d.ts +0 -26
  366. package/dist/hooks/useWalletConnectionContext.d.ts.map +0 -1
  367. package/dist/hooks/useWalletConnectionContext.js +0 -53
  368. package/dist/hooks/useWidgetProps.d.ts +0 -13
  369. package/dist/hooks/useWidgetProps.d.ts.map +0 -1
  370. package/dist/hooks/useWidgetProps.js +0 -18
  371. package/dist/hydrate/builder.d.ts +0 -131
  372. package/dist/hydrate/builder.d.ts.map +0 -1
  373. package/dist/hydrate/builder.js +0 -210
  374. package/dist/hydrate/constants.d.ts +0 -13
  375. package/dist/hydrate/constants.d.ts.map +0 -1
  376. package/dist/hydrate/constants.js +0 -5
  377. package/dist/hydrate/encodeExecute.d.ts +0 -73
  378. package/dist/hydrate/encodeExecute.d.ts.map +0 -1
  379. package/dist/hydrate/encodeExecute.js +0 -60
  380. package/dist/hydrate/index.d.ts.map +0 -1
  381. package/dist/hydrate/multicall.d.ts +0 -69
  382. package/dist/hydrate/multicall.d.ts.map +0 -1
  383. package/dist/hydrate/multicall.js +0 -167
  384. package/dist/hydrate/payload.d.ts +0 -38
  385. package/dist/hydrate/payload.d.ts.map +0 -1
  386. package/dist/hydrate/payload.js +0 -26
  387. package/dist/hydrate/selectors.d.ts +0 -28
  388. package/dist/hydrate/selectors.d.ts.map +0 -1
  389. package/dist/hydrate/selectors.js +0 -326
  390. package/dist/hydrate/source.d.ts +0 -11
  391. package/dist/hydrate/source.d.ts.map +0 -1
  392. package/dist/hydrate/source.js +0 -19
  393. package/dist/hydrate/types.d.ts +0 -21
  394. package/dist/hydrate/types.d.ts.map +0 -1
  395. package/dist/hydrate/utils.d.ts +0 -8
  396. package/dist/hydrate/utils.d.ts.map +0 -1
  397. package/dist/hydrate/utils.js +0 -23
  398. package/dist/index.d.ts.map +0 -1
  399. package/dist/indexerClient.d.ts +0 -23
  400. package/dist/indexerClient.d.ts.map +0 -1
  401. package/dist/indexerClient.js +0 -40
  402. package/dist/intentConfigStore.d.ts +0 -8
  403. package/dist/intentConfigStore.d.ts.map +0 -1
  404. package/dist/intentConfigStore.js +0 -40
  405. package/dist/intentProtocolApi.d.ts +0 -11
  406. package/dist/intentProtocolApi.d.ts.map +0 -1
  407. package/dist/intentProtocolApi.js +0 -11
  408. package/dist/intentProtocolEncoding.d.ts +0 -30
  409. package/dist/intentProtocolEncoding.d.ts.map +0 -1
  410. package/dist/intentProtocolEncoding.js +0 -114
  411. package/dist/intentProtocolResolver.d.ts +0 -28
  412. package/dist/intentProtocolResolver.d.ts.map +0 -1
  413. package/dist/intentProtocolResolver.js +0 -34
  414. package/dist/intentReceiptMonitor.d.ts +0 -24
  415. package/dist/intentReceiptMonitor.d.ts.map +0 -1
  416. package/dist/intentReceiptMonitor.js +0 -30
  417. package/dist/intentReceiptPoller.d.ts +0 -69
  418. package/dist/intentReceiptPoller.d.ts.map +0 -1
  419. package/dist/intentReceiptPoller.js +0 -162
  420. package/dist/intentValidation.d.ts +0 -5
  421. package/dist/intentValidation.d.ts.map +0 -1
  422. package/dist/intentValidation.js +0 -19
  423. package/dist/intents.d.ts +0 -148
  424. package/dist/intents.d.ts.map +0 -1
  425. package/dist/intents.js +0 -391
  426. package/dist/keyMachineClient.d.ts +0 -9
  427. package/dist/keyMachineClient.d.ts.map +0 -1
  428. package/dist/keyMachineClient.js +0 -13
  429. package/dist/keymachine/index.d.ts +0 -34
  430. package/dist/keymachine/index.d.ts.map +0 -1
  431. package/dist/keymachine/index.js +0 -92
  432. package/dist/keymachine/key-machine.gen.d.ts +0 -461
  433. package/dist/keymachine/key-machine.gen.d.ts.map +0 -1
  434. package/dist/keymachine/key-machine.gen.js +0 -164
  435. package/dist/localeUtils.d.ts +0 -46
  436. package/dist/localeUtils.d.ts.map +0 -1
  437. package/dist/localeUtils.js +0 -60
  438. package/dist/logger/index.d.ts +0 -16
  439. package/dist/logger/index.d.ts.map +0 -1
  440. package/dist/logger/index.js +0 -57
  441. package/dist/logger/useSyncLoggerDebug.d.ts +0 -2
  442. package/dist/logger/useSyncLoggerDebug.d.ts.map +0 -1
  443. package/dist/logger/useSyncLoggerDebug.js +0 -9
  444. package/dist/logger.d.ts +0 -2
  445. package/dist/logger.d.ts.map +0 -1
  446. package/dist/meld/components/MeldCountriesList.d.ts +0 -9
  447. package/dist/meld/components/MeldCountriesList.d.ts.map +0 -1
  448. package/dist/meld/components/MeldCountriesList.js +0 -167
  449. package/dist/meld/components/MeldFundMethods.d.ts +0 -14
  450. package/dist/meld/components/MeldFundMethods.d.ts.map +0 -1
  451. package/dist/meld/components/MeldFundMethods.js +0 -163
  452. package/dist/meld/components/MeldProvidersList.d.ts +0 -11
  453. package/dist/meld/components/MeldProvidersList.d.ts.map +0 -1
  454. package/dist/meld/components/MeldProvidersList.js +0 -145
  455. package/dist/meld/components/MeldTokensList.d.ts +0 -12
  456. package/dist/meld/components/MeldTokensList.d.ts.map +0 -1
  457. package/dist/meld/components/MeldTokensList.js +0 -215
  458. package/dist/meld/components/SimpleHeader.d.ts +0 -8
  459. package/dist/meld/components/SimpleHeader.d.ts.map +0 -1
  460. package/dist/meld/components/SimpleHeader.js +0 -18
  461. package/dist/meld/utils/meld.d.ts +0 -41
  462. package/dist/meld/utils/meld.d.ts.map +0 -1
  463. package/dist/meld/utils/meld.js +0 -24
  464. package/dist/mutations.d.ts +0 -19
  465. package/dist/mutations.d.ts.map +0 -1
  466. package/dist/mutations.js +0 -91
  467. package/dist/offlineRecovery.d.ts +0 -24
  468. package/dist/offlineRecovery.d.ts.map +0 -1
  469. package/dist/offlineRecovery.js +0 -219
  470. package/dist/onramp/MeshConnectFlow.d.ts +0 -27
  471. package/dist/onramp/MeshConnectFlow.d.ts.map +0 -1
  472. package/dist/onramp/MeshConnectFlow.js +0 -41
  473. package/dist/onramp/MeshConnectIframe.d.ts +0 -22
  474. package/dist/onramp/MeshConnectIframe.d.ts.map +0 -1
  475. package/dist/onramp/MeshConnectIframe.js +0 -434
  476. package/dist/onramp/SendFromExchangeButton.d.ts +0 -16
  477. package/dist/onramp/SendFromExchangeButton.d.ts.map +0 -1
  478. package/dist/onramp/SendFromExchangeButton.js +0 -36
  479. package/dist/onramp/TrailsOnRampProvider.d.ts +0 -38
  480. package/dist/onramp/TrailsOnRampProvider.d.ts.map +0 -1
  481. package/dist/onramp/TrailsOnRampProvider.js +0 -25
  482. package/dist/onramp/bluvo/hooks/useBluvoFundingSelection.d.ts +0 -12
  483. package/dist/onramp/bluvo/hooks/useBluvoFundingSelection.d.ts.map +0 -1
  484. package/dist/onramp/bluvo/hooks/useBluvoFundingSelection.js +0 -18
  485. package/dist/onramp/index.d.ts +0 -13
  486. package/dist/onramp/index.d.ts.map +0 -1
  487. package/dist/onramp/mesh/components/MeshExchangeConfirmation.d.ts +0 -10
  488. package/dist/onramp/mesh/components/MeshExchangeConfirmation.d.ts.map +0 -1
  489. package/dist/onramp/mesh/components/MeshExchangeConfirmation.js +0 -62
  490. package/dist/onramp/mesh/components/MeshExchangeIcon.d.ts +0 -13
  491. package/dist/onramp/mesh/components/MeshExchangeIcon.d.ts.map +0 -1
  492. package/dist/onramp/mesh/components/MeshExchangeIcon.js +0 -54
  493. package/dist/onramp/mesh/components/MeshExchangeSelection.d.ts +0 -12
  494. package/dist/onramp/mesh/components/MeshExchangeSelection.d.ts.map +0 -1
  495. package/dist/onramp/mesh/components/MeshExchangeSelection.js +0 -135
  496. package/dist/onramp/mesh/components/MeshSessionOptions.d.ts +0 -15
  497. package/dist/onramp/mesh/components/MeshSessionOptions.d.ts.map +0 -1
  498. package/dist/onramp/mesh/components/MeshSessionOptions.js +0 -68
  499. package/dist/onramp/mesh/hooks/useMeshAccessTokens.d.ts +0 -9
  500. package/dist/onramp/mesh/hooks/useMeshAccessTokens.d.ts.map +0 -1
  501. package/dist/onramp/mesh/hooks/useMeshAccessTokens.js +0 -38
  502. package/dist/onramp/mesh/hooks/useMeshFundingSelection.d.ts +0 -11
  503. package/dist/onramp/mesh/hooks/useMeshFundingSelection.d.ts.map +0 -1
  504. package/dist/onramp/mesh/hooks/useMeshFundingSelection.js +0 -21
  505. package/dist/onramp/mesh/hooks/useMeshOnrampFlow.d.ts +0 -71
  506. package/dist/onramp/mesh/hooks/useMeshOnrampFlow.d.ts.map +0 -1
  507. package/dist/onramp/mesh/hooks/useMeshOnrampFlow.js +0 -168
  508. package/dist/onramp/mesh/hooks/useMeshOnrampSessionState.d.ts +0 -32
  509. package/dist/onramp/mesh/hooks/useMeshOnrampSessionState.d.ts.map +0 -1
  510. package/dist/onramp/mesh/hooks/useMeshOnrampSessionState.js +0 -28
  511. package/dist/onramp/mesh/hooks/useMeshSelectedTokenBalance.d.ts +0 -19
  512. package/dist/onramp/mesh/hooks/useMeshSelectedTokenBalance.d.ts.map +0 -1
  513. package/dist/onramp/mesh/hooks/useMeshSelectedTokenBalance.js +0 -57
  514. package/dist/onramp/mesh/hooks/useMeshSessionAccountBalance.d.ts +0 -15
  515. package/dist/onramp/mesh/hooks/useMeshSessionAccountBalance.d.ts.map +0 -1
  516. package/dist/onramp/mesh/hooks/useMeshSessionAccountBalance.js +0 -45
  517. package/dist/onramp/mesh/hooks/useMeshSessionStorage.d.ts +0 -7
  518. package/dist/onramp/mesh/hooks/useMeshSessionStorage.d.ts.map +0 -1
  519. package/dist/onramp/mesh/hooks/useMeshSessionStorage.js +0 -20
  520. package/dist/onramp/meshSessionStorage.d.ts +0 -13
  521. package/dist/onramp/meshSessionStorage.d.ts.map +0 -1
  522. package/dist/onramp/meshSessionStorage.js +0 -165
  523. package/dist/onramp/meshconnect.d.ts +0 -32
  524. package/dist/onramp/meshconnect.d.ts.map +0 -1
  525. package/dist/onramp/meshconnect.js +0 -124
  526. package/dist/onramp/trailsOnramp.d.ts +0 -32
  527. package/dist/onramp/trailsOnramp.d.ts.map +0 -1
  528. package/dist/onramp/trailsOnramp.js +0 -64
  529. package/dist/onramp-client/index.d.ts +0 -13
  530. package/dist/onramp-client/index.d.ts.map +0 -1
  531. package/dist/onramp-client/index.js +0 -19
  532. package/dist/onrampClient.d.ts +0 -10
  533. package/dist/onrampClient.d.ts.map +0 -1
  534. package/dist/onrampClient.js +0 -31
  535. package/dist/package.js +0 -123
  536. package/dist/placeholder.d.ts +0 -142
  537. package/dist/placeholder.d.ts.map +0 -1
  538. package/dist/placeholder.js +0 -95
  539. package/dist/poolUtils.d.ts +0 -16
  540. package/dist/poolUtils.d.ts.map +0 -1
  541. package/dist/poolUtils.js +0 -87
  542. package/dist/pools.d.ts +0 -33
  543. package/dist/pools.d.ts.map +0 -1
  544. package/dist/pools.js +0 -77
  545. package/dist/prepareSend.d.ts +0 -12
  546. package/dist/prepareSend.d.ts.map +0 -1
  547. package/dist/prepareSend.js +0 -207
  548. package/dist/query/QueryProvider.d.ts +0 -9
  549. package/dist/query/QueryProvider.d.ts.map +0 -1
  550. package/dist/query/QueryProvider.js +0 -13
  551. package/dist/query/balance.fetchers.d.ts +0 -116
  552. package/dist/query/balance.fetchers.d.ts.map +0 -1
  553. package/dist/query/balance.fetchers.js +0 -289
  554. package/dist/query/balance.hooks.d.ts +0 -80
  555. package/dist/query/balance.hooks.d.ts.map +0 -1
  556. package/dist/query/balance.hooks.js +0 -123
  557. package/dist/query/balance.queries.d.ts +0 -93
  558. package/dist/query/balance.queries.d.ts.map +0 -1
  559. package/dist/query/balance.queries.js +0 -142
  560. package/dist/query/chains.hooks.d.ts +0 -5
  561. package/dist/query/chains.hooks.d.ts.map +0 -1
  562. package/dist/query/chains.hooks.js +0 -40
  563. package/dist/query/chains.queries.d.ts +0 -16
  564. package/dist/query/chains.queries.d.ts.map +0 -1
  565. package/dist/query/chains.queries.js +0 -17
  566. package/dist/query/client.d.ts +0 -16
  567. package/dist/query/client.d.ts.map +0 -1
  568. package/dist/query/client.js +0 -15
  569. package/dist/query/fiat.fetchers.d.ts +0 -11
  570. package/dist/query/fiat.fetchers.d.ts.map +0 -1
  571. package/dist/query/fiat.fetchers.js +0 -10
  572. package/dist/query/fiat.hooks.d.ts +0 -18
  573. package/dist/query/fiat.hooks.d.ts.map +0 -1
  574. package/dist/query/fiat.hooks.js +0 -20
  575. package/dist/query/fiat.queries.d.ts +0 -24
  576. package/dist/query/fiat.queries.d.ts.map +0 -1
  577. package/dist/query/fiat.queries.js +0 -39
  578. package/dist/query/geo.fetchers.d.ts +0 -5
  579. package/dist/query/geo.fetchers.d.ts.map +0 -1
  580. package/dist/query/geo.fetchers.js +0 -61
  581. package/dist/query/geo.hooks.d.ts +0 -5
  582. package/dist/query/geo.hooks.d.ts.map +0 -1
  583. package/dist/query/geo.hooks.js +0 -17
  584. package/dist/query/geo.queries.d.ts +0 -22
  585. package/dist/query/geo.queries.d.ts.map +0 -1
  586. package/dist/query/geo.queries.js +0 -33
  587. package/dist/query/helpers.d.ts +0 -18
  588. package/dist/query/helpers.d.ts.map +0 -1
  589. package/dist/query/helpers.js +0 -31
  590. package/dist/query/intentProtocol.queries.d.ts +0 -32
  591. package/dist/query/intentProtocol.queries.d.ts.map +0 -1
  592. package/dist/query/intentProtocol.queries.js +0 -41
  593. package/dist/query/meld.fetchers.d.ts +0 -19
  594. package/dist/query/meld.fetchers.d.ts.map +0 -1
  595. package/dist/query/meld.fetchers.js +0 -41
  596. package/dist/query/meld.hooks.d.ts +0 -4
  597. package/dist/query/meld.hooks.d.ts.map +0 -1
  598. package/dist/query/meld.hooks.js +0 -15
  599. package/dist/query/meld.queries.d.ts +0 -61
  600. package/dist/query/meld.queries.d.ts.map +0 -1
  601. package/dist/query/meld.queries.js +0 -97
  602. package/dist/query/persister.d.ts +0 -9
  603. package/dist/query/persister.d.ts.map +0 -1
  604. package/dist/query/persister.js +0 -13
  605. package/dist/query/price.fetchers.d.ts +0 -15
  606. package/dist/query/price.fetchers.d.ts.map +0 -1
  607. package/dist/query/price.fetchers.js +0 -26
  608. package/dist/query/price.hooks.d.ts +0 -352
  609. package/dist/query/price.hooks.d.ts.map +0 -1
  610. package/dist/query/price.hooks.js +0 -35
  611. package/dist/query/price.queries.d.ts +0 -34
  612. package/dist/query/price.queries.d.ts.map +0 -1
  613. package/dist/query/price.queries.js +0 -139
  614. package/dist/query/serialization.d.ts +0 -3
  615. package/dist/query/serialization.d.ts.map +0 -1
  616. package/dist/query/serialization.js +0 -17
  617. package/dist/query/token.fetchers.d.ts +0 -13
  618. package/dist/query/token.fetchers.d.ts.map +0 -1
  619. package/dist/query/token.fetchers.js +0 -6
  620. package/dist/query/token.hooks.d.ts +0 -41
  621. package/dist/query/token.hooks.d.ts.map +0 -1
  622. package/dist/query/token.hooks.js +0 -68
  623. package/dist/query/token.queries.d.ts +0 -67
  624. package/dist/query/token.queries.d.ts.map +0 -1
  625. package/dist/query/token.queries.js +0 -144
  626. package/dist/queryParams.d.ts +0 -9
  627. package/dist/queryParams.d.ts.map +0 -1
  628. package/dist/queryParamsCore.d.ts +0 -2
  629. package/dist/queryParamsCore.d.ts.map +0 -1
  630. package/dist/queryParamsCore.js +0 -10
  631. package/dist/quoteError.d.ts +0 -22
  632. package/dist/quoteError.d.ts.map +0 -1
  633. package/dist/quoteError.js +0 -9
  634. package/dist/recover.d.ts +0 -304
  635. package/dist/recover.d.ts.map +0 -1
  636. package/dist/recover.js +0 -703
  637. package/dist/smartContractWallet.d.ts +0 -8
  638. package/dist/smartContractWallet.d.ts.map +0 -1
  639. package/dist/smartContractWallet.js +0 -11
  640. package/dist/theme.d.ts +0 -3
  641. package/dist/theme.d.ts.map +0 -1
  642. package/dist/toast.d.ts +0 -9
  643. package/dist/toast.d.ts.map +0 -1
  644. package/dist/toast.js +0 -31
  645. package/dist/tokenRegistry.d.ts +0 -50
  646. package/dist/tokenRegistry.d.ts.map +0 -1
  647. package/dist/tokenRegistry.js +0 -589
  648. package/dist/tokenTypes.d.ts +0 -29
  649. package/dist/tokenTypes.d.ts.map +0 -1
  650. package/dist/tokens.d.ts +0 -62
  651. package/dist/tokens.d.ts.map +0 -1
  652. package/dist/tokens.js +0 -370
  653. package/dist/trailsClient.d.ts +0 -11
  654. package/dist/trailsClient.d.ts.map +0 -1
  655. package/dist/trailsClient.js +0 -29
  656. package/dist/transactionIntent/constants.d.ts +0 -8
  657. package/dist/transactionIntent/constants.d.ts.map +0 -1
  658. package/dist/transactionIntent/constants.js +0 -11
  659. package/dist/transactionIntent/deposits/depositOrchestrator.d.ts +0 -55
  660. package/dist/transactionIntent/deposits/depositOrchestrator.d.ts.map +0 -1
  661. package/dist/transactionIntent/deposits/depositOrchestrator.js +0 -88
  662. package/dist/transactionIntent/deposits/gaslessDeposit.d.ts +0 -31
  663. package/dist/transactionIntent/deposits/gaslessDeposit.d.ts.map +0 -1
  664. package/dist/transactionIntent/deposits/gaslessDeposit.js +0 -218
  665. package/dist/transactionIntent/deposits/index.d.ts +0 -4
  666. package/dist/transactionIntent/deposits/index.d.ts.map +0 -1
  667. package/dist/transactionIntent/deposits/standardDeposit.d.ts +0 -50
  668. package/dist/transactionIntent/deposits/standardDeposit.d.ts.map +0 -1
  669. package/dist/transactionIntent/deposits/standardDeposit.js +0 -131
  670. package/dist/transactionIntent/execution/index.d.ts +0 -2
  671. package/dist/transactionIntent/execution/index.d.ts.map +0 -1
  672. package/dist/transactionIntent/execution/transactionState.d.ts +0 -5
  673. package/dist/transactionIntent/execution/transactionState.d.ts.map +0 -1
  674. package/dist/transactionIntent/execution/transactionState.js +0 -21
  675. package/dist/transactionIntent/handlers/index.d.ts +0 -2
  676. package/dist/transactionIntent/handlers/index.d.ts.map +0 -1
  677. package/dist/transactionIntent/handlers/intentHandler.d.ts +0 -71
  678. package/dist/transactionIntent/handlers/intentHandler.d.ts.map +0 -1
  679. package/dist/transactionIntent/handlers/intentHandler.js +0 -533
  680. package/dist/transactionIntent/helpers/index.d.ts +0 -2
  681. package/dist/transactionIntent/helpers/index.d.ts.map +0 -1
  682. package/dist/transactionIntent/helpers/transactionStateHelpers.d.ts +0 -68
  683. package/dist/transactionIntent/helpers/transactionStateHelpers.d.ts.map +0 -1
  684. package/dist/transactionIntent/helpers/transactionStateHelpers.js +0 -124
  685. package/dist/transactionIntent/index.d.ts +0 -10
  686. package/dist/transactionIntent/index.d.ts.map +0 -1
  687. package/dist/transactionIntent/quote/feeExtractors.d.ts +0 -13
  688. package/dist/transactionIntent/quote/feeExtractors.d.ts.map +0 -1
  689. package/dist/transactionIntent/quote/feeExtractors.js +0 -52
  690. package/dist/transactionIntent/quote/index.d.ts +0 -4
  691. package/dist/transactionIntent/quote/index.d.ts.map +0 -1
  692. package/dist/transactionIntent/quote/normalizeQuote.d.ts +0 -44
  693. package/dist/transactionIntent/quote/normalizeQuote.d.ts.map +0 -1
  694. package/dist/transactionIntent/quote/normalizeQuote.js +0 -214
  695. package/dist/transactionIntent/quote/quoteHelpers.d.ts +0 -6
  696. package/dist/transactionIntent/quote/quoteHelpers.d.ts.map +0 -1
  697. package/dist/transactionIntent/quote/quoteHelpers.js +0 -47
  698. package/dist/transactionIntent/types.d.ts +0 -181
  699. package/dist/transactionIntent/types.d.ts.map +0 -1
  700. package/dist/transactionIntent/types.js +0 -38
  701. package/dist/transactionIntent/utils/balanceChecker.d.ts +0 -20
  702. package/dist/transactionIntent/utils/balanceChecker.d.ts.map +0 -1
  703. package/dist/transactionIntent/utils/balanceChecker.js +0 -55
  704. package/dist/transactionIntent/utils/index.d.ts +0 -3
  705. package/dist/transactionIntent/utils/index.d.ts.map +0 -1
  706. package/dist/transactionIntent/utils/resilientDepositTracker.d.ts +0 -25
  707. package/dist/transactionIntent/utils/resilientDepositTracker.d.ts.map +0 -1
  708. package/dist/transactionIntent/utils/resilientDepositTracker.js +0 -62
  709. package/dist/transactionIntent/utils/testnetHelpers.d.ts +0 -2
  710. package/dist/transactionIntent/utils/testnetHelpers.d.ts.map +0 -1
  711. package/dist/transactionIntent/validators.d.ts +0 -4
  712. package/dist/transactionIntent/validators.d.ts.map +0 -1
  713. package/dist/transactionIntent/validators.js +0 -11
  714. package/dist/transactions.d.ts +0 -176
  715. package/dist/transactions.d.ts.map +0 -1
  716. package/dist/transactions.js +0 -115
  717. package/dist/umd/trails.min.js +0 -1251
  718. package/dist/utils/address.d.ts +0 -28
  719. package/dist/utils/address.d.ts.map +0 -1
  720. package/dist/utils/address.js +0 -30
  721. package/dist/utils/fiat.d.ts +0 -8
  722. package/dist/utils/fiat.d.ts.map +0 -1
  723. package/dist/utils/fiat.js +0 -30
  724. package/dist/utils/format.d.ts +0 -74
  725. package/dist/utils/format.d.ts.map +0 -1
  726. package/dist/utils/format.js +0 -274
  727. package/dist/utils/localStorageGc.d.ts +0 -22
  728. package/dist/utils/localStorageGc.d.ts.map +0 -1
  729. package/dist/utils/localStorageGc.js +0 -53
  730. package/dist/utils/passthrough.d.ts +0 -46
  731. package/dist/utils/passthrough.d.ts.map +0 -1
  732. package/dist/utils/passthrough.js +0 -20
  733. package/dist/utils/time.d.ts +0 -27
  734. package/dist/utils/time.d.ts.map +0 -1
  735. package/dist/utils/time.js +0 -68
  736. package/dist/utils/tokenResolution.d.ts +0 -19
  737. package/dist/utils/tokenResolution.d.ts.map +0 -1
  738. package/dist/utils/tokenResolution.js +0 -53
  739. package/dist/utils/validation.d.ts +0 -53
  740. package/dist/utils/validation.d.ts.map +0 -1
  741. package/dist/utils/validation.js +0 -80
  742. package/dist/utils.d.ts +0 -34
  743. package/dist/utils.d.ts.map +0 -1
  744. package/dist/utils.js +0 -58
  745. package/dist/version.d.ts +0 -3
  746. package/dist/version.d.ts.map +0 -1
  747. package/dist/version.js +0 -9
  748. package/dist/widget/assets/components/Aave.d.ts +0 -8
  749. package/dist/widget/assets/components/Aave.d.ts.map +0 -1
  750. package/dist/widget/assets/components/Aave.js +0 -29
  751. package/dist/widget/assets/components/ExchangeIconBlack.d.ts +0 -8
  752. package/dist/widget/assets/components/ExchangeIconBlack.d.ts.map +0 -1
  753. package/dist/widget/assets/components/FundMethodCardBrands.d.ts +0 -8
  754. package/dist/widget/assets/components/FundMethodCardBrands.d.ts.map +0 -1
  755. package/dist/widget/assets/components/FundMethodCardBrands.js +0 -49
  756. package/dist/widget/assets/components/FundMethodExchangeBrands.d.ts +0 -8
  757. package/dist/widget/assets/components/FundMethodExchangeBrands.d.ts.map +0 -1
  758. package/dist/widget/assets/components/FundMethodExchangeBrands.js +0 -37
  759. package/dist/widget/assets/components/MetaMaskIconFox.d.ts +0 -8
  760. package/dist/widget/assets/components/MetaMaskIconFox.d.ts.map +0 -1
  761. package/dist/widget/assets/components/MetaMaskIconFoxWithMargins.d.ts +0 -8
  762. package/dist/widget/assets/components/MetaMaskIconFoxWithMargins.d.ts.map +0 -1
  763. package/dist/widget/assets/components/MetaMaskLogoBlack.d.ts +0 -8
  764. package/dist/widget/assets/components/MetaMaskLogoBlack.d.ts.map +0 -1
  765. package/dist/widget/assets/components/MetaMaskLogoWhite.d.ts +0 -8
  766. package/dist/widget/assets/components/MetaMaskLogoWhite.d.ts.map +0 -1
  767. package/dist/widget/assets/components/Morpho.d.ts +0 -8
  768. package/dist/widget/assets/components/Morpho.d.ts.map +0 -1
  769. package/dist/widget/assets/components/Morpho.js +0 -51
  770. package/dist/widget/assets/components/TrailsBlack.d.ts +0 -8
  771. package/dist/widget/assets/components/TrailsBlack.d.ts.map +0 -1
  772. package/dist/widget/assets/components/TrailsBlack.js +0 -25
  773. package/dist/widget/assets/components/TrailsWhite.d.ts +0 -8
  774. package/dist/widget/assets/components/TrailsWhite.d.ts.map +0 -1
  775. package/dist/widget/assets/components/TrailsWhite.js +0 -25
  776. package/dist/widget/assets/components/WalletChangeBlack.d.ts +0 -8
  777. package/dist/widget/assets/components/WalletChangeBlack.d.ts.map +0 -1
  778. package/dist/widget/assets/components/WalletConnectLogo.d.ts +0 -8
  779. package/dist/widget/assets/components/WalletConnectLogo.d.ts.map +0 -1
  780. package/dist/widget/assets/components/WalletConnectLogoBlack.d.ts +0 -8
  781. package/dist/widget/assets/components/WalletConnectLogoBlack.d.ts.map +0 -1
  782. package/dist/widget/assets/components/WalletConnectLogoBlue.d.ts +0 -8
  783. package/dist/widget/assets/components/WalletConnectLogoBlue.d.ts.map +0 -1
  784. package/dist/widget/assets/components/WalletConnectLogoWhite.d.ts +0 -8
  785. package/dist/widget/assets/components/WalletConnectLogoWhite.d.ts.map +0 -1
  786. package/dist/widget/assets/components/index.d.ts +0 -17
  787. package/dist/widget/assets/components/index.d.ts.map +0 -1
  788. package/dist/widget/bluvo/bluvo-lib/BluvoCache.d.ts +0 -54
  789. package/dist/widget/bluvo/bluvo-lib/BluvoCache.d.ts.map +0 -1
  790. package/dist/widget/bluvo/bluvo-lib/BluvoCache.js +0 -68
  791. package/dist/widget/bluvo/bluvo-lib/BluvoFlowClient.d.ts +0 -386
  792. package/dist/widget/bluvo/bluvo-lib/BluvoFlowClient.d.ts.map +0 -1
  793. package/dist/widget/bluvo/bluvo-lib/BluvoFlowClient.js +0 -872
  794. package/dist/widget/bluvo/bluvo-lib/BluvoWebClient.d.ts +0 -192
  795. package/dist/widget/bluvo/bluvo-lib/BluvoWebClient.d.ts.map +0 -1
  796. package/dist/widget/bluvo/bluvo-lib/BluvoWebClient.js +0 -294
  797. package/dist/widget/bluvo/bluvo-lib/WebSocketClient.d.ts +0 -51
  798. package/dist/widget/bluvo/bluvo-lib/WebSocketClient.d.ts.map +0 -1
  799. package/dist/widget/bluvo/bluvo-lib/WebSocketClient.js +0 -72
  800. package/dist/widget/bluvo/bluvo-lib/WebsocketListener.d.ts +0 -19
  801. package/dist/widget/bluvo/bluvo-lib/WebsocketListener.d.ts.map +0 -1
  802. package/dist/widget/bluvo/bluvo-lib/WebsocketListener.js +0 -62
  803. package/dist/widget/bluvo/bluvo-lib/WorkflowTypes.d.ts +0 -44
  804. package/dist/widget/bluvo/bluvo-lib/WorkflowTypes.d.ts.map +0 -1
  805. package/dist/widget/bluvo/bluvo-lib/WorkflowTypes.js +0 -6
  806. package/dist/widget/bluvo/bluvo-lib/api.types.d.ts +0 -49
  807. package/dist/widget/bluvo/bluvo-lib/api.types.d.ts.map +0 -1
  808. package/dist/widget/bluvo/bluvo-lib/balanceTransform.d.ts +0 -84
  809. package/dist/widget/bluvo/bluvo-lib/balanceTransform.d.ts.map +0 -1
  810. package/dist/widget/bluvo/bluvo-lib/balanceTransform.js +0 -26
  811. package/dist/widget/bluvo/bluvo-lib/createMachine.d.ts +0 -3
  812. package/dist/widget/bluvo/bluvo-lib/createMachine.d.ts.map +0 -1
  813. package/dist/widget/bluvo/bluvo-lib/createMachine.js +0 -38
  814. package/dist/widget/bluvo/bluvo-lib/error-codes.d.ts +0 -156
  815. package/dist/widget/bluvo/bluvo-lib/error-codes.d.ts.map +0 -1
  816. package/dist/widget/bluvo/bluvo-lib/error-codes.js +0 -115
  817. package/dist/widget/bluvo/bluvo-lib/flow.types.d.ts +0 -356
  818. package/dist/widget/bluvo/bluvo-lib/flow.types.d.ts.map +0 -1
  819. package/dist/widget/bluvo/bluvo-lib/flowMachine.d.ts +0 -4
  820. package/dist/widget/bluvo/bluvo-lib/flowMachine.d.ts.map +0 -1
  821. package/dist/widget/bluvo/bluvo-lib/flowMachine.js +0 -45
  822. package/dist/widget/bluvo/bluvo-lib/flowMachine.types.d.ts +0 -20
  823. package/dist/widget/bluvo/bluvo-lib/flowMachine.types.d.ts.map +0 -1
  824. package/dist/widget/bluvo/bluvo-lib/flowStateHandlers.d.ts +0 -39
  825. package/dist/widget/bluvo/bluvo-lib/flowStateHandlers.d.ts.map +0 -1
  826. package/dist/widget/bluvo/bluvo-lib/flowStateHandlers.js +0 -395
  827. package/dist/widget/bluvo/bluvo-lib/index.d.ts +0 -5
  828. package/dist/widget/bluvo/bluvo-lib/index.d.ts.map +0 -1
  829. package/dist/widget/bluvo/bluvo-lib/machine.types.d.ts +0 -15
  830. package/dist/widget/bluvo/bluvo-lib/machine.types.d.ts.map +0 -1
  831. package/dist/widget/bluvo/bluvo-lib/stateHelpers.d.ts +0 -23
  832. package/dist/widget/bluvo/bluvo-lib/stateHelpers.d.ts.map +0 -1
  833. package/dist/widget/bluvo/bluvo-lib/stateHelpers.js +0 -24
  834. package/dist/widget/bluvo/bluvo-lib/useBluvoFlow.d.ts +0 -325
  835. package/dist/widget/bluvo/bluvo-lib/useBluvoFlow.d.ts.map +0 -1
  836. package/dist/widget/bluvo/bluvo-lib/useBluvoFlow.js +0 -152
  837. package/dist/widget/bluvo/bluvo-lib/useFlowMachine.d.ts +0 -11
  838. package/dist/widget/bluvo/bluvo-lib/useFlowMachine.d.ts.map +0 -1
  839. package/dist/widget/bluvo/bluvo-lib/useFlowMachine.js +0 -25
  840. package/dist/widget/bluvo/bluvo-lib/useWithdrawMachine.d.ts +0 -17
  841. package/dist/widget/bluvo/bluvo-lib/useWithdrawMachine.d.ts.map +0 -1
  842. package/dist/widget/bluvo/bluvo-lib/withdrawal.types.d.ts +0 -46
  843. package/dist/widget/bluvo/bluvo-lib/withdrawal.types.d.ts.map +0 -1
  844. package/dist/widget/bluvo/bluvo-lib/withdrawalErrorHandler.d.ts +0 -29
  845. package/dist/widget/bluvo/bluvo-lib/withdrawalErrorHandler.d.ts.map +0 -1
  846. package/dist/widget/bluvo/bluvo-lib/withdrawalErrorHandler.js +0 -95
  847. package/dist/widget/bluvo/bluvo-lib/withdrawalMachine.d.ts +0 -3
  848. package/dist/widget/bluvo/bluvo-lib/withdrawalMachine.d.ts.map +0 -1
  849. package/dist/widget/bluvo/bluvo-lib/withdrawalMachine.js +0 -137
  850. package/dist/widget/bluvo/index.d.ts +0 -2
  851. package/dist/widget/bluvo/index.d.ts.map +0 -1
  852. package/dist/widget/components/AccountActionsDropdown.d.ts +0 -4
  853. package/dist/widget/components/AccountActionsDropdown.d.ts.map +0 -1
  854. package/dist/widget/components/AccountActionsDropdown.js +0 -23
  855. package/dist/widget/components/AccountIntentTransactionHistory.d.ts +0 -9
  856. package/dist/widget/components/AccountIntentTransactionHistory.d.ts.map +0 -1
  857. package/dist/widget/components/AccountIntentTransactionHistory.js +0 -426
  858. package/dist/widget/components/AccountIntentTransactionHistoryButton.d.ts +0 -4
  859. package/dist/widget/components/AccountIntentTransactionHistoryButton.d.ts.map +0 -1
  860. package/dist/widget/components/AccountIntentTransactionHistoryButton.js +0 -23
  861. package/dist/widget/components/AccountSettings.d.ts +0 -7
  862. package/dist/widget/components/AccountSettings.d.ts.map +0 -1
  863. package/dist/widget/components/AccountSettings.js +0 -106
  864. package/dist/widget/components/AddressOrEnsName.d.ts +0 -13
  865. package/dist/widget/components/AddressOrEnsName.d.ts.map +0 -1
  866. package/dist/widget/components/AddressOrEnsName.js +0 -13
  867. package/dist/widget/components/AddressWalletIcon.d.ts +0 -8
  868. package/dist/widget/components/AddressWalletIcon.d.ts.map +0 -1
  869. package/dist/widget/components/AddressWalletIcon.js +0 -32
  870. package/dist/widget/components/AllChainsIcon.d.ts +0 -9
  871. package/dist/widget/components/AllChainsIcon.d.ts.map +0 -1
  872. package/dist/widget/components/AllChainsIcon.js +0 -98
  873. package/dist/widget/components/BluvoExchangeSelection.d.ts +0 -12
  874. package/dist/widget/components/BluvoExchangeSelection.d.ts.map +0 -1
  875. package/dist/widget/components/BluvoExchangeSelection.js +0 -131
  876. package/dist/widget/components/BluvoExchangeSelection.lazy.d.ts +0 -2
  877. package/dist/widget/components/BluvoExchangeSelection.lazy.d.ts.map +0 -1
  878. package/dist/widget/components/BluvoExchangeSelection.lazy.js +0 -4
  879. package/dist/widget/components/BluvoOnrampFlow.d.ts +0 -20
  880. package/dist/widget/components/BluvoOnrampFlow.d.ts.map +0 -1
  881. package/dist/widget/components/BluvoOnrampFlow.js +0 -1472
  882. package/dist/widget/components/BluvoOnrampFlow.lazy.d.ts +0 -2
  883. package/dist/widget/components/BluvoOnrampFlow.lazy.d.ts.map +0 -1
  884. package/dist/widget/components/BluvoOnrampFlow.lazy.js +0 -4
  885. package/dist/widget/components/ChainFilterDropdown.d.ts +0 -17
  886. package/dist/widget/components/ChainFilterDropdown.d.ts.map +0 -1
  887. package/dist/widget/components/ChainFilterDropdown.js +0 -124
  888. package/dist/widget/components/ChainImage.d.ts +0 -8
  889. package/dist/widget/components/ChainImage.d.ts.map +0 -1
  890. package/dist/widget/components/ChainImage.js +0 -24
  891. package/dist/widget/components/ChainList.d.ts +0 -9
  892. package/dist/widget/components/ChainList.d.ts.map +0 -1
  893. package/dist/widget/components/ChainList.js +0 -177
  894. package/dist/widget/components/ClassicSwap.d.ts +0 -10
  895. package/dist/widget/components/ClassicSwap.d.ts.map +0 -1
  896. package/dist/widget/components/ClassicSwap.js +0 -786
  897. package/dist/widget/components/ConfigDisplay.d.ts +0 -7
  898. package/dist/widget/components/ConfigDisplay.d.ts.map +0 -1
  899. package/dist/widget/components/ConfigDisplay.js +0 -122
  900. package/dist/widget/components/ConnectWallet.d.ts +0 -12
  901. package/dist/widget/components/ConnectWallet.d.ts.map +0 -1
  902. package/dist/widget/components/ConnectWallet.js +0 -215
  903. package/dist/widget/components/ConnectedWallets.d.ts +0 -19
  904. package/dist/widget/components/ConnectedWallets.d.ts.map +0 -1
  905. package/dist/widget/components/ConnectedWallets.js +0 -149
  906. package/dist/widget/components/CopyButton.d.ts +0 -18
  907. package/dist/widget/components/CopyButton.d.ts.map +0 -1
  908. package/dist/widget/components/CopyButton.js +0 -51
  909. package/dist/widget/components/CountryFilterDropdown.d.ts +0 -15
  910. package/dist/widget/components/CountryFilterDropdown.d.ts.map +0 -1
  911. package/dist/widget/components/CountryFilterDropdown.js +0 -93
  912. package/dist/widget/components/DebugMenu.d.ts +0 -7
  913. package/dist/widget/components/DebugMenu.d.ts.map +0 -1
  914. package/dist/widget/components/DebugMenu.js +0 -33
  915. package/dist/widget/components/DebugScreensList.d.ts +0 -7
  916. package/dist/widget/components/DebugScreensList.d.ts.map +0 -1
  917. package/dist/widget/components/DebugScreensList.js +0 -56
  918. package/dist/widget/components/DebugToast.d.ts +0 -3
  919. package/dist/widget/components/DebugToast.d.ts.map +0 -1
  920. package/dist/widget/components/DebugToast.js +0 -46
  921. package/dist/widget/components/DepositTracker.d.ts +0 -13
  922. package/dist/widget/components/DepositTracker.d.ts.map +0 -1
  923. package/dist/widget/components/DepositTracker.js +0 -194
  924. package/dist/widget/components/DirectTransfer.d.ts +0 -15
  925. package/dist/widget/components/DirectTransfer.d.ts.map +0 -1
  926. package/dist/widget/components/DirectTransfer.js +0 -218
  927. package/dist/widget/components/Disconnect.d.ts +0 -8
  928. package/dist/widget/components/Disconnect.d.ts.map +0 -1
  929. package/dist/widget/components/Disconnect.js +0 -37
  930. package/dist/widget/components/DynamicInputStyles.d.ts +0 -22
  931. package/dist/widget/components/DynamicInputStyles.d.ts.map +0 -1
  932. package/dist/widget/components/DynamicInputStyles.js +0 -27
  933. package/dist/widget/components/DynamicSizeInputField.d.ts +0 -17
  934. package/dist/widget/components/DynamicSizeInputField.d.ts.map +0 -1
  935. package/dist/widget/components/DynamicSizeInputField.js +0 -125
  936. package/dist/widget/components/ENSAvatar.d.ts +0 -12
  937. package/dist/widget/components/ENSAvatar.d.ts.map +0 -1
  938. package/dist/widget/components/ENSAvatar.js +0 -22
  939. package/dist/widget/components/Earn.d.ts +0 -33
  940. package/dist/widget/components/Earn.d.ts.map +0 -1
  941. package/dist/widget/components/Earn.js +0 -79
  942. package/dist/widget/components/EarnMarkets.d.ts +0 -9
  943. package/dist/widget/components/EarnMarkets.d.ts.map +0 -1
  944. package/dist/widget/components/EarnMarkets.js +0 -313
  945. package/dist/widget/components/EarnPools.d.ts +0 -8
  946. package/dist/widget/components/EarnPools.d.ts.map +0 -1
  947. package/dist/widget/components/EarnPools.js +0 -256
  948. package/dist/widget/components/EarnPoolsFilters.d.ts +0 -18
  949. package/dist/widget/components/EarnPoolsFilters.d.ts.map +0 -1
  950. package/dist/widget/components/EarnPoolsFilters.js +0 -106
  951. package/dist/widget/components/EarnWithdraw.d.ts +0 -21
  952. package/dist/widget/components/EarnWithdraw.d.ts.map +0 -1
  953. package/dist/widget/components/EarnWithdraw.js +0 -477
  954. package/dist/widget/components/ErrorAnimationIcon.d.ts +0 -2
  955. package/dist/widget/components/ErrorAnimationIcon.d.ts.map +0 -1
  956. package/dist/widget/components/ErrorAnimationIcon.js +0 -148
  957. package/dist/widget/components/ErrorDisplay.d.ts +0 -9
  958. package/dist/widget/components/ErrorDisplay.d.ts.map +0 -1
  959. package/dist/widget/components/ErrorDisplay.js +0 -104
  960. package/dist/widget/components/ExecutingIntentsBadge.d.ts +0 -12
  961. package/dist/widget/components/ExecutingIntentsBadge.d.ts.map +0 -1
  962. package/dist/widget/components/ExecutionStatusBadge.d.ts +0 -5
  963. package/dist/widget/components/ExecutionStatusBadge.d.ts.map +0 -1
  964. package/dist/widget/components/ExecutionStatusBadge.js +0 -45
  965. package/dist/widget/components/FeeOption.d.ts +0 -20
  966. package/dist/widget/components/FeeOption.d.ts.map +0 -1
  967. package/dist/widget/components/FeeOption.js +0 -71
  968. package/dist/widget/components/FeeOptions.d.ts +0 -20
  969. package/dist/widget/components/FeeOptions.d.ts.map +0 -1
  970. package/dist/widget/components/FeeOptions.js +0 -99
  971. package/dist/widget/components/FiatSelector.d.ts +0 -18
  972. package/dist/widget/components/FiatSelector.d.ts.map +0 -1
  973. package/dist/widget/components/FiatSelector.js +0 -171
  974. package/dist/widget/components/FiatSelectorButton.d.ts +0 -11
  975. package/dist/widget/components/FiatSelectorButton.d.ts.map +0 -1
  976. package/dist/widget/components/FiatSelectorButton.js +0 -41
  977. package/dist/widget/components/Footer.d.ts +0 -7
  978. package/dist/widget/components/Footer.d.ts.map +0 -1
  979. package/dist/widget/components/Footer.js +0 -71
  980. package/dist/widget/components/Fund.d.ts +0 -19
  981. package/dist/widget/components/Fund.d.ts.map +0 -1
  982. package/dist/widget/components/Fund.js +0 -16
  983. package/dist/widget/components/Fund.types.d.ts +0 -22
  984. package/dist/widget/components/Fund.types.d.ts.map +0 -1
  985. package/dist/widget/components/FundExactInput.d.ts +0 -5
  986. package/dist/widget/components/FundExactInput.d.ts.map +0 -1
  987. package/dist/widget/components/FundExactInput.js +0 -1116
  988. package/dist/widget/components/FundExactOutput.d.ts +0 -5
  989. package/dist/widget/components/FundExactOutput.d.ts.map +0 -1
  990. package/dist/widget/components/FundExactOutput.js +0 -498
  991. package/dist/widget/components/FundMethods.d.ts +0 -15
  992. package/dist/widget/components/FundMethods.d.ts.map +0 -1
  993. package/dist/widget/components/FundMethods.js +0 -219
  994. package/dist/widget/components/FundWalletSelection.d.ts +0 -3
  995. package/dist/widget/components/FundWalletSelection.d.ts.map +0 -1
  996. package/dist/widget/components/FundWalletSelection.js +0 -38
  997. package/dist/widget/components/FundingMethodSelectorButton.d.ts +0 -11
  998. package/dist/widget/components/FundingMethodSelectorButton.d.ts.map +0 -1
  999. package/dist/widget/components/FundingMethodSelectorButton.js +0 -57
  1000. package/dist/widget/components/GreenCheckAnimation.d.ts +0 -2
  1001. package/dist/widget/components/GreenCheckAnimation.d.ts.map +0 -1
  1002. package/dist/widget/components/GreenCheckAnimation.js +0 -135
  1003. package/dist/widget/components/HighPriceImpactBlock.d.ts +0 -7
  1004. package/dist/widget/components/HighPriceImpactBlock.d.ts.map +0 -1
  1005. package/dist/widget/components/HighPriceImpactBlock.js +0 -33
  1006. package/dist/widget/components/HookModalContent.d.ts +0 -8
  1007. package/dist/widget/components/HookModalContent.d.ts.map +0 -1
  1008. package/dist/widget/components/HookModalContent.js +0 -237
  1009. package/dist/widget/components/Identicon.d.ts +0 -9
  1010. package/dist/widget/components/Identicon.d.ts.map +0 -1
  1011. package/dist/widget/components/Identicon.js +0 -176
  1012. package/dist/widget/components/LoadingSpinner.d.ts +0 -5
  1013. package/dist/widget/components/LoadingSpinner.d.ts.map +0 -1
  1014. package/dist/widget/components/LoadingSpinner.js +0 -5
  1015. package/dist/widget/components/MeldForm.d.ts +0 -24
  1016. package/dist/widget/components/MeldForm.d.ts.map +0 -1
  1017. package/dist/widget/components/MeldForm.js +0 -447
  1018. package/dist/widget/components/MeldHistory.d.ts +0 -13
  1019. package/dist/widget/components/MeldHistory.d.ts.map +0 -1
  1020. package/dist/widget/components/MeldHistory.js +0 -307
  1021. package/dist/widget/components/MeldStepsFlow.d.ts +0 -6
  1022. package/dist/widget/components/MeldStepsFlow.d.ts.map +0 -1
  1023. package/dist/widget/components/MeldStepsFlow.js +0 -785
  1024. package/dist/widget/components/MeldTransactionStatus.d.ts +0 -20
  1025. package/dist/widget/components/MeldTransactionStatus.d.ts.map +0 -1
  1026. package/dist/widget/components/MeldTransactionStatus.js +0 -157
  1027. package/dist/widget/components/MeshExchangeAccountHeader.d.ts +0 -9
  1028. package/dist/widget/components/MeshExchangeAccountHeader.d.ts.map +0 -1
  1029. package/dist/widget/components/MeshExchangeAccountHeader.js +0 -30
  1030. package/dist/widget/components/Modal.d.ts +0 -9
  1031. package/dist/widget/components/Modal.d.ts.map +0 -1
  1032. package/dist/widget/components/Modal.js +0 -65
  1033. package/dist/widget/components/OFTProgressBar.d.ts +0 -16
  1034. package/dist/widget/components/OFTProgressBar.d.ts.map +0 -1
  1035. package/dist/widget/components/OFTProgressBar.js +0 -49
  1036. package/dist/widget/components/OnRampProviderSelector.d.ts +0 -13
  1037. package/dist/widget/components/OnRampProviderSelector.d.ts.map +0 -1
  1038. package/dist/widget/components/OnRampProviderSelector.js +0 -144
  1039. package/dist/widget/components/OnrampErrorScreen.d.ts +0 -15
  1040. package/dist/widget/components/OnrampErrorScreen.d.ts.map +0 -1
  1041. package/dist/widget/components/OnrampErrorScreen.js +0 -102
  1042. package/dist/widget/components/OnrampHistoryRow.d.ts +0 -13
  1043. package/dist/widget/components/OnrampHistoryRow.d.ts.map +0 -1
  1044. package/dist/widget/components/OnrampHistoryRow.js +0 -249
  1045. package/dist/widget/components/OnrampPaymentMethods.d.ts +0 -7
  1046. package/dist/widget/components/OnrampPaymentMethods.d.ts.map +0 -1
  1047. package/dist/widget/components/OnrampPaymentMethods.js +0 -54
  1048. package/dist/widget/components/OnrampProviderConfirmation.d.ts +0 -30
  1049. package/dist/widget/components/OnrampProviderConfirmation.d.ts.map +0 -1
  1050. package/dist/widget/components/OnrampProviderConfirmation.js +0 -705
  1051. package/dist/widget/components/OriginSelectionAmount.d.ts +0 -12
  1052. package/dist/widget/components/OriginSelectionAmount.d.ts.map +0 -1
  1053. package/dist/widget/components/OriginSelectionAmount.js +0 -104
  1054. package/dist/widget/components/OriginTransferInformation.d.ts +0 -10
  1055. package/dist/widget/components/OriginTransferInformation.d.ts.map +0 -1
  1056. package/dist/widget/components/OriginTransferInformation.js +0 -56
  1057. package/dist/widget/components/Pay.d.ts +0 -7
  1058. package/dist/widget/components/Pay.d.ts.map +0 -1
  1059. package/dist/widget/components/Pay.js +0 -649
  1060. package/dist/widget/components/PaymentMethods.d.ts +0 -10
  1061. package/dist/widget/components/PaymentMethods.d.ts.map +0 -1
  1062. package/dist/widget/components/PaymentMethods.js +0 -118
  1063. package/dist/widget/components/PercentageMaxButtons.d.ts +0 -14
  1064. package/dist/widget/components/PercentageMaxButtons.d.ts.map +0 -1
  1065. package/dist/widget/components/PercentageMaxButtons.js +0 -62
  1066. package/dist/widget/components/PoolDeposit.d.ts +0 -32
  1067. package/dist/widget/components/PoolDeposit.d.ts.map +0 -1
  1068. package/dist/widget/components/PoolDeposit.js +0 -426
  1069. package/dist/widget/components/PriceImpactWarning.d.ts +0 -11
  1070. package/dist/widget/components/PriceImpactWarning.d.ts.map +0 -1
  1071. package/dist/widget/components/PriceImpactWarning.js +0 -58
  1072. package/dist/widget/components/PulsatingButton.d.ts +0 -9
  1073. package/dist/widget/components/PulsatingButton.d.ts.map +0 -1
  1074. package/dist/widget/components/PulsatingButton.js +0 -48
  1075. package/dist/widget/components/QRCodeOptions.d.ts +0 -9
  1076. package/dist/widget/components/QRCodeOptions.d.ts.map +0 -1
  1077. package/dist/widget/components/QRCodeOptions.js +0 -57
  1078. package/dist/widget/components/QRCodeWalletSelect.d.ts +0 -13
  1079. package/dist/widget/components/QRCodeWalletSelect.d.ts.map +0 -1
  1080. package/dist/widget/components/QRCodeWalletSelect.js +0 -45
  1081. package/dist/widget/components/QrCode.d.ts +0 -10
  1082. package/dist/widget/components/QrCode.d.ts.map +0 -1
  1083. package/dist/widget/components/QrCode.js +0 -69
  1084. package/dist/widget/components/QuoteDetails.d.ts +0 -25
  1085. package/dist/widget/components/QuoteDetails.d.ts.map +0 -1
  1086. package/dist/widget/components/QuoteDetails.js +0 -728
  1087. package/dist/widget/components/QuoteInputErrorBlock.d.ts +0 -7
  1088. package/dist/widget/components/QuoteInputErrorBlock.d.ts.map +0 -1
  1089. package/dist/widget/components/QuoteInputErrorBlock.js +0 -22
  1090. package/dist/widget/components/Receipt.d.ts +0 -18
  1091. package/dist/widget/components/Receipt.d.ts.map +0 -1
  1092. package/dist/widget/components/Receipt.js +0 -443
  1093. package/dist/widget/components/ReceiptRecoverableFunds.d.ts +0 -25
  1094. package/dist/widget/components/ReceiptRecoverableFunds.d.ts.map +0 -1
  1095. package/dist/widget/components/ReceiptRecoverableFunds.js +0 -75
  1096. package/dist/widget/components/RecentChains.d.ts +0 -9
  1097. package/dist/widget/components/RecentChains.d.ts.map +0 -1
  1098. package/dist/widget/components/RecentChains.js +0 -28
  1099. package/dist/widget/components/RecentTokens.d.ts +0 -10
  1100. package/dist/widget/components/RecentTokens.d.ts.map +0 -1
  1101. package/dist/widget/components/RecentTokens.js +0 -37
  1102. package/dist/widget/components/RecipientSelectorButton.d.ts +0 -6
  1103. package/dist/widget/components/RecipientSelectorButton.d.ts.map +0 -1
  1104. package/dist/widget/components/RecipientSelectorButton.js +0 -36
  1105. package/dist/widget/components/Recipients.d.ts +0 -9
  1106. package/dist/widget/components/Recipients.d.ts.map +0 -1
  1107. package/dist/widget/components/Recipients.js +0 -208
  1108. package/dist/widget/components/RefundWarning.d.ts +0 -11
  1109. package/dist/widget/components/RefundWarning.d.ts.map +0 -1
  1110. package/dist/widget/components/RefundWarning.js +0 -33
  1111. package/dist/widget/components/RequiredPropsError.d.ts +0 -8
  1112. package/dist/widget/components/RequiredPropsError.d.ts.map +0 -1
  1113. package/dist/widget/components/RequiredPropsError.js +0 -14
  1114. package/dist/widget/components/ScreenHeader.d.ts +0 -13
  1115. package/dist/widget/components/ScreenHeader.d.ts.map +0 -1
  1116. package/dist/widget/components/ScreenHeader.js +0 -64
  1117. package/dist/widget/components/SearchInputField.d.ts +0 -14
  1118. package/dist/widget/components/SearchInputField.d.ts.map +0 -1
  1119. package/dist/widget/components/SearchInputField.js +0 -51
  1120. package/dist/widget/components/SessionTimeoutScreen.d.ts +0 -12
  1121. package/dist/widget/components/SessionTimeoutScreen.d.ts.map +0 -1
  1122. package/dist/widget/components/SessionTimeoutScreen.js +0 -64
  1123. package/dist/widget/components/ShadowPortal.d.ts +0 -6
  1124. package/dist/widget/components/ShadowPortal.d.ts.map +0 -1
  1125. package/dist/widget/components/ShadowPortal.js +0 -52
  1126. package/dist/widget/components/ShadowRootContext.d.ts +0 -8
  1127. package/dist/widget/components/ShadowRootContext.d.ts.map +0 -1
  1128. package/dist/widget/components/ShadowRootContext.js +0 -12
  1129. package/dist/widget/components/SimpleRecipientInputScreen.d.ts +0 -13
  1130. package/dist/widget/components/SimpleRecipientInputScreen.d.ts.map +0 -1
  1131. package/dist/widget/components/SimpleRecipientInputScreen.js +0 -48
  1132. package/dist/widget/components/SlippageToleranceSettings.d.ts +0 -9
  1133. package/dist/widget/components/SlippageToleranceSettings.d.ts.map +0 -1
  1134. package/dist/widget/components/SlippageToleranceSettings.js +0 -159
  1135. package/dist/widget/components/Swap.d.ts +0 -43
  1136. package/dist/widget/components/Swap.d.ts.map +0 -1
  1137. package/dist/widget/components/Swap.js +0 -6
  1138. package/dist/widget/components/SwapDisplay.d.ts +0 -9
  1139. package/dist/widget/components/SwapDisplay.d.ts.map +0 -1
  1140. package/dist/widget/components/SwapDisplay.js +0 -72
  1141. package/dist/widget/components/ThemeProvider.d.ts +0 -16
  1142. package/dist/widget/components/ThemeProvider.d.ts.map +0 -1
  1143. package/dist/widget/components/ThemeProvider.js +0 -52
  1144. package/dist/widget/components/ThemeSyncer.d.ts +0 -6
  1145. package/dist/widget/components/ThemeSyncer.d.ts.map +0 -1
  1146. package/dist/widget/components/ThemeSyncer.js +0 -25
  1147. package/dist/widget/components/Toast.d.ts +0 -24
  1148. package/dist/widget/components/Toast.d.ts.map +0 -1
  1149. package/dist/widget/components/Toast.js +0 -206
  1150. package/dist/widget/components/TokenDisplayNonSelectable.d.ts +0 -11
  1151. package/dist/widget/components/TokenDisplayNonSelectable.d.ts.map +0 -1
  1152. package/dist/widget/components/TokenDisplayNonSelectable.js +0 -30
  1153. package/dist/widget/components/TokenImage.d.ts +0 -11
  1154. package/dist/widget/components/TokenImage.d.ts.map +0 -1
  1155. package/dist/widget/components/TokenImage.js +0 -96
  1156. package/dist/widget/components/TokenList.d.ts +0 -20
  1157. package/dist/widget/components/TokenList.d.ts.map +0 -1
  1158. package/dist/widget/components/TokenList.js +0 -45
  1159. package/dist/widget/components/TokenSelector.d.ts +0 -32
  1160. package/dist/widget/components/TokenSelector.d.ts.map +0 -1
  1161. package/dist/widget/components/TokenSelector.js +0 -479
  1162. package/dist/widget/components/TokenSelectorButton.d.ts +0 -17
  1163. package/dist/widget/components/TokenSelectorButton.d.ts.map +0 -1
  1164. package/dist/widget/components/TokenSelectorButton.js +0 -64
  1165. package/dist/widget/components/TokenSkeleton.d.ts +0 -12
  1166. package/dist/widget/components/TokenSkeleton.d.ts.map +0 -1
  1167. package/dist/widget/components/TokenSkeleton.js +0 -36
  1168. package/dist/widget/components/Tooltip.d.ts +0 -14
  1169. package/dist/widget/components/Tooltip.d.ts.map +0 -1
  1170. package/dist/widget/components/Tooltip.js +0 -38
  1171. package/dist/widget/components/TrailsHookModal.d.ts +0 -10
  1172. package/dist/widget/components/TrailsHookModal.d.ts.map +0 -1
  1173. package/dist/widget/components/TrailsHookModal.js +0 -55
  1174. package/dist/widget/components/TransactionDetails.d.ts +0 -10
  1175. package/dist/widget/components/TransactionDetails.d.ts.map +0 -1
  1176. package/dist/widget/components/TransactionDetails.js +0 -492
  1177. package/dist/widget/components/TransactionHistoryItem.d.ts +0 -23
  1178. package/dist/widget/components/TransactionHistoryItem.d.ts.map +0 -1
  1179. package/dist/widget/components/TransactionHistoryItem.js +0 -547
  1180. package/dist/widget/components/TransferPendingVertical.d.ts +0 -16
  1181. package/dist/widget/components/TransferPendingVertical.d.ts.map +0 -1
  1182. package/dist/widget/components/TransferPendingVertical.js +0 -356
  1183. package/dist/widget/components/TruncatedTransactionHash.d.ts +0 -12
  1184. package/dist/widget/components/TruncatedTransactionHash.d.ts.map +0 -1
  1185. package/dist/widget/components/TruncatedTransactionHash.js +0 -36
  1186. package/dist/widget/components/UserPreferences.d.ts +0 -7
  1187. package/dist/widget/components/UserPreferences.d.ts.map +0 -1
  1188. package/dist/widget/components/UserPreferences.js +0 -282
  1189. package/dist/widget/components/WaasFeeOptions.d.ts +0 -12
  1190. package/dist/widget/components/WaasFeeOptions.d.ts.map +0 -1
  1191. package/dist/widget/components/WaasFeeOptions.js +0 -349
  1192. package/dist/widget/components/WalletAccountHeader.d.ts +0 -8
  1193. package/dist/widget/components/WalletAccountHeader.d.ts.map +0 -1
  1194. package/dist/widget/components/WalletAccountHeader.js +0 -45
  1195. package/dist/widget/components/WalletConfirmation.d.ts +0 -15
  1196. package/dist/widget/components/WalletConfirmation.d.ts.map +0 -1
  1197. package/dist/widget/components/WalletConfirmation.js +0 -145
  1198. package/dist/widget/components/WalletConnect.d.ts +0 -11
  1199. package/dist/widget/components/WalletConnect.d.ts.map +0 -1
  1200. package/dist/widget/components/WalletConnect.js +0 -164
  1201. package/dist/widget/components/WalletConnectionPending.d.ts +0 -12
  1202. package/dist/widget/components/WalletConnectionPending.d.ts.map +0 -1
  1203. package/dist/widget/components/WalletConnectionPending.js +0 -124
  1204. package/dist/widget/components/WalletList.d.ts +0 -16
  1205. package/dist/widget/components/WalletList.d.ts.map +0 -1
  1206. package/dist/widget/components/WalletList.js +0 -88
  1207. package/dist/widget/components/WidgetProviders.d.ts +0 -16
  1208. package/dist/widget/components/WidgetProviders.d.ts.map +0 -1
  1209. package/dist/widget/components/WidgetProviders.js +0 -43
  1210. package/dist/widget/components/Withdraw.d.ts +0 -12
  1211. package/dist/widget/components/Withdraw.d.ts.map +0 -1
  1212. package/dist/widget/components/Withdraw.js +0 -551
  1213. package/dist/widget/components/YellowWarningAnimation.d.ts +0 -2
  1214. package/dist/widget/components/YellowWarningAnimation.d.ts.map +0 -1
  1215. package/dist/widget/components/YellowWarningAnimation.js +0 -167
  1216. package/dist/widget/components/earnMarketUtils.d.ts +0 -11
  1217. package/dist/widget/components/earnMarketUtils.d.ts.map +0 -1
  1218. package/dist/widget/components/earnMarketUtils.js +0 -48
  1219. package/dist/widget/components/earnNetworks.d.ts +0 -6
  1220. package/dist/widget/components/earnNetworks.d.ts.map +0 -1
  1221. package/dist/widget/components/earnNetworks.js +0 -33
  1222. package/dist/widget/index.d.ts.map +0 -1
  1223. package/dist/widget/modes/EarnWidget.d.ts +0 -90
  1224. package/dist/widget/modes/EarnWidget.d.ts.map +0 -1
  1225. package/dist/widget/modes/EarnWidget.js +0 -41
  1226. package/dist/widget/modes/FundWidget.d.ts +0 -110
  1227. package/dist/widget/modes/FundWidget.d.ts.map +0 -1
  1228. package/dist/widget/modes/FundWidget.js +0 -48
  1229. package/dist/widget/modes/PayWidget.d.ts +0 -80
  1230. package/dist/widget/modes/PayWidget.d.ts.map +0 -1
  1231. package/dist/widget/modes/PayWidget.js +0 -40
  1232. package/dist/widget/modes/SwapWidget.d.ts +0 -76
  1233. package/dist/widget/modes/SwapWidget.d.ts.map +0 -1
  1234. package/dist/widget/modes/SwapWidget.js +0 -41
  1235. package/dist/widget/modes/WithdrawWidget.d.ts +0 -87
  1236. package/dist/widget/modes/WithdrawWidget.d.ts.map +0 -1
  1237. package/dist/widget/modes/WithdrawWidget.js +0 -38
  1238. package/dist/widget/props.d.ts +0 -255
  1239. package/dist/widget/props.d.ts.map +0 -1
  1240. package/dist/widget/props.js +0 -14
  1241. package/dist/widget/providers/TrailsModalProvider.d.ts +0 -78
  1242. package/dist/widget/providers/TrailsModalProvider.d.ts.map +0 -1
  1243. package/dist/widget/providers/TrailsModalProvider.js +0 -57
  1244. package/dist/widget/providers/TrailsProvider.d.ts +0 -100
  1245. package/dist/widget/providers/TrailsProvider.d.ts.map +0 -1
  1246. package/dist/widget/providers/TrailsProvider.js +0 -101
  1247. package/dist/widget/providers/UserActivityProvider.d.ts +0 -18
  1248. package/dist/widget/providers/UserActivityProvider.d.ts.map +0 -1
  1249. package/dist/widget/providers/UserActivityProvider.js +0 -38
  1250. package/dist/widget/providers/WalletContext.d.ts +0 -10
  1251. package/dist/widget/providers/WalletContext.d.ts.map +0 -1
  1252. package/dist/widget/providers/WalletContext.js +0 -23
  1253. package/dist/widget/providers/WidgetProviderTree.d.ts +0 -24
  1254. package/dist/widget/providers/WidgetProviderTree.d.ts.map +0 -1
  1255. package/dist/widget/providers/WidgetProviderTree.js +0 -35
  1256. package/dist/widget/providers/adapterConfig.d.ts +0 -13
  1257. package/dist/widget/providers/adapterConfig.d.ts.map +0 -1
  1258. package/dist/widget/providers/adapterConfig.js +0 -97
  1259. package/dist/widget/providers/sequenceSupport.d.ts +0 -42
  1260. package/dist/widget/providers/sequenceSupport.d.ts.map +0 -1
  1261. package/dist/widget/providers/walletRuntimeResolution.d.ts +0 -10
  1262. package/dist/widget/providers/walletRuntimeResolution.d.ts.map +0 -1
  1263. package/dist/widget/providers/walletRuntimeResolution.js +0 -14
  1264. package/dist/widget/shared/destinationDefaultToken.d.ts +0 -15
  1265. package/dist/widget/shared/destinationDefaultToken.d.ts.map +0 -1
  1266. package/dist/widget/shared/destinationDefaultToken.js +0 -18
  1267. package/dist/widget/shared/destinationSupport.d.ts +0 -40
  1268. package/dist/widget/shared/destinationSupport.d.ts.map +0 -1
  1269. package/dist/widget/shared/destinationSupport.js +0 -215
  1270. package/dist/widget/shared/mapSharedProps.d.ts +0 -9
  1271. package/dist/widget/shared/mapSharedProps.d.ts.map +0 -1
  1272. package/dist/widget/shared/mapSharedProps.js +0 -22
  1273. package/dist/widget/shared/methodMap.d.ts +0 -18
  1274. package/dist/widget/shared/methodMap.d.ts.map +0 -1
  1275. package/dist/widget/shared/methodMap.js +0 -25
  1276. package/dist/widget/shared/resolution.d.ts +0 -8
  1277. package/dist/widget/shared/resolution.d.ts.map +0 -1
  1278. package/dist/widget/shared/resolution.js +0 -63
  1279. package/dist/widget/shared/resolvePaymentSource.d.ts +0 -37
  1280. package/dist/widget/shared/resolvePaymentSource.d.ts.map +0 -1
  1281. package/dist/widget/shared/resolvePaymentSource.js +0 -19
  1282. package/dist/widget/shared/types.d.ts +0 -142
  1283. package/dist/widget/shared/types.d.ts.map +0 -1
  1284. package/dist/widget/styles.gen.d.ts +0 -2
  1285. package/dist/widget/styles.gen.d.ts.map +0 -1
  1286. package/dist/widget/styles.gen.js +0 -29
  1287. package/dist/widget/types/analytics.d.ts +0 -22
  1288. package/dist/widget/types/analytics.d.ts.map +0 -1
  1289. package/dist/widget/types/commonProps.d.ts +0 -48
  1290. package/dist/widget/types/commonProps.d.ts.map +0 -1
  1291. package/dist/widget/utils/countryUtils.d.ts +0 -37
  1292. package/dist/widget/utils/countryUtils.d.ts.map +0 -1
  1293. package/dist/widget/utils/countryUtils.js +0 -14
  1294. package/dist/widget/utils/forexRateStore.d.ts +0 -25
  1295. package/dist/widget/utils/forexRateStore.d.ts.map +0 -1
  1296. package/dist/widget/utils/forexRateStore.js +0 -59
  1297. package/dist/widget/utils/fundMethodSwitchState.d.ts +0 -14
  1298. package/dist/widget/utils/fundMethodSwitchState.d.ts.map +0 -1
  1299. package/dist/widget/utils/fundMethodSwitchState.js +0 -6
  1300. package/dist/widget/utils/historyFilters.d.ts +0 -13
  1301. package/dist/widget/utils/historyFilters.d.ts.map +0 -1
  1302. package/dist/widget/utils/historyFilters.js +0 -108
  1303. package/dist/widget/utils/localeStore.d.ts +0 -19
  1304. package/dist/widget/utils/localeStore.d.ts.map +0 -1
  1305. package/dist/widget/utils/localeStore.js +0 -39
  1306. package/dist/widget/utils/meldProviderUtils.d.ts +0 -6
  1307. package/dist/widget/utils/meldProviderUtils.d.ts.map +0 -1
  1308. package/dist/widget/utils/meldProviderUtils.js +0 -9
  1309. package/dist/widget/utils/meshSupportedTokens.d.ts +0 -4
  1310. package/dist/widget/utils/meshSupportedTokens.d.ts.map +0 -1
  1311. package/dist/widget/utils/meshSupportedTokens.js +0 -12
  1312. package/dist/widget/utils/onrampConfig.d.ts +0 -11
  1313. package/dist/widget/utils/onrampConfig.d.ts.map +0 -1
  1314. package/dist/widget/utils/onrampConfig.js +0 -6
  1315. package/dist/widget/utils/statusLabel.d.ts +0 -2
  1316. package/dist/widget/utils/statusLabel.d.ts.map +0 -1
  1317. package/dist/widget/utils/statusLabel.js +0 -6
  1318. package/dist/widget/utils/tokens.d.ts +0 -60
  1319. package/dist/widget/utils/tokens.d.ts.map +0 -1
  1320. package/dist/widget/utils/tokens.js +0 -16
  1321. package/dist/widget/utils/trailsOnrampConfig.d.ts +0 -23
  1322. package/dist/widget/utils/trailsOnrampConfig.d.ts.map +0 -1
  1323. package/dist/widget/utils/trailsOnrampConfig.js +0 -7
  1324. package/dist/widget/utils/transactionFailure.d.ts +0 -20
  1325. package/dist/widget/utils/transactionFailure.d.ts.map +0 -1
  1326. package/dist/widget/utils/transactionFailure.js +0 -12
  1327. package/dist/widget/utils/viewManagerGuards.d.ts +0 -5
  1328. package/dist/widget/utils/viewManagerGuards.d.ts.map +0 -1
  1329. package/dist/widget/utils/viewManagerGuards.js +0 -24
  1330. package/dist/widget/utils/walletConnectRedirect.d.ts +0 -19
  1331. package/dist/widget/utils/walletConnectRedirect.d.ts.map +0 -1
  1332. package/dist/widget/utils/walletConnectRedirect.js +0 -21
  1333. package/dist/widget/utils/windowUtils.d.ts +0 -13
  1334. package/dist/widget/utils/windowUtils.d.ts.map +0 -1
  1335. package/dist/widget/utils/windowUtils.js +0 -84
  1336. package/dist/widget/widget.d.ts +0 -16
  1337. package/dist/widget/widget.d.ts.map +0 -1
  1338. package/dist/widget/widget.js +0 -1541
  1339. package/dist/widgetFlowHooks.d.ts +0 -12
  1340. package/dist/widgetFlowHooks.d.ts.map +0 -1
  1341. package/dist/widgetFlowHooks.js +0 -18
@@ -0,0 +1,94 @@
1
+ import{$ as e,A as t,B as n,C as r,F as i,J as a,K as o,L as s,N as c,P as l,Q as u,R as d,S as f,T as p,U as m,W as h,X as g,Y as _,Z as v,_ as y,_t as b,a as x,at as S,b as C,c as w,dt as T,et as E,f as D,g as O,gt as k,h as A,ht as j,i as M,j as N,k as P,lt as F,m as I,mt as ee,n as te,nt as ne,o as re,ot as ie,p as L,pt as R,q as ae,r as z,rt as B,s as V,st as oe,t as H,tt as se,u as ce,v as U,w as le,x as ue,y as de,yt as fe,z as pe}from"./ConnectWalletCard-BkbHCcWi.js";import{t as me}from"./defineProperty-BbfpZ9Tg.js";import{_ as he,a as ge,c as _e,d as ve,f as ye,g as be,h as xe,i as Se,l as Ce,m as we,n as Te,o as Ee,p as De,r as Oe,s as ke,t as Ae,u as je,v as Me,x as Ne}from"./contractConstants-CvJrYK9v.js";import{$ as Pe,A as Fe,D as Ie,E as Le,F as Re,G as ze,H as Be,I as Ve,K as He,L as Ue,M as We,N as Ge,O as Ke,P as qe,Q as Je,T as Ye,U as Xe,W as Ze,X as W,Z as Qe,_ as $e,at as et,b as tt,c as nt,ct as rt,dt as it,et as at,ft as ot,gt as st,ht as ct,i as lt,it as ut,j as dt,k as G,lt as ft,mt as pt,nt as mt,o as ht,ot as gt,pt as _t,q as vt,r as yt,rt as bt,s as xt,st as St,tt as Ct,ut as wt,v as Tt,x as Et,y as Dt,z as Ot}from"./actionBuilder-CAS2u5wu.js";import{a as kt,c as At,i as jt,l as Mt,n as Nt,o as Pt,r as Ft}from"./edge-L_Lk1K6j.js";import{c as It,f as Lt,g as Rt,h as zt,l as Bt,o as Vt,p as Ht,u as Ut,y as Wt}from"./hydrate-QyWqQfec.js";import{Config as Gt,Constants as Kt,Erc6492 as qt,Payload as Jt,Payload as Yt,Signature as Xt}from"@0xsequence/wallet-primitives";import{EdgeMode as Zt,EdgeRail as Qt,EdgeStatus as $t,FundMethod as en,IntentMode as tn,IntentProtocolVersion as nn,IntentStatus as rn,JsonEncode as an,RouteProvider as on,RouteProvider as sn,TradeType as cn,TradeType as ln,TrailsApi as un,TransactionStatus as dn}from"@0xtrails/api";import{BaseError as fn,createPublicClient as pn,decodeEventLog as mn,domainSeparator as hn,encodeFunctionData as gn,erc20Abi as _n,formatUnits as vn,getAddress as yn,isAddress as bn,parseAbiItem as xn,parseUnits as Sn,zeroAddress as Cn}from"viem";import{apeChain as wn,arbitrum as Tn,arbitrumNova as En,arbitrumSepolia as Dn,avalanche as On,avalancheFuji as kn,b3 as An,b3Sepolia as jn,base as Mn,baseSepolia as Nn,berachain as Pn,berachainBepolia as Fn,blastSepolia as In,bsc as Ln,bscTestnet as Rn,etherlink as zn,etherlinkTestnet as Bn,gnosis as Vn,gnosisChiado as Hn,hyperEvm as Un,hyperliquidEvmTestnet as Wn,katana as Gn,mainnet as Kn,monad as qn,monadTestnet as Jn,optimism as Yn,optimismSepolia as Xn,polygon as Zn,polygonAmoy as Qn,sepolia as $n,somniaTestnet as er,soneium as tr,soneiumMinato as nr,sonic as rr,sonicTestnet as ir,xaiTestnet as ar}from"viem/chains";import or,{Fragment as sr,StrictMode as cr,Suspense as lr,createContext as ur,createElement as dr,forwardRef as fr,lazy as pr,memo as mr,useCallback as K,useContext as hr,useDeferredValue as gr,useEffect as q,useId as _r,useImperativeHandle as vr,useLayoutEffect as yr,useMemo as J,useReducer as br,useRef as Y,useState as X}from"react";import{QueryClient as xr,QueryClientContext as Sr,QueryClientProvider as Cr,queryOptions as wr,skipToken as Tr,useInfiniteQuery as Er,useMutation as Dr,useQuery as Or,useQueryClient as kr}from"@tanstack/react-query";import{createPortal as Ar}from"react-dom";import{NativeConnectorsWalletProvider as jr,WalletAdapterCompositionProvider as Mr,checkProviderHealth as Nr,checkProviderHealth as Pr,createEip1193Adapter as Fr,isEmbeddedWalletConnector as Ir,isEvmWalletSessionConnected as Lr,isSelectableWalletListConnectOption as Rr,isSequenceWallet as zr,isSequenceWallet as Br,isTrailsWalletClient as Vr,isWalletConnectConnector as Hr,isWalletConnectConnector as Ur,signWithTimeout as Wr,signWithTimeout as Gr,useAccount as Kr,useActiveWalletRuntimeConnection as qr,useConnectedWallets as Jr,useConnection as Yr,useConnections as Xr,useEvmWalletSession as Zr,useHasWalletContext as Qr,useIsSequenceWallet as $r,useOptionalWalletAdapterSnapshot as ei,useOptionalWalletCapabilities as ti,useOptionalWalletSession as ni,useTrailsWalletClient as ri,useWalletAccountEffect as ii,useWalletActions as ai,useWalletChainId as oi,useWalletClient as si,useWalletClientForConnection as ci,useWalletConnectOptions as li,useWalletPublicClient as ui,useWalletSession as di,useWalletSession as fi,wrapWalletClient as pi,wrapWalletClient as mi}from"@0xtrails/wallet";import{Fragment as hi,jsx as Z,jsxs as Q}from"react/jsx-runtime";import{AlertCircle as gi,AlertTriangle as _i,AlignJustify as vi,ArrowDown as yi,ArrowDownCircle as bi,ArrowLeftRight as xi,ArrowLeftRightIcon as Si,ArrowUpCircle as Ci,Building2 as wi,Check as Ti,CheckCircle as Ei,ChevronDown as Di,ChevronLeft as Oi,ChevronRight as ki,ChevronUp as Ai,CirclePlus as ji,Clock as Mi,Copy as Ni,CreditCard as Pi,CreditCardIcon as Fi,DollarSign as Ii,ExternalLink as Li,HelpCircle as Ri,History as zi,HistoryIcon as Bi,Info as Vi,Loader2 as Hi,LogOut as Ui,QrCode as Wi,RefreshCw as Gi,RotateCcw as Ki,Search as qi,Send as Ji,Settings as Yi,Smartphone as Xi,Star as Zi,TrendingDown as Qi,TrendingUp as $i,TriangleAlert as ea,User as ta,Wallet as na,X as ra,XCircle as ia,ZapIcon as aa}from"lucide-react";import{experimental_createQueryPersister as oa}from"@tanstack/query-persist-client-core";import{SequenceMetadata as sa}from"@0xsequence/metadata";import{SEQUENCE_EMBEDDED_WALLET_ID as ca,getQRCodeWallets as la,getWalletIconUrl as ua,getWalletIdFromRdns as da,getWalletName as fa,getWalletRegistry as pa,isSequenceEmbeddedWalletId as ma,isSequenceEmbeddedWalletId as ha,isSequenceWalletId as ga,isSequenceWalletId as _a,matchesWalletId as va,normalizeWalletId as ya,topShownWallets as ba}from"@0xtrails/wallet/registry";import{Databeat as xa}from"@databeat/tracker";import{AbiFunction as Sa,Address as Ca,Bytes as wa,ContractAddress as Ta,Hash as Ea,Hex as Da}from"ox";import{ContractVerificationStatus as Oa,SequenceIndexer as ka,SequenceIndexerGateway as Aa}from"@0xsequence/indexer";import{useVirtualizer as ja}from"@tanstack/react-virtual";import{TrailsOnrampRpcClient as Ma}from"@0xtrails/api/onramp";import{WalletIcon as Na}from"@0xtrails/wallet/registry/icons";import{normalize as Pa}from"viem/ens";import{getRememberedNativeWalletIds as Fa,usePersistedNativeWalletState as Ia,useWalletConnectOptionViews as La}from"@0xtrails/wallet/runtime";const Ra={chainId:101,name:`Solana`,imageUrl:Ge.SOL};function za(e){let t=Ka(e.map(Ua).filter(e=>e!==null));if(t.length===0)throw Error(`[trails-sdk] getChains mapped to zero supported chains`);return t}function Ba(e){return Qe(e)?Ge.SOL:`https://assets.sequence.info/images/networks/large/${e}.webp`}function Va(e,t){if(W(e))throw Error(`[trails-sdk] getChainRpcClient(${e}): Solana is not EVM; use Solana JSON-RPC and SPL helpers instead of viem against Solana HTTP RPCs.`);let n=$(e);return n?_t(e,t,n):(s.console.warn(`[trails-sdk] Chain ${e} not found. Falling back to a generic public client.`),_t(e,t,null))}async function Ha(e){let t=he(),n={trailsApiUrl:e?.trailsApiUrl??t.trailsApiUrl,trailsApiKey:e?.trailsApiKey??t.trailsApiKey},r=(await new un(n.trailsApiKey||``,{hostname:n.trailsApiUrl}).getChains({}))?.chains||[];if(r.length===0)throw Error(`[trails-sdk] getChains returned no supported chains`);return za(r)}function Ua(e){let t=$(e.id);if(!t)return s.console.warn(`[trails-sdk] chain ${e.id} from GetChains is not mapped in SDK, skipping`),null;let n=e.nativeCurrency?.name||t.nativeCurrency.name,r=e.nativeCurrency?.symbol||t.nativeCurrency.symbol,i=e.nativeCurrency?.decimals||t.nativeCurrency.decimals,a=e.blockExplorer?.url||t.blockExplorers?.default?.url,o=e.blockExplorer?.name||t.blockExplorers?.default?.name||`Explorer`;return{...t,name:e.name||t.name,nativeCurrency:{...t.nativeCurrency,name:n,symbol:r,decimals:i},blockExplorers:a?{default:{name:o,url:a}}:t.blockExplorers}}Dn.id,$(Dn.id),kn.id,$(kn.id),jn.id,$(jn.id),Nn.id,$(Nn.id),In.id,$(In.id),Rn.id,$(Rn.id),$n.id,$($n.id),Hn.id,$(Hn.id),Qn.id,$(Qn.id),Xn.id,$(Xn.id),nr.id,$(nr.id),ar.id,$(ar.id),Bn.id,$(Bn.id),er.id,$(er.id),Jn.id,$(Jn.id),Fn.id,$(Fn.id),ir.id,$(ir.id),Wn.id,$(Wn.id),Tn.id,On.id,Mn.id,Vn.id,Yn.id,Zn.id,Kn.id,tr.id,An.id,Ln.id,En.id,wn.id,zn.id,st.id,qn.id,Pn.id,rr.id,Un.id;function $(e,t){if(!e)return null;if(Qe(e))return{id:e,name:`Solana`,imageUrl:Ba(e),nativeCurrency:{name:`Solana`,symbol:`SOL`,decimals:9},rpcUrls:{default:{http:[]},public:{http:[]}},blockExplorers:{default:{name:`Solana Explorer`,url:`https://explorer.solana.com`}}};let n=ct().find(t=>t.id===e)||null;if(!n)return null;let r={...n,rpcUrls:{default:{...n.rpcUrls.default},public:n.rpcUrls.public?{...n.rpcUrls.public}:{...n.rpcUrls.default}},blockExplorers:n.blockExplorers?{...n.blockExplorers}:void 0};if(!t?.usePublicRpc&&t?.sequenceProjectAccessKey&&t?.sequenceNodeGatewayUrl){let n=pt(e,t.sequenceProjectAccessKey,t.sequenceNodeGatewayUrl);n&&(r.rpcUrls={default:{...r.rpcUrls.default,http:[n]},public:{...r.rpcUrls.public,http:[n]}})}e===Gn.id&&(r.blockExplorers={default:{name:`Katanascan`,url:`https://katanascan.com`}});let i=Ga(e,r?.name||``),a=Ba(e);return{...r,name:i,imageUrl:a}}const Wa=[Kn.id,Mn.id,Tn.id,Zn.id,Gn.id,Ln.id,Yn.id,On.id,En.id,zn.id,Vn.id,An.id,wn.id,tr.id,st.id,qn.id,Pn.id,Un.id,rr.id];function Ga(e,t){return{[Tn.id]:`Arbitrum`,[Ln.id]:`BSC`,[Yn.id]:`Optimism`,[tr.id]:`Soneium`}[e]||t||``}function Ka(e){return e.sort((e,t)=>{let n=Wa.indexOf(e.id),r=Wa.indexOf(t.id);return n!==-1&&r!==-1?n-r:n===-1?r===-1?e.name.localeCompare(t.name):1:-1})}async function qa(e){return Ka(await Ha(e))}function Ja(e){return $(e)?.name??`Chain ${e}`}function Ya(e){let t=$(e);return t?`${t.blockExplorers?.default?.url}`:``}function Xa({txHash:e,chainId:t}){return e?`${Ya(t)}/tx/${e}`:``}function Za({address:e,chainId:t}){return e?`${Ya(t)}/address/${e}`:``}const Qa=new Map,$a={register:(e,t)=>{s.console.log(`[trails-sdk] Registering abort controller:`,e),Qa.set(e,t)},unregister:e=>{s.console.log(`[trails-sdk] Unregistering abort controller:`,e),Qa.delete(e)},abort:e=>{let t=Qa.get(e);t&&(t.abort(),Qa.delete(e))},abortAll:()=>{s.console.log(`[trails-sdk] Aborting all active operations:`,Qa.size);for(let[e,t]of Qa)s.console.log(`[trails-sdk] Aborting operation:`,e),t.abort();Qa.clear()},getAll:()=>Array.from(Qa.keys())};async function eo(e,t,n){if(W(t))return!1;let r=await(n??Va(t)).getCode({address:e}),i=no(r),a=to(r),o=i&&!a;return s.console.log(`[trails-sdk] getIsContract:`,e,`chainId:`,t,`isContract:`,o),o}function to(e){return e?.startsWith(`0xef0100`)||!1}function no(e){return e!==void 0&&e!==``&&e!==`0`&&e!==`0x`&&e!==`0x0`&&e!==`0x00`}function ro(e){return no(e)}const io=`https://api.mainnet-beta.solana.com`;function ao(e){let t=new Set,n=[];for(let r of e){let e=r?.trim();!e||t.has(e)||(t.add(e),n.push(e))}return n}function oo(e){return e?.trim()||io}function so(e){return ao([...Array.isArray(e)?e:[e],io])}function co(e){return so(e)}function lo(e){return oo(e)}function uo(e){if(e.mode===Zt.DESTINATION){let t=e.edgeTradeType??cn.EXACT_INPUT,n={rail:Qt.SOLANA,mode:Zt.DESTINATION,destinationChainId:e.destinationChainId,destinationAddress:e.destinationAddress.trim(),destinationTokenAddress:e.destinationTokenAddress.trim(),tradeType:t,provider:on.RELAY};return t===cn.EXACT_OUTPUT&&e.originTokenAmount!=null&&(n.originTokenAmount=e.originTokenAmount),n}let t=e.edgeTradeType??cn.EXACT_OUTPUT,n={rail:Qt.SOLANA,mode:Zt.ORIGIN,originChainId:it,originAddress:e.solanaAddressBase58.trim(),originTokenAddress:e.originTokenMint.trim(),tradeType:t,provider:e.providerRelayOnly?on.RELAY:void 0};return t===cn.EXACT_INPUT&&e.originTokenAmount!=null&&(n.originTokenAmount=e.originTokenAmount),e.refundAddress?.trim()&&(n.refundAddress=e.refundAddress.trim()),n}function fo(e,t,n){if(n===Zt.DESTINATION){let n={ownerAddress:e.ownerAddress,originChainId:e.originChainId,originTokenAddress:e.originTokenAddress,destinationChainId:0,destinationTokenAddress:vt,options:e.options?{...e.options}:void 0};return t===cn.EXACT_INPUT&&e.originTokenAmount!=null&&(n.originTokenAmount=e.originTokenAmount),t===cn.EXACT_OUTPUT&&e.destinationTokenAmount!=null&&(n.destinationTokenAmount=e.destinationTokenAmount),n}let r={ownerAddress:e.ownerAddress,originChainId:0,originTokenAddress:vt,destinationChainId:e.destinationChainId,destinationTokenAddress:e.destinationTokenAddress,destinationToAddress:e.destinationToAddress,destinationApproveAddress:e.destinationApproveAddress,destinationCallData:e.destinationCallData,destinationCallValue:e.destinationCallValue,options:e.options?{...e.options}:void 0};return t===cn.EXACT_OUTPUT&&(r.destinationTokenAmount=e.destinationTokenAmount),r}function po(e){return{intent:e.inner,edge:e.edge}}function mo(e){if(e)switch(e.rail){case kt.SOLANA:return{solana:e};default:return}}function ho(e,t){switch(t){case kt.SOLANA:return e?.solana;default:return}}function go(e,t){switch(e.rail){case kt.SOLANA:return uo({mode:Zt.ORIGIN,solanaAddressBase58:e.signerPublicKeyBase58,originTokenMint:t.originTokenMint,edgeTradeType:t.edgeTradeType,originTokenAmount:t.originTokenAmount,refundAddress:t.refundAddress,providerRelayOnly:t.providerRelayOnly});default:throw Error(`[trails-sdk] Unsupported edge origin rail: ${e.rail}`)}}function _o(e,t){if(!At(e))throw Error(`[trails-sdk] Unsupported edge destination rail: ${e.rail}`);return uo({mode:Zt.DESTINATION,destinationChainId:e.chainId,destinationAddress:e.recipient,destinationTokenAddress:t.destinationTokenAddress,edgeTradeType:t.edgeTradeType,originTokenAmount:t.originTokenAmount})}const vo={queries:{staleTime:5*Ee,gcTime:5*ge,retry:2,retryDelay:De,refetchOnWindowFocus:!1,refetchIntervalInBackground:!1,refetchOnReconnect:!0}},yo=new xr({defaultOptions:vo});function bo({hasWalletContext:e,hasWidgetAdapterProvider:t=!1}){return e?`parent`:t?`adapter`:`builtin-evm`}function xo({hasWalletContext:e,hasWidgetAdapterProvider:t=!1}){return J(()=>bo({hasWalletContext:e,hasWidgetAdapterProvider:t}),[e,t])}const So=ur(null);function Co({children:e,props:t}){return Z(So.Provider,{value:{props:t},children:e})}function wo(){let e=hr(So);if(!e)throw Error(`useWidgetProps must be used within a WidgetPropsProvider`);return e.props}function To(e){let t=e.fromToken?.trim(),n=e.fromChainId==null?null:typeof e.fromChainId==`string`?Number(e.fromChainId):e.fromChainId;return!!(t||n!=null&&n>0&&Number.isFinite(n))}const Eo=ur(`none`);function Do({mode:e,children:t}){return or.createElement(Eo.Provider,{value:e,children:t})}function Oo(){return hr(Eo)}function ko(e,t){return e===`none`?!1:e===`adapter`||e===`parent`?t??!0:!0}function Ao(){return ko(Oo(),ei()?.supportsWidgetWalletSelection)}let jo=null,Mo=null,No=null,Po=!1;function Fo(e){jo=e}function Io(e){Mo=e}function Lo(e){No=e}function Ro(e){Po=e}function zo(e,t,n,r,i){Po&&(jo?jo(e,t,n,r,i):console.warn(`[trails-sdk] Toast not available yet. Make sure ToastProvider is mounted.`))}function Bo(e,t,n,r){Po&&(Mo?Mo(e,t,n,r):console.warn(`[trails-sdk] Toast not available yet. Make sure ToastProvider is mounted.`))}function Vo(){Po&&(No?No():console.warn(`[trails-sdk] Toast not available yet. Make sure ToastProvider is mounted.`))}const Ho=`https://trails.build/web-app-manifest-192x192.png`,Uo={success:3*Ee,error:5*Ee,info:5*Ee},Wo=ur(null);function Go(){let e=hr(Wo);if(!e)throw Error(`useToast must be used within ToastProvider`);return e}const Ko=`persistent-toast`;function qo({children:e}){let[t,n]=X([]),{toast:r=!1}=wo();q(()=>{Ro(r)},[r]);let i=K((e,t,i=`info`,a,o)=>{if(!r)return;let s=a??Uo[i],c=o??Ho,l=`toast-${Date.now()}-${Math.random()}`,u={id:l,title:e,message:t,type:i,duration:s,iconUrl:c};n(e=>[...e,u]),s>0&&setTimeout(()=>{n(e=>e.filter(e=>e.id!==l))},s)},[r]),a=K((e,t,i=`info`,a)=>{if(!r)return;let o={id:Ko,title:e,message:t,type:i,duration:0,iconUrl:a??Ho,isPersistent:!0};n(e=>[...e.filter(e=>e.id!==Ko),o])},[r]),o=K(()=>{n(e=>e.filter(e=>e.id!==Ko))},[]),s=K(e=>{n(t=>t.filter(t=>t.id!==e))},[]);return q(()=>{Fo(i)},[i]),q(()=>{Io(a)},[a]),q(()=>{Lo(o)},[o]),Q(Wo.Provider,{value:{toasts:t,showToast:i,updatePersistentToast:a,removePersistentToast:o,removeToast:s},children:[e,Z(Jo,{toasts:t,onRemove:s})]})}function Jo({toasts:e,onRemove:t}){let n=Y(null),[r,a]=X(null),{isDark:o}=ue();q(()=>{if(n.current&&!n.current.shadowRoot){let e=n.current.attachShadow({mode:`open`});a(e);let t=e;if(t.adoptedStyleSheets!==void 0){let e=new CSSStyleSheet;e.replaceSync(i),t.adoptedStyleSheets=[e]}else{let t=document.createElement(`style`);t.textContent=i,e.appendChild(t)}}},[]);let s=Z(`div`,{className:`fixed top-4 right-4 z-[9999] flex flex-col gap-2 pointer-events-none ${o?`dark`:``}`,children:e.map(e=>Z(Yo,{toast:e,onRemove:t},e.id))});return Z(`div`,{ref:n,style:{position:`fixed`,top:0,right:0,zIndex:99999},children:r?Ar(s,r):null})}function Yo({toast:e,onRemove:t}){let n=()=>{switch(e.type){case`success`:return Z(Ei,{className:`w-5 h-5 text-green-600 dark:text-green-400`});case`error`:return Z(gi,{className:`w-5 h-5 text-red-600 dark:text-red-400`});case`info`:return Z(Vi,{className:`w-5 h-5 text-blue-600 dark:text-blue-400`});default:return Z(Vi,{className:`w-5 h-5 text-blue-600 dark:text-blue-400`})}},r=e.isPersistent;return Z(`div`,{className:`pointer-events-auto trails-fade-slide-in`,children:Z(`div`,{className:`bg-white/95 dark:bg-gray-900/95 backdrop-blur-xl [box-shadow:0_10px_25px_-5px_rgba(0,0,0,0.08),0_8px_10px_-6px_rgba(0,0,0,0.08)] p-4 min-w-[340px] max-w-md border border-gray-200/50 dark:border-gray-700/50 [border-radius:var(--trails-widget-border-radius,16px)] ${r?`ring-2 ring-blue-500/20 dark:ring-blue-400/20`:``}`,children:Q(`div`,{className:`flex items-start gap-3`,children:[e.iconUrl&&Z(`div`,{className:`flex-shrink-0`,children:Z(`img`,{src:e.iconUrl,alt:`App Icon`,className:`w-10 h-10 rounded-xl shadow-sm`,onError:e=>{e.currentTarget.style.display=`none`}})}),Q(`div`,{className:`flex-1 min-w-0`,children:[Q(`div`,{className:`flex items-center gap-2 mb-0.5`,children:[Z(`div`,{className:`flex-shrink-0`,children:n()}),Z(`h4`,{className:`text-sm font-semibold text-gray-900 dark:text-white leading-snug`,children:e.title})]}),Z(`p`,{className:`text-sm text-gray-600 dark:text-gray-300 leading-relaxed`,children:e.message}),e.type===`error`&&Z(`a`,{href:`https://support.trails.build/`,target:`_blank`,rel:`noopener noreferrer`,className:`mt-2 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline inline-block`,children:`Visit support`})]}),Z(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex-shrink-0 text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition-colors rounded-full p-1 hover:bg-gray-100 dark:hover:bg-gray-800 cursor-pointer`,children:Z(ra,{className:`w-4 h-4`})})]})})})}const Xo=ur(null),Zo={purpose:`general`,originScreen:null,connectedWalletAddress:null,originalActiveWalletAddress:null,originalActiveConnectionId:null};function Qo({children:e}){let[t,n]=X(Zo),r={connectionContext:t,setConnectionContext:K((e,t,r,i)=>{s.console.log(`[trails-sdk] Setting wallet connection context:`,{purpose:e,originScreen:t,originalActiveWalletAddress:r,originalActiveConnectionId:i}),n({purpose:e,originScreen:t||null,connectedWalletAddress:null,originalActiveWalletAddress:r||null,originalActiveConnectionId:i||null})},[]),setConnectedWalletAddress:K(e=>{s.console.log(`[trails-sdk] Setting connected wallet address:`,e),n(t=>({...t,connectedWalletAddress:e}))},[]),clearConnectionContext:K(()=>{s.console.log(`[trails-sdk] Clearing wallet connection context`),n(Zo)},[]),isRecipientSelection:t.purpose===`recipient-selection`,isFundMethodSelection:t.purpose===`fund-method-selection`};return Z(Xo.Provider,{value:r,children:e})}function $o(){let e=hr(Xo);if(!e)throw Error(`useWalletConnectionContext must be used within a WalletConnectionProvider`);return e}const es=`trails-sdk:custom-tokens:01`;function ts(){if(typeof window>`u`)return[];try{let e=localStorage.getItem(es);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>{let t=e&&typeof e.contractAddress==`string`&&typeof e.symbol==`string`&&typeof e.name==`string`&&typeof e.decimals==`number`;return t||s.console.warn(`[trails-sdk] Invalid custom token found, skipping:`,e),t}):(s.console.warn(`[trails-sdk] Invalid custom tokens format in localStorage, clearing`),localStorage.removeItem(es),[])}catch(e){s.console.error(`[trails-sdk] Error reading custom tokens from localStorage:`,e);try{localStorage.removeItem(es)}catch{}return[]}}function ns(e){if(!(typeof window>`u`))try{localStorage.setItem(es,JSON.stringify(e))}catch(e){s.console.error(`[trails-sdk] Error saving custom tokens to localStorage:`,e),e instanceof DOMException&&e.name===`QuotaExceededError`&&s.console.warn(`[trails-sdk] localStorage quota exceeded, cannot save custom tokens`)}}function rs(){let[e,t]=X(()=>ts());return{customTokens:e,addCustomToken:K(e=>{t(t=>{let n=G(e),r=t.findIndex(e=>G(e)===n),i={...e,isCustomToken:!0},a;if(r>=0){let e=t[r];if(!e||e.symbol===i.symbol&&e.name===i.name&&e.decimals===i.decimals&&(e.chainId||0)===(i.chainId||0)&&ft(e.contractAddress,i.contractAddress,i.chainId||0)&&e.chainName===i.chainName&&e.imageUrl===i.imageUrl&&e.isCustomToken===!0)return t;a=[...t],a[r]=i}else a=[...t,i];return ns(a),a})},[]),removeCustomToken:K((e,n)=>{t(t=>{let r=t.filter(t=>t.chainId!==e||!ft(t.contractAddress,n,e));return ns(r),r})},[]),clearCustomTokens:K(()=>{t([]),ns([])},[])}}function is(e){return typeof e==`object`&&!!e&&`status`in e&&e.status===404}const as=new Set([`network error`,`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`The Internet connection appears to be offline.`,`Network request failed`,`fetch failed`,`terminated`,` A network error occurred.`,`Network connection lost`]);function os(e){if(!(e instanceof Error&&e.name===`TypeError`&&typeof e.message==`string`))return!!(e instanceof Error&&e.name===`FetchError`&&/request to .+ failed/i.test(e.message));let{message:t}=e;return t===`Load failed`?e.stack===void 0:t.startsWith(`error sending request for url`)?!0:as.has(t)}const ss=e=>(t,n)=>!is(n)&&t<e,cs={refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1},ls=`__trails_bigint__`;function us(e){return!!(e&&typeof e==`object`&&`__type`in e&&`value`in e&&e.__type===ls)}function ds(e){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?{__type:ls,value:t.toString()}:t)}function fs(e){return JSON.parse(e,(e,t)=>us(t)?BigInt(t.value):t)}const ps=oa({storage:typeof window<`u`?window.localStorage:void 0,maxAge:Te,prefix:`trails-query`,serialize:ds,deserialize:fs});var ms=class extends un{};function hs({apiKey:e,jwt:t,hostname:n}){return new ms(e,{jwt:t,hostname:n})}const gs=e=>{let t=Vx();return J(()=>hs({apiKey:e?.apiKey||t.trailsApiKey||``,hostname:e?.hostname||t.trailsApiUrl,jwt:e?.jwt}),[e?.hostname,e?.apiKey,e?.jwt,t])};function _s(e){return Number.isFinite(e)}function vs(e){return Number.isFinite(e)&&e>0}function ys(e){return Number.isFinite(e)&&e>=0}function bs(e){if(e==null)return 0;let t=Number(e);return Number.isFinite(t)?t:0}function xs(e){return Number.isInteger(e)&&e>0&&e<=18}function Ss(e){if(!e||e===``)return!1;let t=Number(e);return Number.isFinite(t)&&t>0}function Cs(e){try{return BigInt(e)>0n}catch{return!1}}function ws(e){return Cs(e.balance||`0`)}function Ts(e){if(e==null||e===``)return!0;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)}function Es(e){if(e==null||e===``)return!0;let t=String(e).trim();return/^\d+$/.test(t)}const Ds=e=>{let t=!1,n=!1,r=!1;for(let i=0;i<e.length;i+=1){let a=e.charCodeAt(i);if(a>=48&&a<=57){t=!0,n&&(r=!0);continue}if(a===46&&!n){n=!0;continue}return!1}return t&&(!n||r)};function Os(e,t){if(typeof e==`bigint`)return e.toString();let n=e.trim();if(!/^\d+$/.test(n))throw Error(`[trails-sdk] ${t} must be a positive bigint or integer-only numeric string in the token's smallest unit (e.g. 1000000n or "1000000"). Got: ${JSON.stringify(e)}`);return n}const ks=e=>{if(e==null)return!1;if(typeof e==`bigint`)return e>0n;let t=e.trim();return t===``||!Ds(t)?!1:Number(t)>0};function As(e){let t=e.replace(/\s/g,``),n=t.lastIndexOf(`,`),r=t.lastIndexOf(`.`);if(n>r&&n!==-1){let e=t.slice(n+1);if(e.length===3&&/^\d+$/.test(e))return r!==-1&&r<n;if(e.length>0&&/^\d+$/.test(e))return!0}if(r!==-1&&n===-1){let e=t.slice(r+1),n=t.slice(0,r);if(e.length===3&&/^\d+$/.test(e))return!!(n.length>=4&&/^\d+$/.test(n))}return!1}function js(){return typeof navigator<`u`&&navigator.language?navigator.language:`en-US`}function Ms(){let e=js();return[`de`,`fr`,`es`,`it`,`pt`,`nl`,`pl`,`ru`,`tr`,`sv`,`da`,`no`,`fi`,`cs`,`hu`,`ro`,`bg`,`hr`,`sk`,`sl`].some(t=>e.toLowerCase().startsWith(t))}function Ns(e,t){if(e==null||e===``)return 0;if(typeof e==`number`)return e;let n=e.toString().trim();n=n.replace(/[$€£¥₹¢]/g,``),n=n.trim();let r=n.startsWith(`-`)||n.startsWith(`(`);n=n.replace(/[()-]/g,``);let i=t?Ms():As(n),a;i?(a=n.replace(/[\s.]/g,``),a=a.replace(`,`,`.`)):a=n.replace(/,/g,``);let o=parseFloat(a);return r?-o:o}const Ps=`trails-forex-rate`,Fs=30*ge,Is=()=>typeof window<`u`&&typeof localStorage<`u`&&typeof localStorage.getItem==`function`&&typeof localStorage.setItem==`function`&&typeof localStorage.removeItem==`function`;var Ls=class e{constructor(){me(this,`currentRate`,null),this.loadFromStorage()}static getInstance(){return e.instance||(e.instance=new e),e.instance}loadFromStorage(){try{if(Is()){let e=localStorage.getItem(Ps);if(e){let t=JSON.parse(e);Date.now()-t.timestamp<Fs?this.currentRate=t:localStorage.removeItem(Ps)}}}catch(e){console.warn(`Failed to load forex rate from localStorage:`,e)}}setRate(e,t){let n={currency:e,rate:t,timestamp:Date.now()};this.currentRate=n;try{Is()&&localStorage.setItem(Ps,JSON.stringify(n))}catch(e){console.warn(`Failed to save forex rate to localStorage:`,e)}}getRate(){return this.currentRate?Date.now()-this.currentRate.timestamp>Fs?(this.clearRate(),null):{currency:this.currentRate.currency,rate:this.currentRate.rate}:null}clearRate(){this.currentRate=null;try{Is()&&localStorage.removeItem(Ps)}catch(e){console.warn(`Failed to clear forex rate from localStorage:`,e)}}convertFromUsd(e){let t=this.getRate();return!t||t.currency===`USD`?null:e*t.rate}};me(Ls,`instance`,void 0);const Rs=Ls.getInstance();function zs(){return`en-US`}function Bs(e,t,n,r,i){e||(e=0);let a;if(a=typeof e==`string`?parseFloat(e):Number(e),Number.isNaN(a))return s.console.warn(`[trails-sdk] formatNumber: Invalid number`,e),String(e);try{return a.toLocaleString(t,{maximumFractionDigits:r,minimumFractionDigits:i,useGrouping:n})}catch(e){s.console.error(`[trails-sdk] Error formatting value:`,e)}return e.toString()}function Vs(e,t){if(!e)return null;if(!Number.isInteger(t)||t<0||t>255)throw Error(`Invalid decimals`);let n=BigInt(e);if(n<0n)throw Error(`Negative balance`);return vn(n,t)}function Hs(e){e||(e=0);let t=Number(e);return!Number.isFinite(t)||Number.isNaN(t)?null:{isNegative:t<0,cappedValue:Math.min(Math.abs(t),0x5af3107a4000)}}function Us(e,{maxFractionDigits:t=8,minFractionDigits:n=2}={}){return Bs(e,`en-US`,!1,t,n)}function Ws(e,{maxFractionDigits:t=8,minFractionDigits:n=2}={}){return Bs(e,void 0,!0,t,n)}function Gs(e,{maxFractionDigits:t=8,minFractionDigits:n=2}={}){return Bs(e,zs(),!0,t,n)}function Ks(e=0){let t=Hs(e);if(!t)return`$0.00`;let{isNegative:n,cappedValue:r}=t,i=n?-r:r;if(r>0&&r<.01){let e=Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:3,minimumFractionDigits:3}).format(i);return e===`$0.000`?`<$0.01`:e}return Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:2,minimumFractionDigits:2}).format(i)}function qs(e=0){let t=zs(),n=Hs(e);if(!n)return new Intl.NumberFormat(t,{style:`currency`,currency:`USD`}).format(0);let{isNegative:r,cappedValue:i}=n,a=`USD`,o=i,s=Rs.getRate();s&&s.currency!==`USD`&&(a=s.currency,o=i*s.rate);let c=[`JPY`,`KRW`,`VND`,`CLP`,`ISK`].includes(a)?0:2,l=r?-o:o,u=a===`USD`?.01:10**-c;if(o>0&&o<u){let e=Math.max(3,c+1),n=new Intl.NumberFormat(t,{style:`currency`,currency:a,maximumFractionDigits:e,minimumFractionDigits:e}).format(l);return n===new Intl.NumberFormat(t,{style:`currency`,currency:a,maximumFractionDigits:e,minimumFractionDigits:e}).format(0)?new Intl.NumberFormat(t,{style:`currency`,currency:a,maximumFractionDigits:c,minimumFractionDigits:c}).format(u).replace(/[0-9.,]+/,e=>`<${e}`):n}return new Intl.NumberFormat(t,{style:`currency`,currency:a,maximumFractionDigits:c,minimumFractionDigits:c}).format(l)}function Js(e=0){let t=Hs(e);if(!t)return`0.00`;let{isNegative:n,cappedValue:r}=t;if(r>0&&r<.01){let e=r.toLocaleString(`en-US`,{maximumFractionDigits:3,minimumFractionDigits:3,useGrouping:!1});return n?`-${e}`:e}let i=r.toLocaleString(`en-US`,{maximumFractionDigits:2,minimumFractionDigits:2,useGrouping:!1});return n?`-${i}`:i}function Ys(e,t){try{let n=Vs(e,t);return n===null?0:Number(n)}catch(n){return s.console.error(`[trails-sdk] Error converting balance:`,{balance:e,decimals:t,err:n}),0}}function Xs(e,t){if(!e)return`0`;try{let n=Vs(e,t);return n===null?`0`:Us(n)}catch(n){throw s.console.error(`[trails-sdk] Error formatting balance:`,{balance:e,decimals:t,err:n}),n}}function Zs(e,t){let n=!(`contractAddress`in e)||e.contractAddress===Cn,r=n?18:e.contractInfo?.decimals;if(!r)return s.console.error(`[trails-sdk] [getTokenBalanceUsd] Missing decimals for token:`,{token:e,isNative:n}),0;let i=Xs(e.balance,r),a=Number(t.value)||0;if(!Number.isFinite(a)||Number.isNaN(a)||a<0)return 0;let o=Number(i);if(!Number.isFinite(o)||Number.isNaN(o)||o<0)return 0;let c=o*a;return!Number.isFinite(c)||Number.isNaN(c)?(s.console.error(`[trails-sdk] Error calculating balance USD:`,{balanceNum:o,priceUsd:a,result:c,token:e,tokenPrice:t}),0):c}function Qs(e,t){if(!e)return{balance:`0`,balanceFormatted:`0`,balanceDisplay:`0`,balanceLocaleDisplay:`0`};try{let n=Vs(e,t);return n===null?{balance:`0`,balanceFormatted:`0`,balanceDisplay:`0`,balanceLocaleDisplay:`0`}:{balance:BigInt(e).toString(),balanceFormatted:Us(n),balanceDisplay:Ws(n),balanceLocaleDisplay:Gs(n)}}catch(n){return s.console.error(`[trails-sdk] Error formatting balance fields:`,{balance:e,decimals:t,err:n}),{balance:typeof e==`string`?e:e.toString(),balanceFormatted:`0`,balanceDisplay:`0`,balanceLocaleDisplay:`0`}}}function $s(e){if(e==null)return{};let t=Number(e);return!Number.isFinite(t)||Number.isNaN(t)?{balanceUsd:0,balanceUsdFormatted:`0.00`,balanceUsdDisplay:`$0.00`,balanceUsdLocaleDisplay:qs(0)}:{balanceUsd:t,balanceUsdFormatted:Js(t),balanceUsdDisplay:Ks(t),balanceUsdLocaleDisplay:qs(t)}}function ec(e){let t=$s(e);return{priceUsd:t.balanceUsd,priceUsdFormatted:t.balanceUsdFormatted,priceUsdDisplay:t.balanceUsdDisplay}}function tc(e){if(e==null)return 0;if(typeof e==`number`)return _s(e)?e:(s.console.error(`[trails-sdk] Invalid number value:`,e),0);let t=Ns(e);return _s(t)?t:(s.console.error(`[trails-sdk] Error normalizing number string:`,{number:e,normalized:t}),0)}function nc({amount:e,usdPrice:t}){let n=tc(e),r=tc(t);if(!ys(n)||!ys(r))return 0;let i=n*r;return _s(i)?i:(s.console.error(`[trails-sdk] Error calculating amount USD:`,{sanitizedAmount:n,sanitizedPrice:r,result:i,amount:e,usdPrice:t}),0)}function rc(e){return e>=1e9?`$${(e/1e9).toFixed(1)}B`:e>=1e6?`$${(e/1e6).toFixed(1)}M`:e>=1e3?`$${(e/1e3).toFixed(1)}K`:`$${e.toFixed(0)}`}const ic={all:[`chains`],supported:e=>wr({queryKey:[...ic.all,`supported`],queryFn:()=>qa(e),staleTime:Oe,gcTime:Te,...cs})};async function ac(e,t){return await e.getTokenList(t)}function oc(e,t){let n=$(e.chainId),r=bt(e.address,e.chainId),i=r&&n?.nativeCurrency.symbol||e.symbol,a=r&&n?.nativeCurrency.name||e.name,o=r?n?.nativeCurrency.decimals??18:Math.max(0,Math.min(18,Math.floor(e.decimals??18))),s=r?Ct(e.chainId):e.address,c={symbol:i,name:a,decimals:o,contractAddress:s,tokenId:`${i}-${n?.name||`chain-${e.chainId}`}`,chainId:e.chainId,chainName:n?.name||`Chain ${e.chainId}`,imageUrl:e.logoUri||Oc({chainId:e.chainId,contractAddress:s,symbol:i}),isNativeToken:r};if(t?.balance){let e=Qs(t.balance,o);c.balance=e.balance,c.balanceFormatted=e.balanceFormatted,c.balanceDisplay=e.balanceDisplay}if(t?.priceUsd!==void 0){let e=ec(t.priceUsd);c.priceUsd=e.priceUsd,c.priceUsdFormatted=e.priceUsdFormatted,c.priceUsdDisplay=e.priceUsdDisplay}return c}function sc(e){return e in Ve}function cc(e){return sc(e)?Ve[e]:e}function lc(e){return e in Ge}const uc=7*Te,dc=`trails-sdk:token-info-cache:01`,fc=Te,pc=new Map;function mc(){if(typeof window>`u`)return{};try{let e=localStorage.getItem(dc);if(!e)return{};let t=JSON.parse(e),n=Date.now(),r=Object.entries(t).filter(([e,t])=>n-t.timestamp<fc);return Object.fromEntries(r)}catch{return{}}}function hc(e,t){if(!(typeof window>`u`))try{let n=mc();if(!t.chainId){s.console.warn(`[trails-sdk] Cannot cache token without chainId:`,t);return}let r={tokenId:t.tokenId,symbol:t.symbol,name:t.name,contractAddress:t.contractAddress,decimals:t.decimals,chainId:t.chainId,chainName:t.chainName,imageUrl:t.imageUrl,isNativeToken:t.isNativeToken,isCustomToken:t.isCustomToken,timestamp:Date.now()};n[e]=r,localStorage.setItem(dc,JSON.stringify(n)),pc.set(e,r)}catch(e){s.console.warn(`[trails-sdk] Failed to cache token info:`,e)}}function gc(e,t){let n=Ke(e,t),r=pc.get(n);if(r)return{symbol:r.symbol,name:r.name,decimals:r.decimals,contractAddress:r.contractAddress,tokenId:r.tokenId,chainId:r.chainId,chainName:r.chainName,imageUrl:r.imageUrl,isNativeToken:r.isNativeToken,isCustomToken:r.isCustomToken};let i=mc()[n];return i?(pc.set(n,i),{symbol:i.symbol,name:i.name,decimals:i.decimals,contractAddress:i.contractAddress,tokenId:i.tokenId,chainId:i.chainId,chainName:i.chainName,imageUrl:i.imageUrl,isNativeToken:i.isNativeToken,isCustomToken:i.isCustomToken}):null}function _c(){if(typeof window>`u`)return{};try{let e=localStorage.getItem(`trails-sdk:token-image-cache:01`);if(!e)return{};let t=JSON.parse(e),n=Date.now(),r=Object.entries(t).filter(([e,t])=>n-t.timestamp<uc);return Object.fromEntries(r)}catch{return{}}}const vc=[`ETH`,`WETH`,`AVAX`,`WAVAX`,`xDAI`,`POL`,`USDC`,`USDT`,`DAI`,`MATIC`,`ARB`,`OP`,`BAT`,`WBTC`,`cbBTC`,`XAI`];function yc(e){return e.sort((e,t)=>{let n=vc.indexOf(e.symbol),r=vc.indexOf(t.symbol);if(n!==-1&&r!==-1)return n-r;if(n!==-1)return-1;if(r!==-1)return 1;let i=!!e.imageUrl,a=!!t.imageUrl;if(i&&!a)return-1;if(!i&&a)return 1;let o=e.symbol.localeCompare(t.symbol);if(o!==0)return o;let s=e.chainName||``,c=t.chainName||``;return s.localeCompare(c)})}function bc(e,t,n){let r=`${e}:${t}:${n}`;return _c()[r]?.imageUrl||``}async function xc(e){let t=(await(e.queryClient??yo).ensureQueryData(ic.supported({trailsApiUrl:e.trailsApiUrl,trailsApiKey:e.trailsApiKey}))).map(e=>e.id),n=hs({apiKey:e.trailsApiKey||``,hostname:e.trailsApiUrl}),r=[];if(e.trailsApiKey&&n&&t.length>0){let e=t.length===1?100:30;for(let i=1;i<=3;i++)try{r=((await ac(n,{chainIds:t,includeAllListed:!0,limit:e})).tokens||[]).filter(e=>xs(e.decimals)?!0:(s.console.warn(`[trails-sdk] Skipping token with invalid decimals:`,{symbol:e.symbol,address:e.address,decimals:e.decimals}),!1)).map(e=>oc(e));break}catch(e){s.console.warn(`[trails-sdk] Error fetching tokens from trails-api (attempt ${i}/3):`,e),i===3&&(r=[])}}for(let e of r)e.imageUrl=Oc({chainId:e.chainId||0,contractAddress:e.contractAddress,symbol:e.symbol})||e.imageUrl;let i=qe.filter(e=>!r.some(t=>t.chainId===e.chainId&&Pe(t.contractAddress,e.contractAddress)));return yc([...r,...i].filter(e=>e.chainId===zn.id?!0:e.chainId&&t.includes(e.chainId)).filter((e,t,n)=>t===n.findIndex(t=>t.chainId===e.chainId&&Pe(t.contractAddress,e.contractAddress))))}Yn.id,Tn.id,Zn.id,zn.id;async function Sc(e,t,n){if(W(e)){let n=gc(e,t);if(n)return n;let r=Be(t);return r?(hc(`${e}:${t}`,r),r):null}let r=St(t),i=gc(e,r);if(i)return i;let a=$(e);if(!a)return s.console.warn(`[trails-sdk] Chain info not found for chainId: ${e}`),null;if(bt(t,e)){let n=Ct(e),r=a.nativeCurrency.decimals??18,i=a.nativeCurrency.symbol||`Unknown`,o={tokenId:`${i}-${a.name||`Unknown`}`,symbol:i,name:a.nativeCurrency.name||`Unknown`,contractAddress:n,decimals:r,chainId:e,chainName:a.name||`Unknown`,imageUrl:Oc({chainId:e,contractAddress:n,symbol:i}),isNativeToken:!0};return hc(Ke(e,t),o),o}let o=(await xc({trailsApiKey:n.trailsApiKey,trailsApiUrl:n.trailsApiUrl,queryClient:n.queryClient})).find(t=>t.chainId===e&&t.contractAddress?.toLowerCase()===r);if(o)return o.imageUrl=Oc({chainId:e,contractAddress:r,symbol:o.symbol}),hc(Ke(e,t),o),o;try{let{contractInfo:i}=await new sa(n.sequenceMetadataUrl,n.trailsApiKey).getContractInfo({chainID:String(e),contractAddress:r});if(i.deployed!==!0)throw Error(`Token at ${r} on chain ${e} is not deployed`);if(i.decimals==null)throw Error(`Token at ${r} on chain ${e} has no decimals`);let o={tokenId:`${i.symbol}-${a.name}`,name:i.name,symbol:i.symbol,decimals:i.decimals,chainId:e,contractAddress:r,chainName:a.name,imageUrl:Oc({chainId:e,contractAddress:r,symbol:i.symbol}),isCustomToken:!0};return hc(Ke(e,t),o),s.console.log(`[trails-sdk] Fetched token info from metadata service:`,o),o}catch(e){s.console.warn(`[trails-sdk] Metadata service failed, falling back to on-chain:`,e)}if(W(e))return null;try{let n=Va(e),[i,o,c]=await Promise.all([n.readContract({address:r,abi:_n,functionName:`name`}),n.readContract({address:r,abi:_n,functionName:`symbol`}),n.readContract({address:r,abi:_n,functionName:`decimals`})]),l={tokenId:`${o}-${a.name}`,name:i,symbol:o,decimals:c,chainId:e,contractAddress:r,chainName:a.name,imageUrl:Oc({chainId:e,contractAddress:r,symbol:o}),isCustomToken:!0};return hc(Ke(e,t),l),s.console.log(`[trails-sdk] Fetched token info on-chain:`,l),l}catch(e){return s.console.error(`[trails-sdk] Error fetching on-chain token info:`,e),null}}async function Cc(e,t){let n=St(e),{contractInfoList:r}=await new sa(t.sequenceMetadataUrl,t.trailsApiKey).findContractInfo({contractAddress:n});return(r||[]).filter(e=>e.deployed===!0&&e.decimals!=null&&e.decimals>0).map(e=>{let t=St(e.address),n=$(e.chainId),r={tokenId:`${e.symbol}-${n?.name||`chain-${e.chainId}`}`,symbol:e.symbol,name:e.name,decimals:e.decimals,chainId:e.chainId,contractAddress:t,chainName:n?.name||`Chain ${e.chainId}`,imageUrl:e.logoURI||Oc({chainId:e.chainId,contractAddress:t,symbol:e.symbol}),isCustomToken:!0};return hc(Ke(e.chainId,e.address),r),r})}const wc={"BNB-USD":`USDT`};async function Tc(e,t,n){let r=$(e),i=t.trim().toUpperCase(),a=r?.nativeCurrency?.symbol;if(a&&i===a.toUpperCase())return Ct(e);let o=await xc(n),s=o.find(t=>t.symbol.trim().toUpperCase()===i&&t.chainId===e);if(!s){let t=wc[i];t&&(s=o.find(n=>n.symbol.trim().toUpperCase()===t.toUpperCase()&&n.chainId===e))}if(s?.contractAddress)return s.contractAddress;throw Error(`Unsupported token symbol: ${t} for chainId: ${e}`)}function Ec({symbol:e,contractAddress:t,chainId:n}){if(e){let t=cc(e);if(lc(t))return Ge[t]}if(t&&n){let e=qe.find(e=>e.chainId===n&&ft(e.contractAddress,t,n));if(e){let t=cc(e.symbol);if(lc(t))return Ge[t]}}return``}function Dc({chainId:e,contractAddress:t,fallbackImageUrl:n,sequenceMetadataUrl:r}){let i=r||`https://metadata.sequence.app`,a=n?`?fallback=${encodeURIComponent(n)}`:`?happy=true`;return`${i}/tokens/${e}/${W(e)?t:St(t)}/image${a}`}function Oc({chainId:e,contractAddress:t,symbol:n}){if(!e||!t||!n)return``;let r=bc(e,t,n);if(r)return r;if(n){let r=Ec({symbol:n,contractAddress:t,chainId:e});if(r)return r}return`https://assets.sequence.info/images/tokens/large/${e}/${e&&W(e)?t:St(t)}.webp`}const kc=[`tokens`],Ac={staleTime:Te,gcTime:Te,retry:ss(2),retryDelay:De,...cs,persister:ps.persisterFn};function jc(e){return[e?.trailsApiUrl??null,!!e?.trailsApiKey,e?.sequenceMetadataUrl??null]}function Mc(e){return[...e].sort((e,t)=>e-t)}function Nc({trailsClient:e,apiKey:t,scope:n,keyParts:r,params:i,staleTime:a=Te,gcTime:o=Te,retry:s=ss(2)}){let c=Mc(i.chainIds),l=i.searchQuery?.trim(),u=!!(e&&t&&c.length>0&&(l===void 0||l.length>0));return wr({queryKey:[...kc,n,...r],queryFn:u?()=>ac(e,{...i,chainIds:c,...l===void 0?{}:{searchQuery:l}}):Tr,staleTime:a,gcTime:o,retry:s,retryDelay:De,...cs})}const Pc={all:kc,supportedList:e=>{let t=!!(e?.trailsApiKey&&e?.trailsApiUrl);return wr({queryKey:[...kc,`supported`,jc(e)],queryFn:t?({client:t})=>xc({...e,queryClient:t}):Tr,...Ac})},search:(e,t,n)=>{let r=Mc(n.chainIds),i=n.searchQuery.trim(),a=n.limit??30;return Nc({trailsClient:e,apiKey:t,scope:`search`,keyParts:[i,r.join(`,`),a],params:{searchQuery:i,chainIds:r,includeAllListed:!0,limit:a},staleTime:30*Ee,gcTime:5*ge,retry:ss(1)})},byChain:(e,t,n)=>{let r=n.limit??100;return Nc({trailsClient:e,apiKey:t,scope:`byChain`,keyParts:[n.chainId??null,r],params:{chainIds:n.chainId==null?[]:[n.chainId],includeAllListed:!0,limit:r}})},address:(e,t,n)=>{let r=t?.trim()||null,i=!!(e&&r&&n?.trailsApiKey);return wr({queryKey:[...kc,`address`,e??null,r,jc(n)],queryFn:i?({client:t})=>Tc(e,r,{...n,queryClient:t}):Tr,...Ac})},info:(e,t,n)=>{let r=t&&bn(t)?St(t):null,i=!!(e&&r);return wr({queryKey:[...kc,`info`,e??null,r,jc(n)],queryFn:i?({client:t})=>Sc(e,r,{trailsApiKey:n?.trailsApiKey??``,trailsApiUrl:n?.trailsApiUrl??``,sequenceMetadataUrl:n?.sequenceMetadataUrl??``,queryClient:t}):Tr,...Ac})}};async function Fc(e,t,n){return!e||!t||!bn(t)||!n?null:yo.ensureQueryData(Pc.info(e,t,n))}const Ic=[];function Lc(e,t,n){let r=new Map;for(let t of e)r.set(G(t),t);for(let e of t){let t=G(e);r.has(t)||r.set(t,e)}let i=Array.from(r.values());return n?i.filter(e=>e.chainId===n):i}function Rc({chainId:e,disabled:t=!1}={}){let{customTokens:n}=rs(),r=Vx(),i=Or({...Pc.supportedList(t?null:r),select:t=>Lc(t,n,e)});return{supportedTokens:i.data??Ic,isLoadingTokens:i.isLoading,refetch:async()=>{t||await i.refetch()}}}function zc({chainId:e,tokenSymbol:t}){let n=Vx();return Or(Pc.address(e,t,n)).data??null}function Bc(){let{supportedTokens:e,isLoadingTokens:t}=Rc();return{tokens:e,isLoadingTokens:t}}function Vc(){return J(()=>({getTokenImageUrl:Oc}),[])}function Hc(){let{sequenceMetadataUrl:e}=Vx();return J(()=>({getSequenceMetadataTokenImageUrl:t=>Dc({...t,sequenceMetadataUrl:e})}),[e])}function Uc({address:e,chainId:t}){let n=Vx(),r=Or(Pc.info(t,e,n));return{tokenInfo:r.data??null,isLoading:r.isLoading,error:r.error??null}}function Wc(e){return{symbol:e.symbol,name:e.name,decimals:e.decimals,contractAddress:e.contractAddress,tokenId:e.tokenId,chainId:e.chainId,chainName:e.chainName,imageUrl:e.imageUrl,isCustomToken:e.isCustomToken,isNativeToken:e.isNativeToken}}function Gc(e,t){let n=!1;function r(){if(!(n||typeof window>`u`)){n=!0;try{localStorage.removeItem(e)}catch{}}}return{read(){if(r(),typeof window>`u`)return null;try{let t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch(e){return s.console.warn(`[${t}] Failed to parse stored token:`,e),null}},has(){if(r(),typeof window>`u`)return!1;try{return sessionStorage.getItem(e)!=null}catch{return!1}},write(n){if(!(typeof window>`u`))try{sessionStorage.setItem(e,JSON.stringify(Wc(n)))}catch(e){s.console.warn(`[${t}] Failed to persist selected token:`,e)}},clear(){if(!(typeof window>`u`))try{sessionStorage.removeItem(e)}catch(e){s.console.warn(`[${t}] Failed to clear stored token:`,e)}}}}function Kc({supportedChains:e,supportedTokensByChain:t,trailsSupportedTokens:n}){if(!e&&!t)return{chainIds:null,tokens:null,tokenKeys:null,tokenRestrictedChainIds:null,error:null};let r=rl(e);if(r.error)return{chainIds:[],tokens:[],tokenKeys:[],tokenRestrictedChainIds:[],error:r.error};let i=il(t,n);if(i.error)return{chainIds:[],tokens:[],tokenKeys:[],tokenRestrictedChainIds:[],error:i.error};let a=i.chainIds,o=r.chainIds;return o&&a?.some(e=>!o.includes(e))?{chainIds:o,tokens:[],tokenKeys:[],tokenRestrictedChainIds:[],error:`to.supportedTokensByChain contains a chain that is not included in to.supportedChains`}:{chainIds:o,tokens:i.tokens?o?i.tokens.filter(e=>e.chainId?o.includes(e.chainId):!1):i.tokens:null,tokenKeys:i.tokenKeys?o?i.tokenKeys.filter(e=>{let t=Number(e.split(`:`)[0]);return o.includes(t)}):i.tokenKeys:null,tokenRestrictedChainIds:i.chainIds?o?i.chainIds.filter(e=>o.includes(e)):i.chainIds:null,error:null}}function qc(e,t){let n=t.chainIds?e.filter(e=>e.chainId?t.chainIds?.includes(e.chainId):!1):[...e];if(!t.tokenKeys)return n;let r=new Set(t.tokenKeys),i=t.tokenRestrictedChainIds&&t.tokenRestrictedChainIds.length>0?new Set(t.tokenRestrictedChainIds):null;return n.filter(e=>i&&e.chainId!=null&&!i.has(e.chainId)?!0:r.has(G(e)))}function Jc(e,t){return e?qc([e],t).length>0:!1}function Yc(e,t,n,r){if(n.chainIds&&!n.chainIds.includes(t))return!1;if(n.tokenKeys&&n.tokenRestrictedChainIds?.includes(t)){let i=e.trim();if(!i)return!1;if(bn(i))return n.tokenKeys.includes(Ke(t,i));let a=Ie(r,i,t);return a?n.tokenKeys.includes(G(a)):!1}return!0}function Xc(e,t,n,r){if(!e||!t&&!n)return!1;if(r&&r.length>0&&e.chainId!=null&&!r.includes(e.chainId))return!0;let i=G(e);return n?.includes(i)||t?.some(e=>G(e)===i)||!1}function Zc(e,t,n,r){if(!t&&!n)return[...e];let i=new Set([...n??[],...t?.map(G)??[]]),a=r&&r.length>0?new Set(r):null;return e.filter(e=>a&&e.chainId!=null&&!a.has(e.chainId)?!0:i.has(G(e)))}function Qc(e){let{supportedChains:t,supportedTokensByChain:n}=e;return JSON.stringify({chains:t?.map(e=>$c(e))??null,tokens:n?.map(e=>({chain:$c(e.chain),tokens:Array.isArray(e.tokens)?e.tokens.map(e=>typeof e==`string`?e.trim().toLowerCase():e):e.tokens}))??null})}function $c(e){try{return dt(e)}catch{return typeof e==`object`&&e&&`id`in e?e.id:String(e)}}const el=[101];function tl(e,t=el){if(e==null)return null;if(t.length===0)return[...e];let n=new Set(t);return e.filter(e=>!n.has(e))}function nl(e,t){if(!e)return;let n=t?.disabledChains?.length?t.disabledChains:null;return(n?tl(e,n)??[]:e).map(e=>({chainId:e,name:$(e)?.name??`Chain ${e}`,imageUrl:``}))}function rl(e){if(!e)return{chainIds:null,error:null};if(e.length===0)return{chainIds:[],error:`to.supportedChains must contain at least one chain`};try{return{chainIds:Array.from(new Set(e.map(dt))),error:null}}catch(e){return{chainIds:[],error:e instanceof Error?e.message:String(e)}}}function il(e,t){if(!e)return{chainIds:null,tokens:null,tokenKeys:null,tokenRestrictedChainIds:null,error:null};if(e.length===0)return{chainIds:[],tokens:[],tokenKeys:[],tokenRestrictedChainIds:[],error:`to.supportedTokensByChain must contain at least one chain entry`};let n=[],r=[],i=new Set,a=[];for(let o of e){let e;try{e=dt(o.chain)}catch(e){return{chainIds:[],tokens:[],tokenKeys:[],tokenRestrictedChainIds:[],error:e instanceof Error?e.message:String(e)}}if(n.push(e),!Array.isArray(o.tokens))return{chainIds:[],tokens:[],tokenKeys:[],tokenRestrictedChainIds:[],error:`to.supportedTokensByChain for chain ${e} must include a tokens array`};if(o.tokens.length===0)return{chainIds:Array.from(new Set(n)),tokens:r,tokenKeys:a,tokenRestrictedChainIds:Array.from(new Set(n)),error:`to.supportedTokensByChain for chain ${e} must contain at least one token`};let s=[];for(let n of o.tokens){let o=n.trim();if(bn(o)){let n=Ke(e,o);if(!i.has(n)){i.add(n),a.push(n);let s=Ie(t,o,e);s&&r.push(s)}continue}let c=Ie(t,o,e);if(!c){s.push(n);continue}let l=G(c);i.has(l)||(i.add(l),a.push(l),r.push(c))}if(s.length>0){let t=s.map(e=>`'${e}'`).join(`, `);return{chainIds:Array.from(new Set(n)),tokens:r,tokenKeys:a,tokenRestrictedChainIds:Array.from(new Set(n)),error:`to.supportedTokensByChain entries not found on chain ${e}: ${t}.`}}}return{chainIds:Array.from(new Set(n)),tokens:r,tokenKeys:a,tokenRestrictedChainIds:Array.from(new Set(n)),error:null}}const al=Gc(`trails_origin_selected_token`,`useOriginSelectedToken`);function ol(e,t,n){return Ie(e,t,n)??Ie(qe,t,n)}function sl(e,t,n){if(!e||e.chainId!==n)return!1;let r=e.contractAddress,i=t.contractAddress;return r&&i&&ft(r,i,n)?!0:!!e.symbol&&!!t.symbol&&e.symbol.toLowerCase()===t.symbol.toLowerCase()}const cl=ur(void 0),ll=({children:e,initialToken:t=null})=>{let{fromToken:n,fromChainId:r,originSupportedChains:i,originSupportedTokensByChain:a}=wo(),o=!!(n&&r),c=!!a,l=!!(i||a),u=Qc({supportedChains:i,supportedTokensByChain:a}),{supportedTokens:d,isLoadingTokens:f}=Rc({disabled:!n&&!r&&!l}),p=jt(),m=or.useMemo(()=>{if(p.length===0)return[];let e=[];for(let t of p){let n=t.getOriginTokens?.()??[];e.push(...n)}return e},[p]),h=or.useMemo(()=>{if(m.length===0)return d;let e=new Set,t=[];for(let n of d){let r=G(n);e.has(r)||(e.add(r),t.push(n))}for(let n of m){let r=G(n);e.has(r)||(e.add(r),t.push(n))}return t},[d,m]),g=Y({originSupportedChains:i,originSupportedTokensByChain:a});g.current={originSupportedChains:i,originSupportedTokensByChain:a};let _=or.useMemo(()=>{if(!l||c&&(f||h.length===0))return{chainIds:null,tokens:null,tokenKeys:null,tokenRestrictedChainIds:null,error:null};let e=Kc({supportedChains:g.current.originSupportedChains,supportedTokensByChain:g.current.originSupportedTokensByChain,trailsSupportedTokens:h});if(e.error)return{...e,error:e.error.replaceAll(`to.supported`,`from.supported`)};if(o){let t=ol(h,n??``,Number(r));if(t&&!Jc(t,e))return{...e,error:`from.token must be included in origin support config`}}return e},[r,n,c,o,f,l,u,h]),v=_.tokens,y=_.tokenKeys,b=_.tokenRestrictedChainIds,x=_.chainIds,S=_.error,C=or.useMemo(()=>qc(h,_),[_,h]),[w,T]=X(()=>o||l?null:al.read()??t),[E,D]=X(()=>o||l?!1:al.has()),O=Y(n),k=Y(r),A=Y(u),j=Y(!1),M=Y(!!(n&&r));q(()=>{(n!==O.current||r!==k.current||u!==A.current)&&(s.console.log(`[useOriginSelectedToken] Props changed, resetting manual selection`),D(!1),O.current=n,k.current=r,A.current=u,j.current=!1)},[n,r,u]),q(()=>{if(s.console.log(`[useOriginSelectedToken] Checking preselection:`,{fromToken:n,fromChainId:r,hasManualSelection:E,hasSelectedToken:!!w,selectedTokenSymbol:w?.symbol}),n&&r&&!E){let e=typeof r==`string`?Number(r):r,t=ol(C,n,e);t?T(n=>sl(n,t,e)?n:(s.console.log(`[useOriginSelectedToken] Found matching token, updating selection:`,t),t)):s.console.log(`[useOriginSelectedToken] No matching token found for:`,{fromToken:n,chainId:e,tokensOnChainCount:C.filter(t=>t.chainId===e).length})}else if(l&&!S){if(f||C.length===0)return;(!j.current||!w||!Jc(w,_))&&(al.clear(),D(!1),T(C[0]??null),j.current=!0)}else if(!n&&!r){let e=M.current;M.current=!1,e&&!E&&w&&(s.console.log(`[useOriginSelectedToken] Props cleared, clearing selection`),T(null))}else M.current=!!(n&&r)},[n,r,C,E,l,S,f,_,w]);let N={selectedToken:w,setSelectedToken:K((e,t)=>{if(l&&e&&!Jc(e,_))return;let n=t?.manual!==!1;T(e),e?(al.write(e),D(n)):al.clear()},[l,_]),clearSelectedToken:K(()=>{T(null),al.clear(),D(!1)},[]),hasManualSelection:E,setHasManualSelection:D,availableOriginTokens:v,availableOriginTokenKeys:y,availableOriginTokenRestrictedChainIds:b,availableOriginChainIds:x,availableOriginTokensError:S};return Z(cl.Provider,{value:N,children:e})};function ul(){let e=hr(cl);if(e===void 0)throw Error(`useOriginSelectedToken must be used within a OriginSelectedTokenProvider`);return e}function dl(e,t,n){return Ie(e,t,n)}function fl(e,t){let n=e.filter(e=>e.chainId===t);return n.find(e=>e.symbol===`USDC`)||n.find(e=>e.symbol===`ETH`)||n[0]||null}function pl(e,t){return Ie(e,t)}function ml({supportedTokens:e,defaultToToken:t,defaultToChainId:n,toChainId:r}){let i=n??r;return t&&i?dl(e,t,Number(i)):i?fl(e,Number(i)):t?pl(e,t):null}function hl(e,t){if(!e||typeof e!=`object`)return null;let n=e.details?.currencyOut;if(!n)return null;let r=n.amount;if(r==null||r===``)return null;let i=n.minimumAmount,a=i!=null&&i!==``?String(i):t!=null&&t!==``?String(t):void 0,o=n.amountUsd,s=o!=null&&o!==``?Number(o):void 0;return{amount:String(r),minimumAmount:a,amountUsd:Number.isFinite(s)?s:void 0}}function gl(e,t){if(!W(e))return null;let n=t?.trim();return!n||!ut(n)?null:Pt({chainId:it,recipient:n})}const _l=Gc(`trails_destination_selected_token`,`useDestinationSelectedToken`),vl=ur(void 0);function yl(e,t,n){return Ie(e,t,n)}const bl=({children:e,initialToken:t=null})=>{let{toToken:n,toChainId:r,defaultToToken:i,defaultToChainId:a,supportedChains:o,supportedTokensByChain:s}=wo(),{supportedTokens:c,isLoadingTokens:l}=Rc(),u=jt(),d=or.useMemo(()=>{let e=[...Ze()];for(let t of u){let n=t.getDestinationTokens?.()??[];e.push(...n)}return e},[u]),f=or.useMemo(()=>{if(d.length===0)return c;let e=new Set,t=[];for(let n of c){let r=G(n);e.has(r)||(e.add(r),t.push(n))}for(let n of d){let r=G(n);e.has(r)||(e.add(r),t.push(n))}return t},[c,d]),p=!!(n&&r),m=Qc({supportedChains:o,supportedTokensByChain:s}),h=!!s,g=!!(o||s),_=!!(!p&&(i||a||g)),v=(p||_)&&l,y=or.useMemo(()=>{if(!g||h&&(l||f.length===0))return{chainIds:null,tokens:null,tokenKeys:null,tokenRestrictedChainIds:null,error:null};let e=Kc({supportedChains:o,supportedTokensByChain:s,trailsSupportedTokens:f});if(e.error)return e;if(p&&!Yc(n??``,Number(r),e,f))return{...e,error:`to.token must be included in destination support config`};if(i){let t=a??r,n=t?yl(f,i,Number(t)):qc(f,e).find(e=>e.symbol.toLowerCase()===i.toLowerCase()||e.contractAddress.toLowerCase()===i.toLowerCase());if(!(t?Yc(i,Number(t),e,f):!n||Jc(n,e)))return{...e,error:`to.defaultToken must be included in destination support config`}}return e},[a,i,h,p,g,l,o,f,s,r,n]),b=y.tokens,x=y.tokenKeys,S=y.tokenRestrictedChainIds,C=y.chainIds,w=y.error,T=or.useMemo(()=>qc(f,y),[y,f]),E=Y({toToken:n,toChainId:r,defaultToToken:i,defaultToChainId:a,destinationSupportKey:m}),D=Y(!1),[O,k]=X(()=>{if(n&&r||i||a||g)return null;let e=_l.read();return e&&W(e.chainId??0)?(_l.clear(),t):e||t}),[A,j]=X(()=>p||_?!1:_l.read()!==null);q(()=>{let e=n!==E.current.toToken||r!==E.current.toChainId,o=i!==E.current.defaultToToken||a!==E.current.defaultToChainId||r!==E.current.toChainId,s=m!==E.current.destinationSupportKey;if(E.current={toToken:n,toChainId:r,defaultToToken:i,defaultToChainId:a,destinationSupportKey:m},n&&r){if(_l.clear(),j(!1),l||f.length===0){e&&k(null);return}let t=yl(f,n,Number(r));k(t||null);return}if(g&&!w){if((!D.current||s)&&(_l.clear(),j(!1)),l||T.length===0||w)return;let e=ml({supportedTokens:T,defaultToToken:i,defaultToChainId:a,toChainId:r})??T[0],t=!D.current||o||s||!O||!Jc(O,y);e&&t&&(D.current=!0,k(e));return}if(i||a){if(l||f.length===0)return;if(o&&D.current){_l.clear(),j(!1);let e=ml({supportedTokens:T,defaultToToken:i,defaultToChainId:a,toChainId:r});e&&k(e);return}if(!D.current){D.current=!0,_l.clear();let e=ml({supportedTokens:T,defaultToToken:i,defaultToChainId:a,toChainId:r});e&&k(e)}return}(e||o||s)&&(D.current=!1,k(_l.read()||t))},[n,r,i,a,m,g,w,l,f,T,y,t,O]);let M={selectedToken:O,setSelectedToken:K(e=>{if(p){k(e);return}g&&e&&!Jc(e,y)||(k(e),e?(_l.write(e),j(!0)):_l.clear())},[g,p,y]),clearSelectedToken:K(()=>{k(null),_l.clear(),j(!1)},[]),hasManualSelection:A,setHasManualSelection:j,isControlledByProps:p,hasDefaultProps:_,isResolvingProps:v,availableDestinationTokens:b,availableDestinationTokenKeys:x,availableDestinationTokenRestrictedChainIds:S,availableDestinationChainIds:C,availableDestinationTokensError:w};return Z(vl.Provider,{value:M,children:e})},xl=()=>{let e=hr(vl);if(e===void 0)throw Error(`useDestinationSelectedToken must be used within a DestinationSelectedTokenProvider`);return e},Sl=ur(void 0),Cl=({children:e,initialCurrency:t=null})=>{let[n,r]=X(()=>{if(typeof window<`u`)try{let e=localStorage.getItem(`trails_fiat_selected_currency`);if(e)return JSON.parse(e)}catch(e){console.warn(`Failed to parse saved fiat currency:`,e)}return t}),[i,a]=X(()=>{if(typeof window<`u`)try{return!!localStorage.getItem(`trails_fiat_selected_currency`)}catch(e){return console.error(`Failed to read fiat currency from localStorage:`,e),!1}return!1}),[o,s]=X(``),c=e=>{if(r(e),a(!0),typeof window<`u`)try{if(e){let t={currencyCode:e.currencyCode,name:e.name,symbolImageUrl:e.symbolImageUrl};localStorage.setItem(`trails_fiat_selected_currency`,JSON.stringify(t))}else localStorage.removeItem(`trails_fiat_selected_currency`)}catch(e){console.error(`Failed to save fiat currency to localStorage:`,e)}},l={selectedCurrency:n,setSelectedCurrency:c,clearSelectedCurrency:()=>{c(null),a(!1)},hasManualSelection:i,setHasManualSelection:a,fiatAmount:o,setFiatAmount:e=>{s(e)}};return Z(Sl.Provider,{value:l,children:e})};function wl(){let e=hr(Sl);if(e===void 0)throw Error(`useFiatSelectedCurrency must be used within a FiatSelectedCurrencyProvider`);return e}const Tl=e=>e==null||!W(e),El=(e,t)=>`${e??`unknown`}:${!t||bt(t)?`native`:St(t)}`,Dl=e=>{let t=typeof e.tokenDecimals==`number`&&e.tokenDecimals>0&&e.tokenDecimals<=18?e.tokenDecimals:bt(e.tokenAddress)?18:void 0;if(t===void 0)return s.console.warn(`[trails-sdk] [fee-options] Missing token decimals`,{tokenAddress:e.tokenAddress,tokenSymbol:e.tokenSymbol}),e.tokenSymbol?`-- ${e.tokenSymbol}`:`--`;try{let n=Xs(e.amount,t);return e.tokenSymbol?`${n} ${e.tokenSymbol}`:n}catch(n){return s.console.warn(`[trails-sdk] [fee-options] Failed to format fee option amount`,{option:e,tokenDecimals:t,error:n}),e.tokenSymbol?`-- ${e.tokenSymbol}`:`--`}};function Ol(e,t,n){if(!e.length||!Tl(t))return[];let r=new Map(n.map(e=>[El(e.chainId,e.contractAddress??null),e]));return e.map(e=>{let n=t===void 0?void 0:r.get(El(t,e.tokenAddress));return{...e,notEnoughBalance:n?.balance?BigInt(n.balance)<BigInt(e.amount??`0`):void 0,tokenImageUrl:n?.imageUrl,chainId:n?.chainId??t,amountUsdDisplay:Ks(e.amountUsd??0),amountUsdLocaleDisplay:qs(e.amountUsd??0),amountFormatted:Dl(e)}}).sort((e,t)=>Number(!!e.notEnoughBalance)-Number(!!t.notEnoughBalance))}const kl=e=>bt(e.tokenAddress)?null:St(e.tokenAddress),Al=e=>e?kl(e):null,jl=e=>kl(e)===null?null:e,Ml=(e,t)=>kl(e)===Al(t),Nl=(e,t)=>t===void 0?null:e.find(e=>kl(e)===t)??null,Pl=(e,t)=>Nl(e,Al(t)),Fl=e=>e.some(e=>!bt(e.tokenAddress)),Il=e=>e!==`direct-transfer`&&e!==`onramp-mesh`,Ll=(...e)=>e.some(e=>e?.walletBehavior?.requiresFeeOptions===!0);function Rl({originToken:e,originTokenBalance:t,originTokenAmount:n,isLoadingBalance:r}){return e?{originToken:e,originTokenBalance:t??e.balance??`0`,originTokenAmount:n??`0`,isLoadingBalance:r}:void 0}const zl=(e,t)=>!!(e&&t&&St(e)===St(t)),Bl=(e,t)=>{try{let n=t?.originToken;return n?.chainId!=null&&!Tl(n.chainId)?!1:t&&zl(n?.contractAddress,e.tokenAddress)?t.isLoadingBalance?!1:Sn(t.originTokenAmount??`0`,n?.decimals??18)+BigInt(e.amount??`0`)>BigInt(t.originTokenBalance??`0`):e.notEnoughBalance??!1}catch(e){return s.console.error(`[trails-sdk] [fee-option] error checking if fee option is disabled`,e),!0}};function Vl({feeOptions:e,selectedFeeOption:t,originTokenInfo:n}){let r=Pl(e,null)??void 0,i=Pl(e,t)??r,a=i?Bl(i,n):!1;return{nativeOption:r,selectedOption:i,displayOption:a?r:i,selectedOptionDisabled:a,allOptionsDisabled:e.length>0&&!n?.isLoadingBalance&&e.every(e=>Bl(e,n))}}function Hl({originChainId:e,feeOptions:t,walletRequiresFeeOptions:n=!1,showFeeOptions:r,tracksWidget:i=!0}){return Tl(e)?n?`waas-fee-options`:r!==!1&&i&&Fl(t??[])?`sdk-selectable`:`native-only`:`unsupported`}const Ul=`trails-fee-option-preference`,Wl=[],Gl=ur(void 0);function Kl(){try{let e=localStorage.getItem(Ul);return e===`native`||e===`erc20`?e:null}catch{return null}}function ql(e,t){if(e.length===0||t!==void 0&&e.some(e=>kl(e)===t))return t;let n=Kl();return kl((n?e.find(e=>kl(e)===null==(n===`native`)):void 0)??e[0])}const Jl=({children:e})=>{let[t,n]=X(void 0),r=K(e=>{let t=Al(e);n(t);try{localStorage.setItem(Ul,t===null?`native`:`erc20`)}catch(e){s.console.warn(`[trails-sdk] Failed to save fee option preference to localStorage`,e)}},[]),i=K(()=>{n(void 0)},[]),a=J(()=>({selectedFeeOptionKey:t,setSelectedFeeOption:r,clearSelectedFeeOption:i}),[t,r,i]);return Z(Gl.Provider,{value:a,children:e})};function Yl(e){let t=hr(Gl);if(t===void 0)throw Error(`useSelectedFeeOption must be used within a SelectedFeeOptionProvider`);let n=e??Wl,r=J(()=>ql(n,t.selectedFeeOptionKey),[n,t.selectedFeeOptionKey]);return{selectedFeeOption:J(()=>Nl(n,r),[n,r]),setSelectedFeeOption:t.setSelectedFeeOption,clearSelectedFeeOption:t.clearSelectedFeeOption}}function Xl(e){let t=e.trim();return t.includes(`.`)&&t.endsWith(`.eth`)}function Zl(e,t){return W(t.originChainId??0)&&ut(e.trim())}function Ql(e,t){let n=e.trim();if(!n)return!1;let r=W(t.destinationChainId??0),i=ut(n),a=bn(n);return i&&!r||a&&r}function $l(e){return e.mode===`earn`?W(e.destinationChainId??0):!0}function eu(e){return e.mode===`earn`?!W(e.destinationChainId??0):!0}function tu(e,t){let n=e.trim();return!n||Zl(n,t)?!1:ut(n)?$l(t):bn(n)?eu(t):!1}function nu(e,t){let n=e.trim();return n?t.mode===`swap`?Zl(n,t):!tu(n,t):!1}function ru(e,t){let n=e.trim();if(!n)return!0;let r=t!=null&&t!==``?Number(t):null;return r!=null&&!Number.isNaN(r)&&W(r)?ut(n):r!=null&&!Number.isNaN(r)?bn(n):et(n)}function iu(e,t){if(ru(e,t))return null;let n=t!=null&&t!==``?Number(t):null,r=n!=null&&!Number.isNaN(n);return r&&W(n)?`Recipient is not a valid Solana address`:r?`Recipient is not a valid EVM address`:`Recipient is not a valid wallet address`}function au(e,t,n){let r=e.trim();if(!r)return null;let i=W(t.destinationChainId??0);return Xl(r)?i?`Recipient must be a Solana address when the destination is Solana`:n.resolvedEnsAddress?null:n.isLoadingEns?`Resolving ENS name...`:`Invalid or unresolved ENS name`:n.isLoadingEns?`Resolving ENS name...`:ut(r)?$l(t)?Zl(r,t)?`Solana-to-Solana swaps are not supported`:n.isValidAddress?null:`Invalid Solana address`:`Solana addresses can only be used when the destination is Solana`:bn(r)?eu(t)?(n.isValidAddress,null):`Recipient must be a Solana address when the destination is Solana`:$l(t)&&eu(t)?`Enter a valid EVM (0x...) or Solana address`:i?`Enter a valid Solana address`:`Enter a valid EVM address or ENS name`}const ou=ur(void 0),su=({children:e})=>{let{address:t}=Yr(),n=Xr(),{mode:r,fundOptions:i}=wo(),{selectedToken:a}=xl(),{selectedToken:o}=ul(),s=i?.hideWallets??[],[c,l]=X(null),u=t||n[0]?.accounts[0]?.address||``,d=Y(u);return q(()=>{let e=d.current;d.current=u;let t=u&&s.length>0&&s.some(e=>at(e,u));if(r===`withdraw`||t||!u)return;let n={mode:r,destinationChainId:a?.chainId,originChainId:o?.chainId},i=tu(u,n);if(!c){if(!i)return;l(u);return}e&&!at(e,u)&&at(c,e)&&i&&l(u)},[a?.chainId,s,r,o?.chainId,u,c]),q(()=>{if(!c)return;let e={mode:r,destinationChainId:a?.chainId,originChainId:o?.chainId};nu(c,e)&&l(null)},[a?.chainId,r,o?.chainId,c]),Z(ou.Provider,{value:{selectedRecipient:c,setSelectedRecipient:l},children:e})};function cu(){let e=hr(ou);if(e===void 0)throw Error(`useSelectedRecipient must be used within a SelectedRecipientProvider`);return e}const lu=ur(void 0),uu=({children:e})=>{let[t,n]=X(``);return Z(lu.Provider,{value:{amount:t,setAmount:n,clearAmount:()=>{n(``)}},children:e})};function du(){let e=hr(lu);if(e===void 0)throw Error(`useSwapAmount must be used within a SwapAmountProvider`);return e}const fu=ur(void 0),pu=({children:e,initialChainId:t=null})=>{let[n,r]=X(t),[i,a]=X(null),o=K(()=>{r(null),a(null)},[]),s=J(()=>({selectedChainId:n,setSelectedChainId:r,clearChainFilter:o,pendingChainId:i,setPendingChainId:a}),[n,o,i]);return Z(fu.Provider,{value:s,children:e})};function mu(e){let t=hr(fu);if(t===void 0)throw Error(`useChainFilter must be used within a ChainFilterProvider`);let{selectedChainId:n,setSelectedChainId:r,clearChainFilter:i,pendingChainId:a,setPendingChainId:o}=t,s=e?.isolated??!1,c=e?.controlled,l=e?.onChange,u=s&&typeof l==`function`,[d,f]=X(null);return{selectedChainId:s?u?c??null:d:n,setSelectedChainId:K(e=>{if(s){if(u){l?.(e);return}f(e);return}r(e)},[r,s,u,l]),clearChainFilter:K(()=>{if(s){if(u){l?.(null);return}f(null);return}i()},[i,s,u,l]),pendingChainId:a,setPendingChainId:o}}const hu=ur(void 0),gu=`trails-balance-visible`,_u=({children:e,initialVisible:t=!0})=>{let[n,r]=X(()=>{try{let e=localStorage.getItem(gu);return e===null?t:JSON.parse(e)}catch(e){return console.warn(`Failed to read balance visibility from localStorage:`,e),t}});q(()=>{try{localStorage.setItem(gu,JSON.stringify(n))}catch(e){console.warn(`Failed to save balance visibility to localStorage:`,e)}},[n]);let i={isBalanceVisible:n,setIsBalanceVisible:r,toggleBalanceVisible:()=>{r(!n)},resetBalanceVisible:()=>{try{localStorage.removeItem(gu),r(!0)}catch(e){console.warn(`Failed to reset balance visibility:`,e),r(!0)}}};return Z(hu.Provider,{value:i,children:e})};function vu(){let e=hr(hu);if(e===void 0)throw Error(`useBalanceVisible must be used within a BalanceVisibleProvider`);return e}const yu=ur(void 0),bu=`trails-theme`,xu=({children:e})=>{let[t,n]=X(()=>{try{let e=localStorage.getItem(bu);return e&&[`auto`,`light`,`dark`].includes(e)?e:null}catch(e){return s.console.warn(`Failed to read theme from localStorage:`,e),null}}),r={selectedTheme:t,setSelectedTheme:K(e=>{n(e);try{localStorage.setItem(bu,e)}catch(e){s.console.warn(`Failed to save theme to localStorage:`,e)}},[]),resetThemePreference:K(()=>{try{localStorage.removeItem(bu),n(null)}catch(e){s.console.warn(`Failed to reset theme preference:`,e),n(null)}},[])};return Z(yu.Provider,{value:r,children:e})};function Su(){let e=hr(yu);if(e===void 0)throw Error(`useThemePreference must be used within a ThemePreferenceProvider`);return e}var Cu=class e{constructor(){me(this,`locale`,null),me(this,`listeners`,new Set);try{let e=typeof window<`u`&&typeof localStorage<`u`&&typeof localStorage.getItem==`function`?localStorage.getItem(`trails-locale-preference`):null;this.locale=e}catch(e){console.warn(`Failed to load locale from localStorage:`,e)}}static getInstance(){return e.instance||(e.instance=new e),e.instance}setLocale(e){this.locale=e,this.notifyListeners()}getLocale(){return this.locale}getEffectiveLocale(){return this.locale?this.locale:typeof navigator<`u`&&navigator.language?navigator.language:`en-US`}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyListeners(){this.listeners.forEach(e=>{e(this.locale)})}};me(Cu,`instance`,void 0);const wu=Cu.getInstance(),Tu=[{code:`en-US`,name:`United States`,flag:`🇺🇸`,countryName:`United States`},{code:`en-GB`,name:`United Kingdom`,flag:`🇬🇧`,countryName:`United Kingdom`},{code:`en-CA`,name:`Canada`,flag:`🇨🇦`,countryName:`Canada`},{code:`en-AU`,name:`Australia`,flag:`🇦🇺`,countryName:`Australia`},{code:`de-DE`,name:`Germany`,flag:`🇩🇪`,countryName:`Germany`},{code:`fr-FR`,name:`France`,flag:`🇫🇷`,countryName:`France`},{code:`es-ES`,name:`Spain`,flag:`🇪🇸`,countryName:`Spain`},{code:`it-IT`,name:`Italy`,flag:`🇮🇹`,countryName:`Italy`},{code:`pt-BR`,name:`Brazil`,flag:`🇧🇷`,countryName:`Brazil`},{code:`pt-PT`,name:`Portugal`,flag:`🇵🇹`,countryName:`Portugal`},{code:`nl-NL`,name:`Netherlands`,flag:`🇳🇱`,countryName:`Netherlands`},{code:`ja-JP`,name:`Japan`,flag:`🇯🇵`,countryName:`Japan`},{code:`ko-KR`,name:`South Korea`,flag:`🇰🇷`,countryName:`South Korea`},{code:`zh-CN`,name:`China`,flag:`🇨🇳`,countryName:`China`},{code:`ru-RU`,name:`Russia`,flag:`🇷🇺`,countryName:`Russia`},{code:`hi-IN`,name:`India`,flag:`🇮🇳`,countryName:`India`},{code:`ar-SA`,name:`Saudi Arabia`,flag:`🇸🇦`,countryName:`Saudi Arabia`},{code:`tr-TR`,name:`Turkey`,flag:`🇹🇷`,countryName:`Turkey`},{code:`sv-SE`,name:`Sweden`,flag:`🇸🇪`,countryName:`Sweden`},{code:`no-NO`,name:`Norway`,flag:`🇳🇴`,countryName:`Norway`},{code:`da-DK`,name:`Denmark`,flag:`🇩🇰`,countryName:`Denmark`},{code:`fi-FI`,name:`Finland`,flag:`🇫🇮`,countryName:`Finland`}],Eu=ur(void 0),Du=`trails-locale-preference`,Ou=({children:e})=>{let[t,n]=X(()=>{try{let e=localStorage.getItem(Du);return e&&Tu.some(t=>t.code===e)?e:null}catch(e){return console.warn(`Failed to read locale preference from localStorage:`,e),null}});q(()=>{try{t?localStorage.setItem(Du,t):localStorage.removeItem(Du),wu.setLocale(t)}catch(e){console.warn(`Failed to save locale preference to localStorage:`,e)}},[t]);let r={selectedLocale:t,setSelectedLocale:e=>{Tu.some(t=>t.code===e)?n(e):console.warn(`Unsupported locale: ${e}`)},resetLocalePreference:()=>{try{localStorage.removeItem(Du),n(null)}catch(e){console.warn(`Failed to reset locale preference:`,e),n(null)}},getEffectiveLocale:()=>{if(t)return t;if(typeof navigator<`u`&&navigator.language){let e=navigator.language;if(Tu.some(t=>t.code===e))return e;let t=e.split(`-`)[0];if(t){let e=Tu.find(e=>e.code.startsWith(t));if(e)return e.code}}return`en-US`}};return Z(Eu.Provider,{value:r,children:e})};function ku(){let e=hr(Eu);if(e===void 0)throw Error(`useLocalePreference must be used within a LocalePreferenceProvider`);return e}async function Au(e){return(await e.getFiatCurrencyList()).currencies||[]}async function ju(e,t){return(await e.getExchangeRate({toCurrency:t})).exchangeRate}const Mu={all:[`fiat`],currencies:()=>[...Mu.all,`currencies`],currencyList:e=>{let t=!!e;return wr({queryKey:[...Mu.currencies()],queryFn:t?()=>Au(e):Tr,staleTime:Te,gcTime:Te,retry:ss(3),retryDelay:De,persister:ps.persisterFn,refetchOnMount:!1,refetchOnReconnect:!1})},exchangeRates:()=>[...Mu.all,`exchangeRate`],exchangeRate:(e,t)=>{let n=!!e&&!!t;return wr({queryKey:[...Mu.exchangeRates(),t??null],queryFn:n?()=>ju(e,t):Tr,staleTime:5*ge,gcTime:Oe,retry:ss(2),retryDelay:De,persister:ps.persisterFn})}};function Nu(){let e=gs();return Or(Mu.currencyList(e))}function Pu(e={}){let{fromCurrency:t=`USD`,toCurrency:n=`USD`,disabled:r=!1}=e,i=gs(),a=t===n,o=t===`USD`?n:t,{data:s,isLoading:c,error:l}=Or(Mu.exchangeRate(i,r||a?null:o)),u;return a?u=1:s?.value&&(t===`USD`&&n!==`USD`?u=s.value:t!==`USD`&&n===`USD`&&(u=1/s.value)),{exchangeRate:u,isLoading:a?!1:c,error:a?null:l}}const Fu=ur(void 0),Iu=`trails-display-currency-preference`,Lu=({children:e})=>{let{data:t=[]}=Nu(),[n,r]=X(()=>{try{return localStorage.getItem(Iu)}catch(e){return console.warn(`Failed to read currency preference from localStorage:`,e),null}});q(()=>{t.length>0&&n&&(t.some(e=>e.code===n)||(r(null),localStorage.removeItem(Iu)))},[t,n]);let i=n||`USD`,{exchangeRate:a}=Pu({fromCurrency:`USD`,toCurrency:i,disabled:i===`USD`});q(()=>{i===`USD`?Rs.clearRate():a&&Rs.setRate(i,a)},[i,a]),q(()=>{try{n?localStorage.setItem(Iu,n):localStorage.removeItem(Iu)}catch(e){console.warn(`Failed to save currency preference to localStorage:`,e)}},[n]);let o={selectedCurrency:n,setSelectedCurrency:e=>{t.some(t=>t.code===e)?r(e):console.warn(`Unsupported currency: ${e}`)},resetCurrencyPreference:()=>{try{localStorage.removeItem(Iu),r(null)}catch(e){console.warn(`Failed to reset currency preference:`,e),r(null)}},getEffectiveCurrency:()=>n||`USD`};return Z(Fu.Provider,{value:o,children:e})};function Ru(){let e=hr(Fu);if(e===void 0)throw Error(`useDisplayCurrencyPreference must be used within a DisplayCurrencyPreferenceProvider`);return e}const zu=ur(void 0),Bu=({children:e})=>{let[t,n]=X(`wallet`),[r,i]=X(null),[a,o]=X({id:``,name:``}),[s,c]=X(null),[l,u]=X([]),[d,f]=X(null),[p,m]=X(null),[h,g]=X([]),_={selectedFundMethod:t,selectedFundingWallet:r,paymentMethod:a,selectedMeshExchange:s,selectedMeshAccessTokens:l,selectedBluvoExchange:d,selectedBluvoWalletId:p,selectedBluvoBalances:h,setSelectedFundMethod:n,setSelectedFundingWallet:i,setPaymentMethod:o,setSelectedMeshExchange:c,setSelectedMeshAccessTokens:u,setSelectedBluvoExchange:f,setSelectedBluvoWalletId:m,setSelectedBluvoBalances:g,clearSelectedBluvoFunding:K(()=>{m(e=>e===null?e:null),g(e=>e.length===0?e:[])},[])};return Z(zu.Provider,{value:_,children:e})};function Vu(){let e=hr(zu);if(e===void 0)throw Error(`useSelectedFundMethod must be used within a SelectedFundMethodProvider`);return e}function Hu(){return hr(zu)?.selectedFundingWallet??null}function Uu(){let e=hr(zu);if(e===void 0)return s.console.error(`[trails-sdk] useSkipBalanceFetch: Outside the widget context - returning defaults (don't skip balance fetch)`),{selectedFundMethod:`wallet`,shouldSkipBalanceFetch:!1};let t=e.selectedFundMethod===`onramp-meld`||e.selectedFundMethod===`direct-transfer`||e.selectedFundMethod===`onramp-mesh`||e.selectedFundMethod===`onramp-bluvo`;return{selectedFundMethod:e.selectedFundMethod,shouldSkipBalanceFetch:t}}const Wu=ur({solanaWallet:null});function Gu({children:e,solanaWallet:t=null}){return Z(Wu.Provider,{value:{solanaWallet:t},children:e})}function Ku(){return hr(Wu).solanaWallet}function qu(){return hr(Wu).solanaWallet}function Ju(e){return{kind:`evm`,connectionId:e.connectionId,address:e.address}}function Yu({address:e,walletId:t,walletName:n}){return{kind:`solana`,address:e,walletId:t,walletName:n}}function Xu(e){return e?.kind===`evm`}function Zu(e){return e?.kind===`solana`}function Qu(e,t){return!e||!t||e.kind!==t.kind?!1:e.kind===`evm`?t.kind===`evm`&&e.connectionId===t.connectionId&&e.address.toLowerCase()===t.address.toLowerCase():t.kind===`solana`&&e.address===t.address&&(e.walletId??e.walletName??e.address)===(t.walletId??t.walletName??t.address)}function $u(e,t){return e==null?!1:W(e)!==Zu(t)}function ed(e,t){return Xu(e)?t.some(t=>t.connectionId===e.connectionId&&t.address.toLowerCase()===e.address.toLowerCase()):!1}function td(e,t){return Xu(e)?e.connectionId===t.connectionId&&e.address.toLowerCase()===t.address.toLowerCase():!1}function nd(e,t,n){if(!Zu(t))return Xu(t)?n&&!ed(t,n)?e:t.address:e}function rd(e){return e.kind===`evm`?`evm:${e.connectionId}:${e.address}`:`solana:${e.walletId??e.walletName??e.address}`}function id(e){if(!e)return;let t=e.toLowerCase().trim(),n=da(t);return(ya(n??t)??n??t).toLowerCase().replace(/-(solana|svm|evm|eip155)$/,``)}function ad(e,t){let n=id(e),r=id(t);return n!==void 0&&r!==void 0&&n===r}function od(e,t){let n=id(e);if(n){for(let e of t)if(ad(e.id,n)||va(e.id,n)||e.name&&ad(e.name.toLowerCase().replace(/\s+/g,`-`),n))return e.id}}function sd(e,t,n){return e?e.connections.find(e=>e.id===t&&e.namespace===n)||e.connections.find(e=>e.namespace===n&&(t.endsWith(`:${e.id}`)||e.id.endsWith(`:${t}`))):void 0}function cd(e){return id(e.walletId)??id(e.walletName?.toLowerCase().replace(/\s+/g,`-`))}function ld(e){if(e.connected)return cd(e)}function ud(e,t){return id(sd(t,e.connectionId,`eip155`)?.walletGroupId)??id(e.walletId)??id((e.name||e.connector?.name||``).toLowerCase().replace(/\s+/g,`-`))??e.name.toLowerCase()}function dd(e,t,n){return ad(ud(e,n),ld(t))}function fd(e){return e?.trim()||void 0}function pd(e){return fd(e.walletIcon)||e.availableWallets?.find(t=>t.walletId===e.walletId)?.walletIcon?.trim()||void 0}function md(e,t,n){if(n?.preferSolanaIcon&&e.networks.includes(`solana`)&&t){let e=pd(t);if(e)return e}let r=fd(e.icon??e.evmWallet?.icon);if(r)return r;if(Zu(e.selection)&&t)return pd(t)}function hd(e){if(e?.connected)return e.publicKey?.toBase58?.()??void 0}function gd(e){return!e.evmWallet&&e.networks.includes(`solana`)&&!!e.solanaAddress}function _d(e,t){if(t)return e.find(e=>Qu(e.selection,t))}function vd({connectedWallets:e,svmWallet:t,session:n}){let r=hd(t),i=e.map(e=>{let i=!!r&&!!t&&dd(e,t,n);return{selection:Ju(e),name:e.name||e.connector?.name||`Wallet`,icon:e.icon,evmWallet:e,solanaAddress:i?r:void 0,networks:i?[`evm`,`solana`]:[`evm`]}}),a=i.some(e=>e.networks.includes(`solana`));return r&&t&&!a&&i.push({selection:Yu({address:r,walletId:t.walletId,walletName:t.walletName}),name:t.walletName??`Wallet`,icon:pd(t),walletId:t.walletId,solanaAddress:r,networks:[`solana`]}),i}function yd({groupedWallets:e,selectedFundingWallet:t}){let n=_d(e,t);if(n)return n.selection;let r=e.find(e=>e.evmWallet?.isActive);if(r)return r.selection;let i=e.find(gd);return i?i.selection:e[0]?.selection??null}function bd({connectedWallets:e,svmWallet:t,session:n,selectedFundingWallet:r,activeEvmAddress:i}){let a=vd({connectedWallets:e,svmWallet:t,session:n});if(a.length===0)return;let o=_d(a,r);if(r)return o??a[0];if(i){let e=i.toLowerCase(),t=a.find(t=>t.evmWallet?.address.toLowerCase()===e);if(t)return t}return a.find(gd)||a[0]}function xd(e,t){return t?.preferSolanaAddress&&e.solanaAddress?e.solanaAddress:Zu(e.selection)?e.solanaAddress??e.selection.address:e.evmWallet?.address??e.solanaAddress??``}function Sd({evmAccountAddress:e,connectedWallets:t,svmWallet:n,session:r}){if(!e||!n?.connected||!n.publicKey)return;let i=t.find(t=>t.address.toLowerCase()===e.toLowerCase());if(!(!i||!dd(i,n,r)))return n.publicKey.toBase58()}function Cd({evmAccountAddress:e,connectedWallets:t,svmWallet:n,session:r}){let i=Sd({evmAccountAddress:e,connectedWallets:t,svmWallet:n,session:r});if(i)return i;if(!e)return hd(n)}function wd(e,t){return Zu(e)?!0:Xu(e)?!!t&&Qu(t.selection,e)&&!!t.solanaAddress&&!!t.evmWallet:e==null&&t?!!t.solanaAddress:!1}function Td({connectedWallets:e,svmWallet:t,selectedFundingWallet:n,hasActiveEvmConnection:r}){return Zu(n)?!0:!!hd(t)&&!r&&e.length===0}function Ed(e,t){if(t){let n=e.find(e=>e.address.toLowerCase()===t.toLowerCase());if(n)return n}return e.find(e=>e.isActive)??e[0]}function Dd({connectedWallets:e,svmWallet:t,session:n}){if(e.length===0)return;let r=(t?.connected?e.find(e=>dd(e,t,n)):void 0)??e.find(e=>e.isActive)??e[e.length-1];if(r)return{selection:Ju(r),wallet:r}}function Od({connectedWallets:e,svmWallet:t,session:n}){if(!t?.connected)return;let r=e.find(e=>dd(e,t,n));if(r)return Ju(r);let i=hd(t);if(i)return Yu({address:i,walletId:t.walletId,walletName:t.walletName})}function kd(){let e=Be(Ot);if(!e)throw Error(`createSolanaFundingOriginToken: Solana SOL token registry entry is missing`);return{...e,imageUrl:Ge.SOL??``,balance:`0`}}function Ad(e){return!!e&&e.chainId===101&&e.isNativeToken===!0&&e.symbol?.toUpperCase()===`SOL`}function jd({fundMethod:e,setOriginChainId:t,setSourceChainFilterId:n}){let{fromToken:r,fromChainId:i}=wo(),a=Zu(Hu()),{selectedToken:o,setSelectedToken:s,setHasManualSelection:c}=ul(),l=o?.chainId;yr(()=>{To({fromToken:r,fromChainId:i})||e&&e!==`wallet`||a&&(W(l??0)||(s(kd(),{manual:!1}),c(!1),t?.(101),n?.(101)))},[r,i,e,a,l,s,c,t,n])}function Md(){let{fromToken:e,fromChainId:t}=wo(),{isConnected:n}=Kr(),r=Jr(),i=ni(),a=qu(),{selectedFundMethod:o,setSelectedFundingWallet:s,setSelectedFundMethod:c}=Vu(),l=Hu(),u=n&&r.length>0;return{connectedWallets:r,trailsSession:i,svmWallet:a,selectedFundMethod:o,setSelectedFundingWallet:s,setSelectedFundMethod:c,selectedFundingWallet:l,originPreselected:To({fromToken:e,fromChainId:t}),usesWalletFunding:o===`wallet`,usesSolanaOnlyFunding:Td({connectedWallets:r,svmWallet:a,selectedFundingWallet:l,hasActiveEvmConnection:u})}}function Nd({next:e,current:t,setSelectedFundingWallet:n,setSelectedFundMethod:r}){e&&!Qu(e,t)&&(n(e),r(`wallet`))}function Pd(e){let{connectedWallets:t,trailsSession:n,svmWallet:r,setSelectedFundingWallet:i,setSelectedFundMethod:a,selectedFundingWallet:o,originPreselected:s,usesWalletFunding:c,usesSolanaOnlyFunding:l}=e,u=Y(null);q(()=>{if(s||!c||!l){u.current=null;return}let e=Od({connectedWallets:t,svmWallet:r,session:n}),d=`${o?rd(o):`none`}->${e?rd(e):`none`}`;u.current!==d&&(e?Nd({next:e,current:o,setSelectedFundingWallet:i,setSelectedFundMethod:a}):Zu(o)&&i(null),u.current=d)},[t,s,o,a,i,r,n,l,c])}function Fd(e){let{connectedWallets:t,trailsSession:n,svmWallet:r,setSelectedFundingWallet:i,setSelectedFundMethod:a,selectedFundingWallet:o,originPreselected:s,usesWalletFunding:c,usesSolanaOnlyFunding:l}=e,{selectedToken:u}=ul(),d=u?.chainId;q(()=>{if(!(s||!c||l)&&d!=null&&W(d)){if(!r?.connected)return;Nd({next:Od({connectedWallets:t,svmWallet:r,session:n}),current:o,setSelectedFundingWallet:i,setSelectedFundMethod:a})}},[t,d,s,o,a,i,r,n,l,c])}function Id(){let e=Md();return Pd(e),Fd(e),null}const Ld=ur(void 0),Rd=({children:e})=>{let[t,n]=X(null);return Z(Ld.Provider,{value:{selectedPool:t,setSelectedPool:n},children:e})};function zd(){let e=hr(Ld);if(e===void 0)throw Error(`useEarnPool must be used within an EarnPoolProvider`);return e}let Bd=null;function Vd(){return fe||`dev`}function Hd(){Bd=null;try{localStorage.removeItem(`checkoutId`)}catch(e){s.console.error(`Error removing checkout id:`,e)}}function Ud(){try{return localStorage.getItem(`checkoutUserId`)}catch(e){s.console.error(`Error getting checkout user id:`,e)}}function Wd(e){if(e)try{localStorage.setItem(`checkoutUserId`,St(e))}catch(e){s.console.error(`Error setting checkout user id:`,e)}return Kd(),Gd()}function Gd(){if(Bd)return Bd;try{Bd=localStorage.getItem(`checkoutId`)}catch(e){s.console.error(`Error getting checkout id:`,e)}return Bd}function Kd(){Hd(),Bd=qd();try{localStorage.setItem(`checkoutId`,Bd)}catch(e){s.console.error(`Error setting checkout id:`,e)}}function qd(){try{return crypto.randomUUID()}catch(e){return s.console.error(`Error generating checkout id:`,e),Date.now().toString()}}function Jd(e,t){if(!e)return``;let n=St(e);t?.userAgentSalt&&typeof navigator<`u`&&(n=`${n}:${navigator.userAgent}`),t?.extraSalt&&t.extraSalt.length>0&&(n=`${n}:${t.extraSalt}`);let r=wa.fromString(n),i=Ea.sha256(r);return wa.toHex(i).replace(`0x`,``).substring(0,50)}function Yd(e){return Jd(Jd(e),{userAgentSalt:!1,extraSalt:`s3qs4lt`})}typeof window<`u`&&(window._pseudonymize=Jd);const Xd={PAGEVIEW:`PAGEVIEW`,WIDGET_SCREEN:`WIDGET_SCREEN`,PAYMENT_STARTED:`PAYMENT_STARTED`,PAYMENT_COMPLETED:`PAYMENT_COMPLETED`,PAYMENT_ERROR:`PAYMENT_ERROR`,WALLET_CONNECTED:`WALLET_CONNECTED`,WALLET_DISCONNECTED:`WALLET_DISCONNECTED`,INTENT_QUOTE_REQUESTED:`INTENT_QUOTE_REQUESTED`,INTENT_QUOTE_RECEIVED:`INTENT_QUOTE_RECEIVED`,INTENT_QUOTE_ERROR:`INTENT_QUOTE_ERROR`,INTENT_COMMIT_STARTED:`INTENT_COMMIT_STARTED`,INTENT_COMMIT_COMPLETED:`INTENT_COMMIT_COMPLETED`,INTENT_COMMIT_ERROR:`INTENT_COMMIT_ERROR`,TRANSACTION_STARTED:`TRANSACTION_STARTED`,TRANSACTION_SIGNED:`TRANSACTION_SIGNED`,TRANSACTION_SUBMITTED:`TRANSACTION_SUBMITTED`,TRANSACTION_CONFIRMED:`TRANSACTION_CONFIRMED`,TRANSACTION_ERROR:`TRANSACTION_ERROR`,RELAYER_CALL_STARTED:`RELAYER_CALL_STARTED`,RELAYER_CALL_COMPLETED:`RELAYER_CALL_COMPLETED`,RELAYER_CALL_ERROR:`RELAYER_CALL_ERROR`,ONRAMP_QUOTE_REQUESTED:`ONRAMP_QUOTE_REQUESTED`,ONRAMP_QUOTE_RECEIVED:`ONRAMP_QUOTE_RECEIVED`,ONRAMP_QUOTE_ERROR:`ONRAMP_QUOTE_ERROR`,ONRAMP_WIDGET_SESSION:`ONRAMP_WIDGET_SESSION`,ONRAMP_PAYMENT_COMPLETED:`ONRAMP_PAYMENT_COMPLETED`,WIDGET_CLICK:`WIDGET_CLICK`};function Zd(e){let t={};for(let[n,r]of Object.entries(e))r!=null&&(t[n]=typeof r==`string`?r:String(r));return t}var Qd=class{constructor(e){me(this,`sequenceProjectAccessKey`,void 0),this.sequenceProjectAccessKey=e}updateProjectAccessKey(e){this.sequenceProjectAccessKey=e}autoIdentifyIfNeeded(e,t){if(!e)return;let n=this.getCurrentUserId(),r=n&&typeof n==`string`&&n.length>20;n&&n!==`anonymous`&&r||(s.console.log(`[trails-sdk] DEBUG: Auto-identifying from ${t}`,{userAddress:e,currentUserId:n,currentUserIdLength:n?.length,isHashedAddressFormat:r,timestamp:new Date().toISOString()}),this.identifyUser({address:e}))}getCurrentUserId(){}getCommonProps(){return{...this.getNavigatorProps(),...this.getDocumentProps(),...this.getWindowProps(),sequenceProjectAccessKey:this.sequenceProjectAccessKey||``,sdkVersion:Vd()}}getNavigatorProps(){if(typeof navigator>`u`)return{userAgent:``,userLocale:``,userLanguage:``,userCountry:``,userTimezone:``,userTimezoneOffset:``};let e=js(),t=e.includes(`-`)&&e.split(`-`)[1]||``,n=e.includes(`-`)&&e.split(`-`)[0]||e,r=``,i=``;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone||``,i=new Date().getTimezoneOffset().toString()}catch{}return{userAgent:navigator.userAgent,userLocale:e,userLanguage:n,userCountry:t,userTimezone:r,userTimezoneOffset:i}}getDocumentProps(){return typeof window>`u`?{userAgent:``,title:``}:{title:document.title,referrer:document.referrer}}getWindowProps(){return typeof window>`u`?{url:``,origin:``,hostname:``,pathname:``,screenWidth:``,screenHeight:``,screenPixelRatio:``,screenResolution:``,screenOrientation:``}:{url:window.location?.href,origin:window?.origin||window?.location?.origin,hostname:window.location?.hostname,pathname:window.location?.pathname,screenWidth:window.innerWidth?.toString(),screenHeight:window.innerHeight?.toString(),screenPixelRatio:window.devicePixelRatio?.toString(),screenResolution:`${window.screen?.width}x${window.screen?.height}`,screenOrientation:window.screen?.orientation?.type?.toString()}}trackPageview(){this.track({event:Xd.PAGEVIEW,props:this.getCommonProps()})}trackWidgetScreen(e){this.autoIdentifyIfNeeded(e.userAddress,`trackWidgetScreen`),this.track({event:Xd.WIDGET_SCREEN,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.userAddress&&{userAddress:Yd(e.userAddress)}}})}trackPaymentStarted(e){this.autoIdentifyIfNeeded(e.userAddress,`trackPaymentStarted`),Hd();let{onramp:t,...n}=e,r=t?{...t.sessionId&&{onrampSessionId:t.sessionId},onrampProvider:t.provider,onrampSourceAmount:t.sourceAmount,onrampSourceCurrency:t.sourceCurrencyCode,onrampDestinationAmount:t.destinationAmount,onrampDestinationCurrency:t.destinationCurrencyCode,onrampExchangeRate:t.exchangeRate,...t.networkFees&&{onrampNetworkFees:t.networkFees},...t.transactionFee&&{onrampTransactionFee:t.transactionFee},...t.totalFees&&{onrampTotalFees:t.totalFees},onrampCountryCode:t.countryCode,...t.paymentMethod&&{onrampPaymentMethod:t.paymentMethod},...t.quoteId&&{onrampQuoteId:t.quoteId},onrampTimestamp:t.timestamp}:{};this.track({event:Xd.PAYMENT_STARTED,props:{...this.getCommonProps(),checkoutId:Wd(e.userAddress),...n,...e.userAddress&&{userAddress:Yd(e.userAddress)},...e.intentAddress&&{intentAddress:e.intentAddress},destinationChainId:e.destinationChainId?.toString(),originChainId:e.originChainId?.toString(),originTokenAmount:e.originTokenAmount?.toString(),originTokenDecimals:e.originTokenDecimals?.toString(),destinationTokenAmount:e.destinationTokenAmount?.toString(),destinationTokenDecimals:e.destinationTokenDecimals?.toString(),sourceTokenPriceUsd:e.sourceTokenPriceUsd?.toString(),destinationTokenPriceUsd:e.destinationTokenPriceUsd?.toString(),tradeType:e.tradeType,swapProvider:e.swapProvider,bridgeProvider:e.bridgeProvider,...r}})}validateUsdAmount(e,t){if(!e)return;let n;if(typeof e==`number`)n=e;else if(typeof e==`string`){if(n=Number(e),!_s(n)){s.console.warn(`[trails-sdk] Invalid USD amount string, expected a number:`,{usdAmount:e,context:t});return}}else return;if(!ys(n)){s.console.warn(`[trails-sdk] Invalid USD amount detected, not sending to analytics:`,{usdAmount:e,context:t});return}if(n>1e9){s.console.warn(`[trails-sdk] Suspiciously large USD amount detected, not sending to analytics:`,{usdAmount:e,context:t});return}if(t.rawAmount&&t.formattedAmount&&t.decimals!==void 0&&t.decimals>=0&&t.decimals<=18)try{let n=BigInt(t.rawAmount),r=t.decimals,i=BigInt(10**r),a=Number(n)/Number(i),o=Number(t.formattedAmount),c=o/a;if(c>2||c<.5){s.console.warn(`[trails-sdk] Formatted amount doesn't match raw amount with decimals, not sending USD to analytics:`,{usdAmount:e,rawAmount:t.rawAmount,formattedAmount:t.formattedAmount,decimals:t.decimals,expectedFormatted:a,actualFormatted:o,ratio:c,context:t});return}}catch(e){s.console.warn(`[trails-sdk] Error validating raw amount against formatted amount:`,e)}if(t.formattedAmount&&t.priceUsd&&Number(t.formattedAmount)>0&&Number(t.priceUsd)>0){let r=Number(t.formattedAmount)*Number(t.priceUsd),i=n/r;if(i>10||i<.1){s.console.warn(`[trails-sdk] USD amount doesn't match expected calculation, not sending to analytics:`,{usdAmount:e,expectedUsd:r,ratio:i,context:t});return}}return n.toString()}trackPaymentCompleted(e){this.autoIdentifyIfNeeded(e.userAddress,`trackPaymentCompleted`);let t=this.validateUsdAmount(e.depositTokenAmountUsd,{rawAmount:e.depositTokenAmount,formattedAmount:e.depositTokenAmountFormatted,decimals:e.originTokenDecimals,priceUsd:e.sourceTokenPriceUsd,tokenSymbol:e.originTokenSymbol}),n=this.validateUsdAmount(e.destinationTokenAmountUsd,{rawAmount:e.destinationTokenAmount,formattedAmount:e.destinationTokenAmountFormatted,decimals:e.destinationTokenDecimals,priceUsd:e.destinationTokenPriceUsd,tokenSymbol:e.destinationTokenSymbol}),r=n;if(t&&n){let i=Number(t),a=Number(n)/i;(a>100||a<.01)&&(s.console.warn(`[trails-sdk] Suspicious USD ratio between deposit and destination, not sending destination USD:`,{depositTokenAmountUsd:t,destinationTokenAmountUsd:n,ratio:a,depositTokenAmount:e.depositTokenAmount,destinationTokenAmount:e.destinationTokenAmount,originTokenSymbol:e.originTokenSymbol,destinationTokenSymbol:e.destinationTokenSymbol}),r=void 0)}let{onramp:i,...a}=e,o=i?{...i.sessionId&&{onrampSessionId:i.sessionId},onrampProvider:i.provider,onrampSourceAmount:i.sourceAmount,onrampSourceCurrency:i.sourceCurrencyCode,onrampDestinationAmount:i.destinationAmount,onrampDestinationCurrency:i.destinationCurrencyCode,onrampExchangeRate:i.exchangeRate,...i.networkFees&&{onrampNetworkFees:i.networkFees},...i.transactionFee&&{onrampTransactionFee:i.transactionFee},...i.totalFees&&{onrampTotalFees:i.totalFees},onrampCountryCode:i.countryCode,...i.paymentMethod&&{onrampPaymentMethod:i.paymentMethod},...i.quoteId&&{onrampQuoteId:i.quoteId},onrampTimestamp:i.timestamp}:{};this.track({event:Xd.PAYMENT_COMPLETED,props:{...this.getCommonProps(),checkoutId:Gd(),...a,originChainId:e.originChainId?.toString(),destinationChainId:e.destinationChainId?.toString(),...e.userAddress&&{userAddress:Yd(e.userAddress)},...e.intentAddress&&{intentAddress:e.intentAddress},originTokenAddress:e.originTokenAddress,originTokenSymbol:e.originTokenSymbol,originTokenAmount:e.originTokenAmount?.toString(),originTokenAmountFormatted:e.originTokenAmountFormatted?.toString(),depositTokenAmount:e.depositTokenAmount?.toString(),depositTokenAmountFormatted:e.depositTokenAmountFormatted?.toString(),depositTokenAmountUsd:t,destinationTokenAmount:e.destinationTokenAmount?.toString(),destinationTokenAmountFormatted:e.destinationTokenAmountFormatted?.toString(),destinationTokenAmountUsd:r,originTokenDecimals:e.originTokenDecimals?.toString(),destinationTokenDecimals:e.destinationTokenDecimals?.toString(),tradeType:e.tradeType,sourceTokenPriceUsd:e.sourceTokenPriceUsd?.toString(),destinationTokenPriceUsd:e.destinationTokenPriceUsd?.toString(),swapProvider:e.swapProvider,bridgeProvider:e.bridgeProvider,...o}}),Hd()}trackPaymentError(e){this.track({event:Xd.PAYMENT_ERROR,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.userAddress&&{userAddress:Yd(e.userAddress)},...e.intentAddress&&{intentAddress:e.intentAddress},originChainId:e.originChainId?.toString(),destinationChainId:e.destinationChainId?.toString()}})}trackWalletConnected(e){this.track({event:Xd.WALLET_CONNECTED,props:{...this.getCommonProps(),...e,address:e.address,chainId:e.chainId?.toString()}})}trackWalletDisconnected(e){this.track({event:Xd.WALLET_DISCONNECTED,props:{...this.getCommonProps(),...e||{}}})}trackIntentQuoteRequested(e){this.autoIdentifyIfNeeded(e.userAddress,`trackIntentQuoteRequested`),this.track({event:Xd.INTENT_QUOTE_REQUESTED,props:{...this.getCommonProps(),checkoutId:Gd(),originChainId:e.originChainId?.toString(),destinationChainId:e.destinationChainId?.toString(),originTokenAddress:e.originTokenAddress,destinationTokenAddress:e.destinationTokenAddress,...e.userAddress&&{userAddress:Yd(e.userAddress)},originTokenSymbol:e.originTokenSymbol,destinationTokenSymbol:e.destinationTokenSymbol}})}trackIntentQuoteReceived(e){this.autoIdentifyIfNeeded(e.userAddress,`trackIntentQuoteReceived`),this.track({event:Xd.INTENT_QUOTE_RECEIVED,props:{...this.getCommonProps(),quoteId:e.quoteId,checkoutId:Gd(),totalFeeUSD:e.totalFeeUSD?.toString(),trailsFixedFeeUSD:e.trailsFixedFeeUSD?.toString(),crossChainFeeTotalUSD:e.crossChainFeeTotalUSD?.toString(),takerFeeUSD:e.takerFeeUSD?.toString(),providerFeeUSD:e.providerFeeUSD?.toString(),trailsSwapFeeUSD:e.trailsSwapFeeUSD?.toString(),gasFeesPerChainUSD:e.gasFeesPerChainUSD?.map(e=>e?.toString()).join(`,`),originTokenTotalAmount:e.originTokenTotalAmount?.toString(),totalFeeAmount:e.totalFeeAmount?.toString(),provider:e.provider,swapProvider:e.swapProvider,bridgeProvider:e.bridgeProvider,feeToken:e.feeToken,...e.userAddress&&{userAddress:Yd(e.userAddress)},...e.intentAddress&&{intentAddress:e.intentAddress},feeTokenSymbol:e.feeTokenSymbol,originTokenSymbol:e.originTokenSymbol,destinationTokenSymbol:e.destinationTokenSymbol,depositTokenAmountUsd:e.depositTokenAmountUsd?.toString(),originPreconditionAmount:e.originPreconditionAmount?.toString(),destinationPreconditionAmount:e.destinationPreconditionAmount?.toString(),fromAmount:e.fromAmount?.toString(),fromAmountMin:e.fromAmountMin?.toString(),toAmount:e.toAmount?.toString(),toAmountMin:e.toAmountMin?.toString()}})}trackIntentQuoteError(e){this.track({event:Xd.INTENT_QUOTE_ERROR,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.userAddress&&{userAddress:Yd(e.userAddress)},originChainId:e.originChainId?.toString(),destinationChainId:e.destinationChainId?.toString(),originTokenSymbol:e.originTokenSymbol,destinationTokenSymbol:e.destinationTokenSymbol}})}trackIntentCommitStarted(e){this.track({event:Xd.INTENT_COMMIT_STARTED,props:{...this.getCommonProps(),checkoutId:Gd(),...e,originChainId:e.originChainId?.toString(),destinationChainId:e.destinationChainId?.toString(),intentAddress:e.intentAddress,...e.userAddress&&{userAddress:Yd(e.userAddress)},originTokenSymbol:e.originTokenSymbol,destinationTokenSymbol:e.destinationTokenSymbol}})}trackIntentCommitCompleted(e){this.track({event:Xd.INTENT_COMMIT_COMPLETED,props:{...this.getCommonProps(),checkoutId:Gd(),...e,originChainId:e.originChainId?.toString(),destinationChainId:e.destinationChainId?.toString(),intentAddress:e.intentAddress,...e.userAddress&&{userAddress:Yd(e.userAddress)},originTokenSymbol:e.originTokenSymbol,destinationTokenSymbol:e.destinationTokenSymbol}})}trackIntentCommitError(e){this.track({event:Xd.INTENT_COMMIT_ERROR,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.userAddress&&{userAddress:Yd(e.userAddress)},...e.intentAddress&&{intentAddress:e.intentAddress},originChainId:e.originChainId?.toString(),destinationChainId:e.destinationChainId?.toString(),originTokenSymbol:e.originTokenSymbol,destinationTokenSymbol:e.destinationTokenSymbol}})}trackTransactionStarted(e){this.autoIdentifyIfNeeded(e.userAddress,`trackTransactionStarted`),this.track({event:Xd.TRANSACTION_STARTED,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.userAddress&&{userAddress:Yd(e.userAddress)},...e.intentAddress&&{intentAddress:e.intentAddress},chainId:e.chainId?.toString(),depositTokenAmountUsd:e.depositTokenAmountUsd?.toString()}})}trackTransactionSigned(e){this.track({event:Xd.TRANSACTION_SIGNED,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.userAddress&&{userAddress:Yd(e.userAddress)},...e.intentAddress&&{intentAddress:e.intentAddress},depositTokenAmountUsd:e.depositTokenAmountUsd?.toString()}})}trackTransactionSubmitted(e){this.track({event:Xd.TRANSACTION_SUBMITTED,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.userAddress&&{userAddress:Yd(e.userAddress)},...e.intentAddress&&{intentAddress:e.intentAddress},chainId:e.chainId?.toString(),depositTokenAmountUsd:e.depositTokenAmountUsd?.toString()}})}trackTransactionConfirmed(e){this.track({event:Xd.TRANSACTION_CONFIRMED,props:{...this.getCommonProps(),checkoutId:Gd(),...e,chainId:e.chainId?.toString(),...e.userAddress&&{userAddress:Yd(e.userAddress)},...e.intentAddress&&{intentAddress:e.intentAddress},blockNumber:e.blockNumber?.toString(),depositTokenAmountUsd:e.depositTokenAmountUsd?.toString()}})}trackTransactionError(e){this.track({event:Xd.TRANSACTION_ERROR,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.userAddress&&{userAddress:Yd(e.userAddress)},...e.intentAddress&&{intentAddress:e.intentAddress}}})}trackRelayerCallStarted(e){this.track({event:Xd.RELAYER_CALL_STARTED,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.walletAddress&&{walletAddress:e.walletAddress},...e.contractAddress&&{contractAddress:e.contractAddress},chainId:e.chainId?.toString()}})}trackRelayerCallCompleted(e){this.track({event:Xd.RELAYER_CALL_COMPLETED,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.walletAddress&&{walletAddress:e.walletAddress},...e.contractAddress&&{contractAddress:e.contractAddress},chainId:e.chainId?.toString()}})}trackRelayerCallError(e){this.track({event:Xd.RELAYER_CALL_ERROR,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.walletAddress&&{walletAddress:e.walletAddress},...e.contractAddress&&{contractAddress:e.contractAddress},chainId:e.chainId?.toString()}})}trackOnrampQuoteRequested(e){this.track({event:Xd.ONRAMP_QUOTE_REQUESTED,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.walletAddress&&{walletAddress:Yd(e.walletAddress)}}})}trackOnrampQuoteReceived(e){this.track({event:Xd.ONRAMP_QUOTE_RECEIVED,props:{...this.getCommonProps(),checkoutId:Gd(),...e,quotesCount:e.quotesCount?.toString(),responseTime:e.responseTime?.toString(),...e.walletAddress&&{walletAddress:Yd(e.walletAddress)}}})}trackOnrampQuoteError(e){this.track({event:Xd.ONRAMP_QUOTE_ERROR,props:{...this.getCommonProps(),checkoutId:Gd(),...e,responseTime:e.responseTime?.toString(),...e.walletAddress&&{walletAddress:Yd(e.walletAddress)}}})}trackWidgetClick(e){let t=e.userAddress;this.autoIdentifyIfNeeded(t,`trackWidgetClick`),this.track({event:Xd.WIDGET_CLICK,props:{...this.getCommonProps(),...e,userAddress:t?Jd(t):void 0}})}trackOnrampWidgetSession(e){this.track({event:Xd.ONRAMP_WIDGET_SESSION,props:{...this.getCommonProps(),checkoutId:Gd(),...e,...e.userAddress&&{userAddress:Yd(e.userAddress)}}})}trackOnrampPaymentCompleted(e){this.track({event:Xd.ONRAMP_PAYMENT_COMPLETED,props:{...this.getCommonProps(),checkoutId:Gd(),...e,sourceAmount:e.sourceAmount?.toString(),destinationAmount:e.destinationAmount?.toString(),...e.userAddress&&{userAddress:Yd(e.userAddress)}}})}},$d=class extends Qd{constructor(e,t,n,r){super(r),me(this,`databeat`,void 0),me(this,`loggingEnabled`,!1),this.databeat=new xa(e,t,{userIdentTracking:!0,privacy:{userIdHash:!1,userAgentSalt:!1},...n})}identifyUser({address:e}){Ud()!==e?.toLowerCase()&&Hd();let t=Yd(e);s.console.log(`[trails-sdk] DEBUG: identifyUser called`,{address:e,hashedAddress:t,timestamp:new Date().toISOString()}),this.databeat.identify(t,{userIdHash:!1,allowTracking:!0})}unidentifyUser(){Hd(),this.databeat.reset(),this.databeat.identify()}getCurrentUserId(){return this.databeat.getUserId()}track(e){let t={...e,props:Zd(e.props)};return this.databeat.track(t).catch(()=>{}).then(()=>this.logEvent(e))}enable(){return this.databeat.enable()}allowTracking(e){return this.databeat.allowTracking(e)}disable(){return this.databeat.disable()}logEvent(e){this.loggingEnabled&&s.console.log(`[trails-sdk] Analytics track:`,e)}getSessionId(){return this.databeat.getSessionId()}getUserId(){return this.databeat.getUserId()}},ef=class extends Qd{constructor({loggingEnabled:e,sequenceProjectAccessKey:t}){super(t),me(this,`loggingEnabled`,!1),this.loggingEnabled=e}identifyUser(e){return this}unidentifyUser(){return this}enable(){return this}allowTracking(e){return this}track(e){return this.logEvent(e),this}disable(){return this}logEvent(e){this.loggingEnabled&&s.console.log(`[trails-sdk] MockAnalytics track:`,e)}getSessionId(){return`0x${Math.random().toString(16).slice(2,10)}`}getUserId(){return`0x${Math.random().toString(16).slice(2,10)}`}};let tf=null,nf;const rf=e=>{let t=pe(`analyticsDebugLocal`)===`true`,n=pe(`analyticsDebugProd`)===`true`,i=Me(`CI`)===`true`,a=(t||i)&&!n,o=e??nf;return tf?o&&tf.updateProjectAccessKey(o):(tf=a?new ef({loggingEnabled:!i,sequenceProjectAccessKey:o}):new $d(r,{jwt:f},{},o),nf=void 0),tf},af=e=>{tf?tf.updateProjectAccessKey(e):nf=e},of=e=>{rf().trackWidgetScreen(e)},sf=e=>{rf().trackPaymentStarted(e)},cf=e=>{rf().trackPaymentCompleted(e)},lf=e=>{rf().trackPaymentError(e)},uf=e=>{let t=rf();t.unidentifyUser(),t.trackWalletDisconnected(e)},df=e=>{rf().trackIntentQuoteRequested(e)},ff=e=>{rf().trackIntentQuoteReceived(e)},pf=e=>{rf().trackIntentQuoteError(e)},mf=e=>{rf().trackIntentCommitStarted(e)},hf=e=>{rf().trackIntentCommitCompleted(e)},gf=e=>{rf().trackIntentCommitError(e)},_f=e=>{rf().trackTransactionStarted(e)},vf=e=>{rf().trackTransactionSubmitted(e)},yf=e=>{rf().trackTransactionConfirmed(e)},bf=e=>{rf().trackTransactionError(e)},xf=e=>{rf().trackOnrampQuoteRequested(e)},Sf=e=>{rf().trackOnrampQuoteReceived(e)},Cf=e=>{rf().trackOnrampQuoteError(e)},wf=e=>{rf().trackWidgetClick(e)},Tf=e=>{rf().trackOnrampWidgetSession(e)},Ef=e=>{rf().trackOnrampPaymentCompleted(e)};function Df(){return rf().getSessionId()}const Of=e=>e===`auto`?N:(parseFloat(e)*100).toString(),kf=e=>e===`auto`?N:(parseFloat(e)/100).toString(),Af=`trails-slippage-tolerance`,jf=e=>{try{let t=localStorage.getItem(Af);return t===`auto`||t===null?null:t||e}catch{return e}},Mf=({className:e=``})=>{let[t,n]=X(``),[r,i]=X(!1),[a,o]=X(`auto`);q(()=>{try{let e=localStorage.getItem(Af);e?e===`auto`?(o(`auto`),n(N)):(o(`custom`),n(Of(e))):(o(`auto`),n(N))}catch{o(`auto`),n(N)}},[]);let s=e=>{let t=e.target.value;if(t===``||/^\d*\.?\d*$/.test(t)){let e=parseFloat(t);if(_s(e)&&e>20)return;n(t)}},c=()=>{if(t===``||t===`auto`){n(N);try{localStorage.setItem(Af,N)}catch{}return}let e=parseFloat(t);if(!ys(e)||e>20){try{let e=localStorage.getItem(Af);n(e&&e!==`auto`?Of(e):N)}catch{n(N)}return}let r=kf(t);try{localStorage.setItem(Af,r)}catch(e){console.warn(`Failed to save slippage tolerance to localStorage:`,e)}n(e.toString())},l=e=>{e.key===`Enter`&&e.currentTarget.blur()},u=()=>{o(`auto`),n(N);try{localStorage.setItem(Af,N)}catch(e){console.warn(`Failed to save slippage tolerance to localStorage:`,e)}},d=()=>{if(o(`custom`),t===`auto`){n(`1`);let e=kf(`1`);try{localStorage.setItem(Af,e)}catch(e){console.warn(`Failed to save slippage tolerance to localStorage:`,e)}}},f=e=>{o(`custom`);let t=e.toString();n(t);let r=kf(t);try{localStorage.setItem(Af,r)}catch(e){console.warn(`Failed to save slippage tolerance to localStorage:`,e)}};return Q(`div`,{className:`space-y-3 ${e}`,children:[Q(`div`,{className:`flex items-center space-x-2`,children:[Z(`div`,{className:`text-sm font-medium trails-text-primary`,children:`Slippage`}),Q(`div`,{className:`relative`,children:[Z(`button`,{type:`button`,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),className:`text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors`,children:Z(Ri,{className:`w-4 h-4`})}),r&&Q(`div`,{className:`absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 w-64 p-2 text-xs text-white bg-gray-900 dark:bg-gray-700 rounded-md shadow-lg z-10`,children:[`Auto mode calculates optimal slippage based on transaction size and routing. Higher slippage allows for larger price movements but may result in less favorable rates.`,Z(`div`,{className:`absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-gray-900 dark:border-t-gray-700`})]})]})]}),Q(`div`,{className:`flex items-center gap-2`,children:[Z(`button`,{type:`button`,onClick:u,className:`px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${a===`auto`?`bg-[#DBEAFE] text-[#2563EB]`:`bg-transparent text-gray-900 dark:text-gray-100 hover:text-gray-700 dark:hover:text-gray-300 cursor-pointer`}`,children:`Auto`}),Z(`button`,{type:`button`,onClick:d,className:`px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${a===`custom`?`bg-[#DBEAFE] text-[#2563EB]`:`bg-transparent text-gray-900 dark:text-gray-100 hover:text-gray-700 dark:hover:text-gray-300 cursor-pointer`}`,children:`Custom`})]}),a===`custom`&&Z(hi,{children:Q(`div`,{className:`flex items-center gap-2`,children:[Q(`div`,{className:`relative w-16`,children:[Z(`input`,{type:`text`,value:t===`auto`?``:t,onChange:s,onBlur:c,onKeyDown:l,placeholder:`5`,className:`w-full px-3 py-1.5 text-xs border border-solid border-gray-200 dark:border-gray-700 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 trails-input pr-6 rounded-full`}),Z(`div`,{className:`absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none`,children:Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`%`})})]}),[.5,1,3,5].map(e=>Q(`button`,{type:`button`,onClick:()=>f(e),className:`px-2 py-1 text-xs font-medium rounded-full border transition-colors cursor-pointer ${parseFloat(t)===e?`bg-gray-200 dark:bg-gray-700 text-gray-900 dark:text-gray-100 border-gray-400 dark:border-gray-500`:`bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-400 border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700`}`,children:[e,`%`]},e))]})})]})},Nf=Ue.chainId,Pf=Ue.tokenAddress;function Ff(e){return{token:{chainId:e.chainId,tokenAddress:e.tokenAddress,tokenSymbol:e.tokenSymbol},priceUsd:1,updatedAt:new Date().toISOString()}}function If(e){return{chainId:e.chainId,tokenAddress:e.tokenAddress||e.contractAddress||Cn,tokenSymbol:e.tokenSymbol||e.tokenId||e.tokenID||e.symbol}}function Lf(e){let t=Number(e.chainId||0),n=e.tokenAddress||Cn;return`${W(t)?n:n.toLowerCase()}-${t}-${(e.tokenSymbol||``).toUpperCase()}`}function Rf(e){return W(Number(e.chainId))&&bt(e.tokenAddress||Cn,e.chainId)}function zf(e){return{chainId:Nf,tokenAddress:Pf,tokenSymbol:e.tokenSymbol||`SOL`}}function Bf(e,t){let n=If(e.token);return Number(n.chainId)===Nf&&n.tokenAddress.toLowerCase()===Pf.toLowerCase()?{...e,token:{chainId:t.chainId,tokenAddress:t.tokenAddress,tokenSymbol:t.tokenSymbol||e.token.tokenSymbol}}:e}async function Vf(e,t){if(!e)throw Error(`Trails client is required`);if(t.length===0)return[];let n=[],r=[];for(let e of t)W(Number(e.chainId))&&ze(e.tokenAddress)?n.push(Ff(e)):r.push(e);if(r.length===0)return n;try{let t=r.find(Rf),i=t?r.map(e=>Rf(e)?zf(e):e):r,a=(await e.getTokenPrices({tokens:i}))?.tokenPrices||[],o=t?a.map(e=>Bf(e,t)):a;return[...n,...o]}catch(e){throw s.console.error(`[trails-sdk] Failed to fetch token prices:`,e),e}}const Hf=`tokenPrices`,Uf=`batch`,Wf=`single`,Gf=90*Ee,Kf=90*Ee;function qf(e){let t=new Map;for(let n of e){let e=If(n),r=Lf(e);t.has(r)||t.set(r,e)}return Array.from(t.values()).sort((e,t)=>Lf(e).localeCompare(Lf(t)))}function Jf(e){return typeof e==`object`&&!!e&&`chainId`in e&&typeof e.chainId==`number`&&`tokenAddress`in e&&typeof e.tokenAddress==`string`&&(!(`tokenSymbol`in e)||typeof e.tokenSymbol==`string`)}function Yf(e){if(e[0]!==Hf||e[1]!==Uf)return null;let t=e[2];return!Array.isArray(t)||!t.every(Jf)?null:[...t]}function Xf(e){return e?Date.now()-e<Gf:!1}function Zf(e,t){if(e)return e.find(e=>Lf(If(e.token))===t)??null}function Qf(e,t){return e.getQueryCache().findAll({queryKey:rp.batch()}).flatMap(e=>{let n=Yf(e.queryKey);return n?.some(e=>Lf(e)===t)?[{queryKey:e.queryKey,tokens:n,data:Array.isArray(e.state.data)?e.state.data:void 0,dataUpdatedAt:e.state.dataUpdatedAt,fetchStatus:e.state.fetchStatus}]:[]})}function $f({queryClient:e,trailsClient:t,tokens:n,prices:r}){let i=new Map(r.map(e=>[Lf(If(e.token)),e]));for(let r of n){let n=Lf(r);e.setQueryData(rp.byToken(r,t,e).queryKey,i.get(n)??null)}}function ep(e,t){if(!t)return{price:void 0,updatedAt:void 0};let n=Lf(If(t)),r=Qf(e,n).filter(e=>e.data!==void 0).sort((e,t)=>t.dataUpdatedAt-e.dataUpdatedAt)[0];return r?.data?{price:Zf(r.data,n),updatedAt:r.dataUpdatedAt||void 0}:{price:void 0,updatedAt:void 0}}async function tp({queryClient:e,trailsClient:t,token:n}){let r=Lf(n),i=Qf(e,r).filter(e=>e.fetchStatus===`fetching`).sort((e,t)=>e.tokens.length-t.tokens.length)[0];if(i)try{return Zf(await e.fetchQuery(rp.byTokens(i.tokens,t,e)),r)??null}catch{}let a=Qf(e,r).filter(e=>e.data!==void 0&&Xf(e.dataUpdatedAt)).sort((e,t)=>t.dataUpdatedAt-e.dataUpdatedAt)[0];return a?.data?Zf(a.data,r)??null:(await Vf(t,[n]))[0]??null}function np(e,t){return e[0]===Hf?e[1]===Wf?e[2]===t:Yf(e)?.some(e=>Lf(e)===t)??!1:!1}const rp={all:[Hf],batch:()=>[...rp.all,Uf],single:()=>[...rp.all,Wf],byTokens:(e,t,n=yo)=>{let r=qf(e),i=r.length>0&&!!t;return wr({queryKey:[...rp.batch(),r],queryFn:i?async()=>{if(!t)throw Error(`Trails client is required`);let e=await Vf(t,r);return $f({queryClient:n,trailsClient:t,tokens:r,prices:e}),e}:Tr,staleTime:Gf,gcTime:Kf,retry:ss(2),retryDelay:De,persister:ps.persisterFn})},byToken:(e,t,n=yo)=>{let r=e?If(e):null,i=r?Lf(r):null,a=!!r&&!!t;return wr({queryKey:[...rp.single(),i],queryFn:a?async()=>{if(!r||!t)throw Error(`Token price query requires a token and Trails client`);return tp({queryClient:n,trailsClient:t,token:r})}:Tr,staleTime:Gf,gcTime:Kf,retry:ss(2),retryDelay:De,persister:ps.persisterFn})}};function ip(e,t){let n=t??yo;if(!e)return n.invalidateQueries({queryKey:rp.all});let r=Lf(If(e));return n.invalidateQueries({predicate:e=>np(e.queryKey,r)})}async function ap(e,t){return yo.ensureQueryData(rp.byToken(t,e,yo))}async function op(e,t){return t.length===0?[]:yo.ensureQueryData(rp.byTokens(t,e,yo))}async function sp(e){let[{versions:t},{version:n}]=await Promise.all([e.getSupportedIntentProtocols(),e.getDefaultIntentProtocol()]);if(t.length===0)throw Error(`[trails-sdk] getSupportedIntentProtocols returned an empty list`);return{supported:t,apiDefault:n}}const cp=5*ge,lp={all:[`intentProtocol`],apiContext:e=>wr({queryKey:[...lp.all,`apiContext`,e.getHostname()],queryFn:()=>sp(e),staleTime:cp,gcTime:15*ge,...cs}),defaultIntentProtocol:e=>wr({queryKey:[...lp.all,`defaultIntentProtocol`,e.client.getHostname(),e.override??`__none__`,e.global??`__none__`],queryFn:()=>yo.fetchQuery(lp.apiContext(e.client)).then(t=>up({override:e.override,global:e.global,supported:t.supported,apiDefault:t.apiDefault})),staleTime:cp,gcTime:15*ge,...cs})};function up(e){let{override:t,global:n,supported:r,apiDefault:i}=e;return t?(fp(t,r),t):n?(fp(n,r),n):r.includes(le)?le:(fp(i,r),s.console.warn(`[trails-sdk] SDK default intent protocol "${le}" is not supported by the API; using API default "${i}".`),i)}async function dp(e){let{trailsClient:t,override:n}=e,r=he(`intentProtocol`),i=await yo.fetchQuery(lp.defaultIntentProtocol({client:t,override:n,global:r}));return s.console.log(`[trails-sdk] [intent-protocol] === Protocol Version Selected ===`,{intentProtocol:i,override:n,global:r}),{intentProtocol:i}}function fp(e,t){if(!t.includes(e)){let n=t.length?t.join(`, `):`(none)`;throw Error(`[trails-sdk] Intent protocol "${e}" is not supported by the API. Supported: ${n}`)}}const pp=Object.values(nn);function mp(e){if(e===nn.v1)throw Error(`[trails-sdk] Intent protocol "${e}" is no longer supported by this SDK version. Use "${nn.v1_5}".`);return e&&pp.includes(e)?e:(e?s.console.warn(`[trails-sdk] [intent-protocol] Unrecognized intent protocol "${e}" in API response; defaulting to "${le}".`):s.console.log(`[trails-sdk] [intent-protocol] Intent protocol version not in API response, defaulting to "${le}".`),le)}function hp(e){switch(e){case`wallet`:return en.WALLET;case`direct-transfer`:return en.DIRECT_TRANSFER;case`onramp-mesh`:return en.ONRAMP_MESH;case`onramp-bluvo`:return en.ONRAMP_BLUVO;case`onramp-meld`:return en.ONRAMP_MELD}}function gp(e){switch(e){case`pay`:return tn.PAY;case`fund`:return tn.FUND;case`earn`:return tn.EARN;case`swap`:return tn.SWAP;case`withdraw`:return tn.WITHDRAW}}function _p(e){return e===`direct-transfer`||e===`onramp-mesh`||e===`onramp-bluvo`||e===`onramp-meld`}const vp={TRANSACTION_HISTORY:3*Ee,META_TRANSACTION:2*Ee,CCTP_QUEUE:5*Ee,FAILURE_POLLING:2*Ee,TRANSACTION_RECEIPT:3*Ee};function yp(e,t){return e?.toString()===t?.toString()}function bp(e,t){return Pe(e,t)}async function xp({account:e,tokenAddress:t,depositAmount:r,publicClient:i,knownBalance:a,decimals:o}){try{let c;c=a===void 0?bt(t)?await i.getBalance({address:e.address}):await i.readContract({address:t,abi:_n,functionName:`balanceOf`,args:[e.address]}):BigInt(a);let l=BigInt(r);s.console.log(`[trails-sdk] balance`,c),s.console.log(`[trails-sdk] requiredAmount`,l);let u=c>=l;s.console.log(`[trails-sdk] hasEnoughBalance`,u);let d=``,f=``;if(bt(t))d=vn(c,18),f=vn(l,18);else if(o!==void 0)d=vn(c,o),f=vn(l,o);else{let e=await i.readContract({address:t,abi:_n,functionName:`decimals`});if(!e)throw Error(`Decimals not found`);d=vn(c,e),f=vn(l,e)}let p=null;return u||(p=new n(`Insufficient balance: Need ${Us(f)} ${t} for ${e.address} on ${i.chain?.name} but only have ${Us(d)} ${t}`)),{hasEnoughBalance:u,balance:c,balanceFormatted:d,requiredAmount:l,requiredAmountFormatted:f,balanceError:p}}catch(e){return s.console.error(`[trails-sdk] Error checking account balance:`,e),{hasEnoughBalance:!1,balance:BigInt(0),balanceFormatted:`0`,requiredAmount:BigInt(0),requiredAmountFormatted:`0`,balanceError:e instanceof Error?e:null}}}async function Sp(e,t){try{return await eo(e,t)}catch{return!1}}async function Cp(e,t,n,r,i,a,o,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S){let C=Number(t);if(!Number.isFinite(C)||!Number.isInteger(C)||C<=0)throw Error(`originChainId must be a positive integer chain id`);let w=Number(i);if(!Number.isFinite(w)||!Number.isInteger(w)||w<=0)throw Error(`destinationChainId must be a positive integer chain id`);let T=ro(u),E=_?zr(_):ga(v),D;D=b??await Sp(e,W(C)?w:C);let O=y===!0||E||D;if(s.console.log(`[trails-sdk] Wallet check for onlyNativeGasFee:`,{isSequence:E,isSmartContract:D,isSmartWallet:y,onlyNativeGasFee:O,walletId:v,connectorName:_?.name,usedCachedValue:b!=null}),f===ln.EXACT_INPUT&&(!r||r===`0`))throw Error(`originTokenAmount cannot be zero for EXACT_INPUT trade type`);let k={slippageTolerance:d===null?void 0:Number(d),swapProvider:p||void 0,bridgeProvider:m||void 0,intentProtocol:x};return h!==void 0&&(k.swapProviderFallback=h),g!==void 0&&(k.bridgeProviderFallback=g),{ownerAddress:e,originChainId:C,originTokenAddress:n,originTokenAmount:BigInt(r),destinationChainId:w,destinationToAddress:c,destinationTokenAddress:a,destinationTokenAmount:BigInt(o),destinationApproveAddress:l,destinationCallData:T?u:`0x`,destinationCallValue:BigInt(`0`),onlyNativeGasFee:O,options:k,tradeType:f,mode:S?gp(S):void 0}}function wp(e,{tradeType:t,fromAmountUsd:n,toAmountUsd:r}){let i=e.fees?.totalFeeUsd||0,a=Ks(i),o=qs(i);return s.console.log(`[trails-sdk] getFeesFromIntent`,{tradeType:t,fromAmountUsd:n,toAmountUsd:r,totalFeeAmountUsd:i,totalFeeAmountUsdDisplay:a,totalFeeAmountUsdLocaleDisplay:o}),{feeTokenAddress:e.fees?.feeTokenAddress??Cn,totalFeeAmount:e.fees?.totalFeeAmount?.toString()??`0`,totalFeeAmountUsd:i.toString(),totalFeeAmountUsdDisplay:a,totalFeeAmountUsdLocaleDisplay:o}}function Tp(e){return e?.quote?.priceImpact?.toString()??`0`}function Ep(e){return e?.quote?.priceImpactUsd?.toString()??`0`}function Dp(e){let t=e.totalFeeUsd||0;return{feeTokenAddress:e.feeTokenAddress??Cn,totalFeeAmount:e.totalFeeAmount?.toString()??`0`,totalFeeAmountUsd:t.toString(),totalFeeAmountUsdDisplay:Ks(t),totalFeeAmountUsdLocaleDisplay:qs(t)}}function Op(){return{feeTokenAddress:Cn,totalFeeAmount:`0`,totalFeeAmountUsd:`0`,totalFeeAmountUsdDisplay:Ks(0),totalFeeAmountUsdLocaleDisplay:qs(0)}}const kp=250000n,Ap=50000n;function jp(e){return e===1?3:2}async function Mp(e){let t=e.chain?.id,n=jp(t);try{let r=await e.estimateFeesPerGas();if(r.maxFeePerGas&&r.maxPriorityFeePerGas){let e=BigInt(Math.floor(Number(r.maxPriorityFeePerGas)*n)),i=e-r.maxPriorityFeePerGas,a=r.maxFeePerGas+i;return s.console.log(`[trails-sdk][gas-estimation] Boosting fees for faster processing:`,{originalMaxFee:r.maxFeePerGas,originalPriorityFee:r.maxPriorityFeePerGas,boostedMaxFee:a,boostedPriorityFee:e,multiplier:n,chainId:t}),{maxFeePerGas:a,maxPriorityFeePerGas:e}}}catch{}try{let r=await e.getGasPrice(),i=BigInt(Math.floor(Number(r)*n));return s.console.log(`[trails-sdk][gas-estimation] Boosting legacy gas price for faster processing:`,{originalGasPrice:r,boostedGasPrice:i,multiplier:n,chainId:t}),{gasPrice:i}}catch(e){throw Error(`Failed to get fee data`,{cause:e})}}function Np(e,t,n=50){s.console.log(`[trails-sdk][gas-estimation] calculateMaxNativeAmount called with:`,{userBalanceFormatted:e,gasCostFormatted:t,bufferPercentage:n});try{if(!e||typeof e!=`string`)return s.console.log(`[trails-sdk][gas-estimation] Invalid userBalanceFormatted, returning 0`),`0`;let r=parseFloat(e);if(!vs(r))return`0`;if(!t||typeof t!=`string`)return e;let i=parseFloat(t);if(!ys(i)||i===0)return e;let a=i*(1+(typeof n==`number`&&ys(n)&&n<=100?n:50)/100);if(!_s(a))return`0`;let o=r-a;if(!_s(o)||o<=0)return`0`;let c=o.toFixed(6);return!c||typeof c!=`string`?`0`:(s.console.log(`[trails-sdk][gas-estimation] calculateMaxNativeAmount result:`,{balance:r,gasCost:i,gasWithBuffer:a,maxAmount:o,result:c}),c)}catch(e){return s.console.error(`[trails-sdk][gas-estimation] Error in calculateMaxNativeAmount:`,e),`0`}}async function Pp(e,t,n,r,i,a){s.console.log(`[trails-sdk][gas-estimation] getDefaultGasCostEstimate called with:`,{balance:e,chainId:t,hasAccount:!!n,hasTo:!!r,hasData:!!i,hasValue:!!a});try{let o=parseFloat(e);if(!vs(o))return s.console.log(`[trails-sdk][gas-estimation] Invalid balance, returning 0`),`0`;if(t)try{let e=$(t);if(e&&!W(t)){let t=Va(e.id),o=kp;if(n&&r&&i!==void 0&&a!==void 0)try{let e=await t.estimateGas({account:n,to:r,data:i,value:BigInt(a)});e>250000n?(o=e+Ap,s.console.log(`[trails-sdk][gas-estimation] Using estimated gas + buffer for max button:`,{estimatedGas:e,buffer:Ap,gasLimit:o})):(o=kp,s.console.log(`[trails-sdk][gas-estimation] Using default gas limit for max button (estimated was below default):`,{estimatedGas:e,gasLimit:o}))}catch(e){s.console.error(`[trails-sdk][gas-estimation] Error estimating gas for max button, using default:`,e)}let c;try{let e=await Mp(t);if(c=e.maxFeePerGas||e.gasPrice||0n,c===0n)throw Error(`Could not determine gas price`);s.console.log(`[trails-sdk][gas-estimation] Using boosted fee data for max button:`,{maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,gasPrice:e.gasPrice,effectiveGasPrice:c})}catch{s.console.log(`[trails-sdk][gas-estimation] getFeeData failed, using fallback with multiplier`);let e=await t.getGasPrice();c=BigInt(Math.floor(Number(e)*2))}let l=o*c,u=vn(l,18);return s.console.log(`[trails-sdk][gas-estimation] Calculated gas cost for max button:`,{gasLimit:o,effectiveGasPrice:c,gasCostWei:l,gasCostFormatted:u}),u}}catch(e){s.console.error(`[trails-sdk][gas-estimation] Error fetching gas price for max button:`,e)}let c=o*.01;return s.console.log(`[trails-sdk][gas-estimation] Using fallback 1% gas cost estimate:`,{balance:o,defaultGasCost:c.toFixed(6)}),c.toFixed(6)}catch(e){return s.console.error(`[trails-sdk][gas-estimation] Error in getDefaultGasCostEstimate:`,e),`0`}}const Fp=[`CCTP`,`RELAY`,`LIFI`,`HYPERLANE`,`LZ_TRANSFER`],Ip=e=>Fp.includes(e),Lp={AUTO:{name:``,url:``},CCTP:{name:`Circle CCTP`,url:`https://www.circle.com/`},RELAY:{name:`Relay`,url:`https://relay.link/`},LIFI:{name:`LiFi`,url:`https://li.fi/`},ZEROX:{name:`0x`,url:`https://0x.org/`},SUSHI:{name:`Sushi`,url:`https://www.sushi.com/`},LZ_OFT:{name:`LayerZero OFT`,url:`https://layerzero.network/`},LZ_TRANSFER:{name:`LayerZero Transfer`,url:`https://layerzero.network/`},HYPERLANE:{name:`Hyperlane`,url:`https://www.hyperlane.xyz/`}};async function Rp(e,t,n,r){if(!e)return`0`;let i=typeof e==`string`?parseFloat(e):e;if(i===0)return`0`;let a=await Sc(n,t,r);if(!a?.decimals)throw Error(`Token decimals not found for token ${t} on chain ${n}`);let o=Xs(BigInt(Math.floor(i)),a.decimals),s=parseFloat(o);return s<1e-6&&s>0?`<0.000001`:o}async function zp(e,t,n){let r=e?.fees;if(!r)return{trailsFeeBreakdown:null,originGasUsd:0,destinationGasUsd:0,totalGasUsd:0,providerFeeUsd:0,trailsFeeUsd:0,originAmountUsd:n?.originAmountUsd??0,destinationAmountUsd:n?.destinationAmountUsd??0,totalFeesUsd:n?.totalFeesUsd??0,totalFeesUsdDisplay:Ks(0),originGasUsdDisplay:Ks(0),destinationGasUsdDisplay:Ks(0),totalGasUsdDisplay:Ks(0),providerFeeUsdDisplay:Ks(0),trailsFeeUsdDisplay:Ks(0),totalProviderFeesUsd:0,totalProviderFeesUsdDisplay:Ks(0)};let i=e.quoteRequest.originChainId,a=e.quoteRequest.destinationChainId,o=r.originGas,s=r.destinationGas,c=typeof o?.totalFeeUsd==`string`?parseFloat(o.totalFeeUsd):o?.totalFeeUsd??0,l=typeof s?.totalFeeUsd==`string`?parseFloat(s.totalFeeUsd):s?.totalFeeUsd??0,u=r.gasFeeUsd??0,d=r.providerFeeUsd??0,f=r.trailsFeeUsd??0,p=n?.originAmountUsd??0,m=n?.destinationAmountUsd??0,h=r?.totalFeeUsd??0,g=null;if(o||s){if(g={},o&&i!==void 0){let e=o.nativeTokenSymbol||`Unknown`,n=i,r=Cn;g.originRelayFee={amount:await Rp(o.totalFeeAmount.toString(),r,n,t),tokenSymbol:e,tokenAddress:r,chainId:n,usdValue:Ks(c),usdValueLocale:qs(c)},g.originChainId=n}if(s&&a!==void 0){let e=s.nativeTokenSymbol||`Unknown`,n=a,r=Cn;g.destinationRelayFee={amount:await Rp(s.totalFeeAmount.toString(),r,n,t),tokenSymbol:e,tokenAddress:r,chainId:n,usdValue:Ks(l),usdValueLocale:qs(l)},g.destinationChainId=n}let n=r.provider?.quoteProviderFee;if((d>0||n!==void 0)&&i!==void 0){let e=r.feeTokenAddress||Cn,a=typeof i==`bigint`?Number(i):i,o=await Sc(a,e,t);if(!o?.symbol)throw Error(`Token symbol not found for provider fee token ${e} on chain ${a}`);g.providerFee={amount:await Rp(n?.toString(),e,a,t),tokenSymbol:o.symbol,tokenAddress:e,chainId:a,usdValue:Ks(d)}}let u=e.quote?.routeProviders||[],p=e.quote?.routeProvidersFeeUsd||[];u.length>0&&(g.providerFees=u.map((e,t)=>{let n=Lp[e]||{name:e,url:``},r=p[t]??0;return{id:e,name:n.name,url:n.url,feeUsd:r,usdValue:Ks(r),usdValueLocale:qs(r),isBridge:Ip(e)}}).filter(e=>e.feeUsd>0));let m=r.provider?.trailsFee;if((f>0||m!==void 0)&&i!==void 0){let e=r.feeTokenAddress||Cn,n=typeof i==`bigint`?Number(i):i,a=await Sc(n,e,t);if(!a?.symbol)throw Error(`Token symbol not found for trails fee token ${e} on chain ${n}`);g.trailsFee={amount:await Rp(m?.toString(),e,n,t),tokenSymbol:a.symbol,tokenAddress:e,chainId:n,usdValue:Ks(f),usdValueLocale:qs(f)}}let h=c+l+d+f;g.totalUsdValue=Ks(h)}return{trailsFeeBreakdown:g,originGasUsd:c,destinationGasUsd:l,totalGasUsd:u,providerFeeUsd:d,trailsFeeUsd:f,originAmountUsd:p,destinationAmountUsd:m,totalFeesUsd:h,totalFeesUsdDisplay:Ks(h),originGasUsdDisplay:Ks(c),destinationGasUsdDisplay:Ks(l),totalGasUsdDisplay:Ks(u),providerFeeUsdDisplay:Ks(d),trailsFeeUsdDisplay:Ks(f),totalProviderFeesUsd:d,totalProviderFeesUsdDisplay:Ks(d)}}function Bp({originChainId:e,destinationChainId:t,esimatedDurationSeconds:n}){return n!=null&&Number.isFinite(n)&&n>=0?Math.round(n):e===Kn.id&&t===Kn.id?60:e===Kn.id||t===Kn.id?45:15}function Vp({originChainId:e,destinationChainId:t,esimatedDurationSeconds:n}){return Ce(Bp({originChainId:e,destinationChainId:t,esimatedDurationSeconds:n}))}function Hp(e){if(!e?.quote)return;let t=e.quote;if(typeof t.estimatedDuration==`number`&&Number.isFinite(t.estimatedDuration))return t.estimatedDuration}async function Up({originDepositAddress:e,destinationDepositAddress:t,destinationAddress:n,destinationApproveAddress:r,destinationCalldata:i,originChainId:a,destinationChainId:o,originAmount:c,originAmountMin:l,destinationAmount:u,destinationAmountMin:d,originTokenAddress:f,destinationTokenAddress:p,originTokenPriceUsd:m,destinationTokenPriceUsd:h,transactionStates:g,fees:_,slippageTolerance:v,priceImpact:y,priceImpactUsd:b,originNativeTokenPriceUsd:x,noSufficientBalance:S,estimatedGasLimit:C,intent:w,trailsApiKey:T,trailsApiUrl:E,sequenceMetadataUrl:D,feeData:O,resolvedOriginToken:k,destinationAmountUsdOverride:A,edgeId:j}){if(!o)throw Error(`Destination chain id is required`);if(!p&&a===o&&(p=f),!p&&a===o&&(p=f),!p)throw Error(`Destination token address is required`);let M=k??await Sc(a,f,{trailsApiKey:T,trailsApiUrl:E,sequenceMetadataUrl:D}),N=await Sc(o,p,{trailsApiKey:T,trailsApiUrl:E,sequenceMetadataUrl:D}),P=$(a),F=$(o);if(!M||!N||!P||!F)throw s.console.error(`[trails-sdk] Token or chain not found`,{originToken:M,destinationToken:N,originChain:P,destinationChain:F}),Error(`Token or chain not found`);let I=!W(a),ee=!W(o),te=Xs(I&&w?.quote?.fromAmountMin?.toString()||l||`0`,M.decimals),ne=Us(I&&w?.quote?.fromAmountMinUsd||0),re=Ks(I&&w?.quote?.fromAmountMinUsd||0),ie=Xs(ee&&w?.quote?.toAmountMin?.toString()||d||`0`,N.decimals),L=Xs(I&&w?.quote?.fromAmount?.toString()||c,M.decimals),R=Gs(Xs(I&&w?.quote?.fromAmount?.toString()||c,M.decimals)),ae=I&&w?.quote?.fromAmountUsd||(m==null?0:Number(m)*parseFloat(L)),z=Us(ae),B=Ks(ae),V=qs(ae),oe=ee&&w?.quote?.toAmount?.toString()||u,H=Xs(oe,N.decimals),se=Gs(Xs(oe,N.decimals)),ce=ee&&w?.quote?.toAmountUsd||(A??(h==null?0:Number(h)*parseFloat(H))),U=Us(ce),le=Ks(ce),ue=qs(ce),de=ee&&w?.quote?.toAmountMinUsd||(A!=null&&parseFloat(H)>0?parseFloat(ie)/parseFloat(H)*A:h==null?0:Number(h)*parseFloat(ie)),fe=Us(de),pe=Ks(de),me=ro(i),he=W(P.id)?F.id:P.id,ge=W(he)?null:Va(he),_e=0,ve=`0`,ye=`0`,be=`0`;try{if(x&&(C||O)){let e=C||250000n;s.console.log(`[trails-sdk][gas-estimation] Calculating gas cost for quote with gasLimit:`,e,`(estimated:`,C,`default:`,kp,`)`);let t=O??(ge==null?void 0:await Mp(ge));if(!t)throw Error(`Could not determine gas price (no EVM fee client)`);let n=t.maxFeePerGas||t.gasPrice;if(!n)throw Error(`Could not determine gas price`);let r=e*n;ye=r.toString(),be=vn(r,18),_e=parseFloat(vn(r,18))*x,ve=Ks(_e),s.console.log(`[trails-sdk][gas-estimation] Quote gas cost calculated:`,{gasCostWei:r,gasCost:ye,gasCostFormatted:be,gasCostUsd:_e,gasCostUsdDisplay:ve})}}catch(e){s.console.error(`[trails-sdk][gas-estimation] Error estimating gas cost for quote display`,e)}let xe=I&&w?.quote?.fromAmountUsd!=null&&w?.quote?.fromAmount!=null?w.quote.fromAmountUsd/Number(vn(w.quote.fromAmount,M.decimals)):m==null?0:Number(m),Se=ee&&w?.quote?.toAmountUsd!=null&&w?.quote?.toAmount!=null?w.quote.toAmountUsd/Number(vn(w.quote.toAmount,N.decimals)):h==null?0:Number(h),Ce=Wp(xe,Se,M.symbol,N.symbol),we=w?.quote?.routeProviders&&Array.isArray(w.quote.routeProviders)?w.quote.routeProviders.map(e=>{let t=Lp[e]||{name:e,url:``};return{id:e,name:t.name,url:t.url}}):[],Te=Ks(b),Ee=qs(b),{trailsFeeBreakdown:De,totalFeesUsd:Oe,totalFeesUsdDisplay:ke,originGasUsd:Ae,destinationGasUsd:je,totalGasUsd:Me,providerFeeUsd:Ne,trailsFeeUsd:Pe,originGasUsdDisplay:Fe,destinationGasUsdDisplay:Ie,totalGasUsdDisplay:Le,providerFeeUsdDisplay:Re,trailsFeeUsdDisplay:ze,totalProviderFeesUsd:Be,totalProviderFeesUsdDisplay:Ve}=w?await zp(w,{trailsApiKey:T,trailsApiUrl:E,sequenceMetadataUrl:D},{originAmountUsd:w?.quote?.fromAmountUsd||0,destinationAmountUsd:ee?w?.quote?.toAmountUsd||0:A??ce,totalFeesUsd:parseFloat(_?.totalFeeAmountUsdDisplay?.replace(/[^0-9.-]/g,``)||`0`)}):{trailsFeeBreakdown:null,totalFeesUsd:0,totalFeesUsdDisplay:`$0.00`,originGasUsd:0,destinationGasUsd:0,totalGasUsd:0,providerFeeUsd:0,trailsFeeUsd:0,originGasUsdDisplay:`$0.00`,destinationGasUsdDisplay:`$0.00`,totalGasUsdDisplay:`$0.00`,providerFeeUsdDisplay:`$0.00`,trailsFeeUsdDisplay:`$0.00`,totalProviderFeesUsd:0,totalProviderFeesUsdDisplay:`$0.00`},He=w?.intentProtocol,Ue=mp(He);s.console.log(`[trails-sdk] [intent-protocol] Quote normalized with version`,{intentProtocol:Ue,intentId:w?.intentId});let We=Hp(w),Ge=Bp({originChainId:a,destinationChainId:o,esimatedDurationSeconds:We});return{intentProtocol:Ue,originDepositAddress:e||``,destinationDepositAddress:W(o)?``:t||``,destinationAddress:n||``,destinationApproveAddress:r,destinationCalldata:me&&i||``,intentId:w?.intentId??null,edgeId:j??null,expiresAt:w?.expiresAt??null,originAmount:c||`0`,originAmountMin:l||c||`0`,originAmountMinUsdFormatted:ne||`0`,originAmountMinUsdDisplay:re||`0`,destinationAmount:u||`0`,destinationAmountMin:d||u||`0`,destinationAmountMinUsdFormatted:fe||`0`,destinationAmountMinUsdDisplay:pe||`0`,originAmountFormatted:L,originAmountFormattedLocale:R,originAmountUsd:w?.quote?.fromAmountUsd||void 0,fromAmountUsd:w?.quote?.fromAmountUsd||void 0,originAmountUsdFormatted:z,originAmountUsdDisplay:B,originAmountUsdLocaleDisplay:V,destinationAmountFormatted:H,destinationAmountFormattedLocale:se,destinationAmountUsd:ce||void 0,toAmountUsd:ce||void 0,destinationAmountUsdFormatted:U,destinationAmountUsdDisplay:le,destinationAmountUsdLocaleDisplay:ue,originToken:M,destinationToken:N,fees:_||Op(),slippageTolerance:v||`0`,maxSlippage:w?.quote?.maxSlippage??null,priceImpact:y||`0`,priceImpactUsd:b||void 0,priceImpactUsdDisplay:Te||`0`,originChain:P,destinationChain:F,completionEstimateSeconds:Ge,completionEstimateDisplay:Vp({originChainId:a,destinationChainId:o,esimatedDurationSeconds:We}),transactionStates:g||[],gasCostUsd:_e,gasCostUsdDisplay:ve,gasCost:ye,gasCostFormatted:be,originTokenRate:Ce.originTokenRate,destinationTokenRate:Ce.destinationTokenRate,originTokenPriceUsd:xe,destinationTokenPriceUsd:Se,originAmountDisplay:Ws(L),destinationAmountDisplay:Ws(H),originAmountMinDisplay:Ws(te),destinationAmountMinDisplay:Ws(ie),routeProviders:we,noSufficientBalance:S||!1,trailsFeeBreakdown:De,totalFeesUsd:Oe,totalFeesUsdDisplay:ke,originGasUsd:Ae,destinationGasUsd:je,totalGasUsd:Me,providerFeeUsd:Ne,trailsFeeUsd:Pe,originGasUsdDisplay:Fe,destinationGasUsdDisplay:Ie,totalGasUsdDisplay:Le,providerFeeUsdDisplay:Re,trailsFeeUsdDisplay:ze,totalProviderFeesUsd:Be,totalProviderFeesUsdDisplay:Ve,originGasUsdLocaleDisplay:qs(Ae),destinationGasUsdLocaleDisplay:qs(je),totalGasUsdLocaleDisplay:qs(Me),providerFeeUsdLocaleDisplay:qs(Ne),trailsFeeUsdLocaleDisplay:qs(Pe),totalProviderFeesUsdLocaleDisplay:qs(Be),priceImpactUsdLocaleDisplay:Ee,priceImpactDetails:w?.quote?.priceImpactDetails??null}}function Wp(e,t,n,r){if(e===0||t===0)return{originTokenRate:`0`,destinationTokenRate:`0`};let i=e/t,a=t/e,o=Ws(i,{maxFractionDigits:r===`USDC`?2:7}),s=Ws(a,{maxFractionDigits:n===`USDC`?2:7});return{originTokenRate:`1 ${n} = ${o} ${r}`,destinationTokenRate:`1 ${r} = ${s} ${n}`}}function Gp(e,t,n=`Transaction`){let r=``,i=`pending`,a=0;`transactionHash`in e?(r=e.transactionHash,i=e.status===`success`?`confirmed`:`failed`,a=Number(e.blockNumber)):`txnHash`in e&&(r=e.txnHash||``,i=e.status===`SUCCEEDED`?`confirmed`:`failed`,a=0);let o=`txnMinedAt`in e?e.txnMinedAt:void 0;return{transactionHash:r,explorerUrl:Xa({txHash:r,chainId:t}),chainId:t,blockNumber:a,state:i,label:n,txnMinedAt:o}}function Kp(e,t,n){let r=Gt.hashConfiguration(e),i=Ta.fromCreate2({from:n.factory,bytecodeHash:Ea.keccak256(wa.concat(wa.from(n.creationCode),wa.padLeft(wa.from(n.stage1),32)),{as:`Bytes`}),salt:r});if(!Ca.isEqual(i,t))throw Error(`Intent address mismatch: derived ${i}, expected ${t}`)}function qp(e,t){if(!Gt.findSignerLeaf(e,t))throw Error(`Owner ${t} not found as a signer in intent configuration`);let{maxWeight:n}=Gt.getWeight(e,e=>Ca.isEqual(e.address,t));if(n<e.threshold)throw Error(`Owner signer max weight ${n} is below threshold ${e.threshold}`)}var Jp=class{constructor(e,t){me(this,`hostname`,void 0),me(this,`fetch`,void 0),me(this,`path`,`/rpc/KeyMachine/`),me(this,`queryKey`,{ping:()=>[`KeyMachine`,`ping`],config:e=>[`KeyMachine`,`config`,e],tree:e=>[`KeyMachine`,`tree`,e],payload:e=>[`KeyMachine`,`payload`,e],wallets:e=>[`KeyMachine`,`wallets`,e],deployHash:e=>[`KeyMachine`,`deployHash`,e],witness:e=>[`KeyMachine`,`witness`,e],configUpdates:e=>[`KeyMachine`,`configUpdates`,e],migrations:e=>[`KeyMachine`,`migrations`,e],saveConfig:e=>[`KeyMachine`,`saveConfig`,e],saveTree:e=>[`KeyMachine`,`saveTree`,e],savePayload:e=>[`KeyMachine`,`savePayload`,e],saveWallet:e=>[`KeyMachine`,`saveWallet`,e],saveSignature:e=>[`KeyMachine`,`saveSignature`,e],saveSignature2:e=>[`KeyMachine`,`saveSignature2`,e],saveSignerSignatures:e=>[`KeyMachine`,`saveSignerSignatures`,e],saveSignerSignatures2:e=>[`KeyMachine`,`saveSignerSignatures2`,e],saveSignerSignatures3:e=>[`KeyMachine`,`saveSignerSignatures3`,e],saveMigration:e=>[`KeyMachine`,`saveMigration`,e]}),me(this,`ping`,(e,t)=>this.fetch(this.url(`Ping`),Yp(`{}`,e,t)).then(e=>Xp(e).then(e=>Qp(e,`PingResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`config`,(e,t,n)=>this.fetch(this.url(`Config`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`ConfigResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`tree`,(e,t,n)=>this.fetch(this.url(`Tree`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`TreeResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`payload`,(e,t,n)=>this.fetch(this.url(`Payload`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`PayloadResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`wallets`,(e,t,n)=>this.fetch(this.url(`Wallets`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`WalletsResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`deployHash`,(e,t,n)=>this.fetch(this.url(`DeployHash`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`DeployHashResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`witness`,(e,t,n)=>this.fetch(this.url(`Witness`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`WitnessResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`configUpdates`,(e,t,n)=>this.fetch(this.url(`ConfigUpdates`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`ConfigUpdatesResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`migrations`,(e,t,n)=>this.fetch(this.url(`Migrations`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`MigrationsResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`saveConfig`,(e,t,n)=>this.fetch(this.url(`SaveConfig`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`SaveConfigResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`saveTree`,(e,t,n)=>this.fetch(this.url(`SaveTree`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`SaveTreeResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`savePayload`,(e,t,n)=>this.fetch(this.url(`SavePayload`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`SavePayloadResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`saveWallet`,(e,t,n)=>this.fetch(this.url(`SaveWallet`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`SaveWalletResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`saveSignature`,(e,t,n)=>this.fetch(this.url(`SaveSignature`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`SaveSignatureResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`saveSignature2`,(e,t,n)=>this.fetch(this.url(`SaveSignature2`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`SaveSignature2Response`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`saveSignerSignatures`,(e,t,n)=>this.fetch(this.url(`SaveSignerSignatures`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`SaveSignerSignaturesResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`saveSignerSignatures2`,(e,t,n)=>this.fetch(this.url(`SaveSignerSignatures2`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`SaveSignerSignatures2Response`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`saveSignerSignatures3`,(e,t,n)=>this.fetch(this.url(`SaveSignerSignatures3`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`SaveSignerSignatures3Response`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),me(this,`saveMigration`,(e,t,n)=>this.fetch(this.url(`SaveMigration`),Yp(Zp(e),t,n)).then(e=>Xp(e).then(e=>Qp(e,`SaveMigrationResponse`)),e=>{throw tm.new({cause:`fetch(): ${e instanceof Error?e.message:String(e)}`})})),this.hostname=e.replace(/\/*$/,``),this.fetch=(e,n)=>t(e,n)}url(e){return this.hostname+this.path+e}};const Yp=(e=`{}`,t={},n=null)=>({method:`POST`,headers:{...t,"Content-Type":`application/json`,[sm]:cm},body:e,signal:n}),Xp=e=>e.text().then(t=>{let n;try{n=JSON.parse(t)}catch(n){throw am.new({status:e.status,cause:`JSON.parse(): ${n instanceof Error?n.message:String(n)}: response text: ${t}`})}if(!e.ok){let e=typeof n.code==`number`?n.code:0;throw(om[e]||$p).new(n)}return n}),Zp=e=>JSON.stringify(e),Qp=(e,t=``)=>{let n=e;if(typeof e==`string`)try{n=JSON.parse(e)}catch(e){throw am.new({cause:`JsonDecode: JSON.parse failed: ${e.message}`})}return n};var $p=class e extends Error{constructor(t={}){super(t.message),me(this,`code`,void 0),me(this,`status`,void 0),this.name=t.name||`WebrpcEndpointError`,this.code=typeof t.code==`number`?t.code:0,this.message=t.message||`endpoint error`,this.status=typeof t.status==`number`?t.status:400,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}static new(e){return new this({message:e.message,code:e.code,status:e.status,cause:e.cause})}},em=class e extends $p{constructor(t={}){super(t),this.name=t.name||`WebrpcEndpoint`,this.code=typeof t.code==`number`?t.code:0,this.message=t.message||`endpoint error`,this.status=typeof t.status==`number`?t.status:400,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}},tm=class e extends $p{constructor(t={}){super(t),this.name=t.name||`WebrpcRequestFailed`,this.code=typeof t.code==`number`?t.code:-1,this.message=t.message||`request failed`,this.status=typeof t.status==`number`?t.status:400,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}},nm=class e extends $p{constructor(t={}){super(t),this.name=t.name||`WebrpcBadRoute`,this.code=typeof t.code==`number`?t.code:-2,this.message=t.message||`bad route`,this.status=typeof t.status==`number`?t.status:404,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}},rm=class e extends $p{constructor(t={}){super(t),this.name=t.name||`WebrpcBadMethod`,this.code=typeof t.code==`number`?t.code:-3,this.message=t.message||`bad method`,this.status=typeof t.status==`number`?t.status:405,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}},im=class e extends $p{constructor(t={}){super(t),this.name=t.name||`WebrpcBadRequest`,this.code=typeof t.code==`number`?t.code:-4,this.message=t.message||`bad request`,this.status=typeof t.status==`number`?t.status:400,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}},am=class e extends $p{constructor(t={}){super(t),this.name=t.name||`WebrpcBadResponse`,this.code=typeof t.code==`number`?t.code:-5,this.message=t.message||`bad response`,this.status=typeof t.status==`number`?t.status:500,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}};const om={0:em,[-1]:tm,[-2]:nm,[-3]:rm,[-4]:im,[-5]:am,[-6]:class e extends $p{constructor(t={}){super(t),this.name=t.name||`WebrpcServerPanic`,this.code=typeof t.code==`number`?t.code:-6,this.message=t.message||`server panic`,this.status=typeof t.status==`number`?t.status:500,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}},[-7]:class e extends $p{constructor(t={}){super(t),this.name=t.name||`WebrpcInternalError`,this.code=typeof t.code==`number`?t.code:-7,this.message=t.message||`internal error`,this.status=typeof t.status==`number`?t.status:500,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}},[-8]:class e extends $p{constructor(t={}){super(t),this.name=t.name||`WebrpcClientAborted`,this.code=typeof t.code==`number`?t.code:-8,this.message=t.message||`request aborted by client`,this.status=typeof t.status==`number`?t.status:400,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}},[-9]:class e extends $p{constructor(t={}){super(t),this.name=t.name||`WebrpcStreamLost`,this.code=typeof t.code==`number`?t.code:-9,this.message=t.message||`stream lost`,this.status=typeof t.status==`number`?t.status:400,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}},[-10]:class e extends $p{constructor(t={}){super(t),this.name=t.name||`WebrpcStreamFinished`,this.code=typeof t.code==`number`?t.code:-10,this.message=t.message||`stream finished`,this.status=typeof t.status==`number`?t.status:200,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}},1:class e extends $p{constructor(t={}){super(t),this.name=t.name||`InvalidArgument`,this.code=typeof t.code==`number`?t.code:1,this.message=t.message||`invalid argument`,this.status=typeof t.status==`number`?t.status:400,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}},2:class e extends $p{constructor(t={}){super(t),this.name=t.name||`NotFound`,this.code=typeof t.code==`number`?t.code:2,this.message=t.message||`not found`,this.status=typeof t.status==`number`?t.status:404,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,e.prototype)}}},sm=`Webrpc`,cm=`webrpc@v0.38.0;gen-typescript@v0.29.0;key-machine@v0.0.1`;var lm=class{constructor(e=`https://keymachine.sequence.app`,t){me(this,`service`,void 0);let n=t??globalThis.fetch;if(!n)throw Error(`fetch is not available`);this.service=new Jp(e,n)}async getConfiguration(e){let{version:t,config:n}=await this.service.config({imageHash:e});if(t!==3)throw Error(`invalid configuration version ${t}, expected version 3`);return um(n)}async getDeploy(e){let{deployHash:t,context:n}=await this.service.deployHash({wallet:e});return Da.assert(t),Ca.assert(n.factory),Ca.assert(n.mainModule),Ca.assert(n.mainModuleUpgradable),Da.assert(n.walletCreationCode),{imageHash:t,context:{factory:n.factory,stage1:n.mainModule,stage2:n.mainModuleUpgradable,creationCode:n.walletCreationCode}}}async getTree(e){let{version:t,tree:n}=await this.service.tree({imageHash:e});if(t!==3)throw Error(`invalid tree version ${t}, expected version 3`);return fm(n)}};function um(e){return e.checkpointer!==void 0&&Ca.assert(e.checkpointer),{threshold:BigInt(e.threshold),checkpoint:BigInt(e.checkpoint),checkpointer:e.checkpointer,topology:dm(e.tree)}}function dm(e){switch(typeof e){case`string`:return Da.assert(e),e;case`object`:if(Array.isArray(e))return[dm(e[0]),dm(e[1])];if(`weight`in e){if(`address`in e)return Ca.assert(e.address),e.imageHash?(Da.assert(e.imageHash),{type:`sapient-signer`,address:e.address,weight:BigInt(e.weight),imageHash:e.imageHash}):{type:`signer`,address:e.address,weight:BigInt(e.weight)};if(`tree`in e)return{type:`nested`,weight:BigInt(e.weight),threshold:BigInt(e.threshold),tree:dm(e.tree)}}if(`subdigest`in e)return Da.assert(e.subdigest),{type:e.isAnyAddress?`any-address-subdigest`:`subdigest`,digest:e.subdigest}}throw Error(`unknown config tree '${JSON.stringify(e)}'`)}function fm(e){switch(typeof e){case`string`:return Da.assert(e),e;case`object`:if(Array.isArray(e))return e.map(fm);if(`data`in e)return Da.assert(e.data),{type:`leaf`,value:Da.toBytes(e.data)}}throw Error(`unknown tree '${JSON.stringify(e)}'`)}const pm=2160*60*60*1e3;function mm(e,t,n=864e5){try{let r=localStorage.getItem(e);(!r||Date.now()-Number(r)>n)&&(t(),localStorage.setItem(e,String(Date.now())))}catch(e){s.console.debug(`[trails-sdk] [localStorage-gc] GC error`,e)}}function hm(e,t,n){let r=Date.now()-t,i=0;for(let t=localStorage.length-1;t>=0;t--){let a=localStorage.key(t);if(a?.startsWith(e))try{let e=localStorage.getItem(a);if(!e)continue;let t=n(e);(t===null||t<r)&&(localStorage.removeItem(a),i++)}catch{}}return i}function gm(e,t,n,r,i){let a=Date.now()-t,o=0;for(let t=localStorage.length-1;t>=0;t--){let s=localStorage.key(t);if(s?.startsWith(e))try{let e=localStorage.getItem(s);if(!e)continue;let t=r(e),c=!1;for(let[e,r]of Object.entries(t)){let i=n(r);(i===null||i<a)&&(delete t[e],c=!0,o++)}c&&(Object.keys(t).length===0?localStorage.removeItem(s):localStorage.setItem(s,i(t)))}catch{}}return o}const _m=`trails-sdk:intent-config:01:`,vm=()=>typeof window<`u`&&typeof localStorage<`u`&&typeof localStorage.getItem==`function`;function ym(){let e=hm(_m,pm,e=>JSON.parse(e).storedAt??null);e>0&&s.console.debug(`[trails-sdk] [intent-store] GC removed ${e} intent config(s) older than 90 days`)}function bm(e){if(!vm())return null;try{let t=localStorage.getItem(_m+e.toLowerCase());if(!t)return s.console.debug(`[trails-sdk] [intent-store] Intent config cache miss`,e),null;let n=JSON.parse(t);return{config:Gt.configFromJson(n.configJson),context:n.context}}catch{return null}}function xm(e,t,n){if(vm())try{mm(`trails-sdk:gc:intent-config:lastRan`,ym);let r={configJson:Gt.configToJson(t),context:n,storedAt:Date.now()};localStorage.setItem(_m+e.toLowerCase(),JSON.stringify(r)),s.console.debug(`[trails-sdk] [intent-store] Intent config cached`,e)}catch{}}const Sm=`trails-sdk:committed-intents:01:`,Cm=()=>typeof window<`u`&&typeof localStorage<`u`&&typeof localStorage.getItem==`function`;function wm(e){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?{__bigint:t.toString()}:t)}function Tm(e){return JSON.parse(e,(e,t)=>t&&typeof t==`object`&&`__bigint`in t?BigInt(t.__bigint):t)}function Em(){let e=gm(Sm,pm,e=>{let t=e.createdAt?new Date(e.createdAt).getTime():null;return t&&t>0?t:null},e=>Tm(e),wm);e>0&&s.console.debug(`[trails-sdk] [intent-store] GC removed ${e} committed intent(s) older than 90 days`)}function Dm(e){if(Cm())try{mm(`trails-sdk:gc:committed-intents:lastRan`,Em);let t=Sm+e.ownerAddress.toLowerCase(),n=localStorage.getItem(t),r=n?Tm(n):{};r[e.intentId]=e,localStorage.setItem(t,wm(r)),s.console.debug(`[trails-sdk] [intent-store] Committed intent stored`,e.intentId)}catch(e){s.console.error(`[trails-sdk] [intent-store] Error storing committed intent`,e)}}function Om(e){if(!Cm())return[];try{let t=Sm+e.toLowerCase(),n=localStorage.getItem(t);if(!n)return[];let r=Tm(n);return Object.values(r)}catch{return[]}}function km(e,t){if(Cm())try{let n=Sm+t.toLowerCase(),r=localStorage.getItem(n);if(!r)return;let i=Tm(r);delete i[e],localStorage.setItem(n,wm(i))}catch{}}function Am(e,t,n,r,i){if(!n)return console.warn(`[trails-sdk] No ${r} configuration returned — skipping validation`),null;let a=um(n);return Kp(a,Ca.from(t),i),qp(a,Ca.from(e)),s.console.debug(`[trails-sdk] ${r} configuration validated`,{intentAddress:t,ownerAddress:e,config:a}),a}async function jm(e,t,n={},r){df({originChainId:t.originChainId||0,destinationChainId:t.destinationChainId||0,originTokenAddress:t.originTokenAddress,destinationTokenAddress:t.destinationTokenAddress,userAddress:t.ownerAddress,...n});try{s.console.log(`[trails-sdk] quote intent args:`,t);let i;if(r){let n=new Promise((e,t)=>{r.aborted&&t(Error(`Request aborted`)),r.addEventListener(`abort`,()=>{t(Error(`Request aborted`))})});i=await Promise.race([e.quoteIntent(t,{},r),n])}else i=await e.quoteIntent(t);if(!i||!i.intent)throw s.console.error(`[trails-sdk] No result from quoteIntent`),Error(`No result from quoteIntent`);let a=i.intent,o=Am(a.ownerAddress,a.originIntentAddress,i.originConfiguration,`origin`,P);if(o&&xm(Ca.from(a.originIntentAddress),o,P),a.destinationIntentAddress){let e=Am(a.ownerAddress,a.destinationIntentAddress,i.destinationConfiguration,`destination`,P);e&&xm(Ca.from(a.destinationIntentAddress),e,P)}let c=a.originPrecondition,l=a.destinationPrecondition,u=a.quote?.routeProvidersFeeUsd&&Array.isArray(a.quote.routeProvidersFeeUsd)&&a.quote.routeProvidersFeeUsd.length>0?a.quote.routeProvidersFeeUsd.reduce((e,t)=>e+t,0):0;return ff({quoteId:a.originIntentAddress||`unknown`,totalFeeUSD:a.fees?.totalFeeUsd?.toString(),crossChainFeeTotalUSD:a.fees?.provider?.totalFeeUsd,providerFeeUSD:u,trailsSwapFeeUSD:a.fees?.provider?.trailsFeeUsd,gasFeesPerChainUSD:[typeof a.fees?.originGas?.totalFeeUsd==`string`?parseFloat(a.fees.originGas.totalFeeUsd):a.fees?.originGas?.totalFeeUsd||0,typeof a.fees?.destinationGas?.totalFeeUsd==`string`?parseFloat(a.fees.destinationGas.totalFeeUsd):a.fees?.destinationGas?.totalFeeUsd||0],originTokenTotalAmount:void 0,totalFeeAmount:a.fees?.totalFeeAmount?.toString(),provider:a.quote?.routeProviders?a.quote.routeProviders.join(`,`):void 0,swapProvider:a.quote?.routeProviders?.[0]||void 0,bridgeProvider:a.quote?.routeProviders?.[1]||void 0,feeToken:a.fees?.feeTokenAddress,userAddress:t.ownerAddress,intentAddress:a.originIntentAddress,originPreconditionAmount:c?.minAmount?.toString(),destinationPreconditionAmount:l?.minAmount?.toString(),fromAmount:a.quote?.fromAmount?.toString(),fromAmountMin:a.quote?.fromAmountMin?.toString(),toAmount:a.quote?.toAmount?.toString(),toAmountMin:a.quote?.toAmountMin?.toString(),...n}),{intent:a,gasFeeOptions:i.gasFeeOptions,passthrough:i.passthrough,transactionStates:i.transactionStates}}catch(e){throw s.console.error(`[trails-sdk] Error in getIntent`,e),pf({error:a(e),userAddress:t.ownerAddress,originChainId:t.originChainId||0,destinationChainId:t.destinationChainId||0,originTokenAddress:t.originTokenAddress,destinationTokenAddress:t.destinationTokenAddress,...n}),e}}async function Mm(e,t,n={},r){df({originChainId:t.edge?.originChainId||0,destinationChainId:t.intent?.destinationChainId||0,originTokenAddress:t.edge?.originTokenAddress??``,destinationTokenAddress:t.intent?.destinationTokenAddress??``,userAddress:t.intent?.ownerAddress??``,...n});try{s.console.log(`[trails-sdk] quoteIntentEdge args:`,t);let i=r?AbortSignal.any([r,AbortSignal.timeout(6e4)]):AbortSignal.timeout(6e4),a=await e.quoteIntentEdge(t,{},i);if(!a?.edgeId||!a.edge)throw s.console.error(`[trails-sdk] Invalid quoteIntentEdge response`),Error(`No result from quoteIntentEdge`);return ff({quoteId:a.intent?.originIntentAddress||a.edgeId,userAddress:t.intent?.ownerAddress??``,originChainId:t.edge?.originChainId||0,destinationChainId:t.intent?.destinationChainId||0,originTokenAddress:t.edge?.originTokenAddress??``,destinationTokenAddress:t.intent?.destinationTokenAddress??``,...n}),a}catch(e){throw s.console.error(`[trails-sdk] Error in quoteIntentEdge`,e),pf({error:a(e),userAddress:t.intent?.ownerAddress??``,originChainId:t.edge?.originChainId||0,destinationChainId:t.intent?.destinationChainId||0,originTokenAddress:t.edge?.originTokenAddress??``,destinationTokenAddress:t.intent?.destinationTokenAddress??``,...n}),e}}async function Nm(e,t,n={}){let r=t.originCalls,i=t.destinationCalls,o=[];r&&o.push(r),i&&o.push(i);let c=t.originPrecondition,l=t.destinationPrecondition,u=[];c&&u.push(c),l&&u.push(l),s.console.log(`[trails-sdk] commitIntent inputs:`,{intentId:t.intentId,ownerAddress:t.ownerAddress,originIntentAddress:t.originIntentAddress,destinationIntentAddress:t.destinationIntentAddress,calls:o,preconditions:u}),s.console.log(`[trails-sdk] Detailed preconditions:`,u),u.forEach((e,t)=>{s.console.log(`[trails-sdk] Precondition ${t}:`,{type:e.type,chainId:e.chainId,ownerAddress:e.ownerAddress,tokenAddress:e.tokenAddress,minAmount:e.minAmount?.toString()})}),s.console.log(`[trails-sdk] originIntentAddress:`,t.originIntentAddress),s.console.log(`[trails-sdk] destinationIntentAddress:`,t.destinationIntentAddress);let d=t.quoteRequest.originChainId.toString(),f=t.quoteRequest.destinationChainId.toString(),p=c?.ownerAddress;s.console.log(`[trails-sdk] Address comparison:`,{receivedAddress:p,calculatedAddress:t.originIntentAddress,match:p&&Pe(p,t.originIntentAddress)});try{mf({intentAddress:t.originIntentAddress,userAddress:t.ownerAddress,originChainId:d?Number(d):void 0,destinationChainId:f?Number(f):void 0,...n});let r=await e.commitIntent({intent:t});return s.console.log(`[trails-sdk] commitIntent response:`,r),Dm(t),hf({intentAddress:t.originIntentAddress,userAddress:t.ownerAddress,originChainId:d?Number(d):void 0,destinationChainId:f?Number(f):void 0,...n}),r}catch(e){throw gf({error:a(e),userAddress:t.ownerAddress,intentAddress:t.originIntentAddress,originChainId:d?Number(d):void 0,destinationChainId:f?Number(f):void 0,...n}),e}}async function Pm(e,t,n,r){s.console.log(`[trails-sdk] executeIntent inputs:`,{intentId:t,providedDepositTransactionHash:n,hasDepositSignature:!!r});let i={intentId:t,depositTransactionHash:n,depositSignature:r};s.console.log(`[trails-sdk] executeIntent request:`,i);try{let t=await e.executeIntent(i);return s.console.log(`[trails-sdk] executeIntent response:`,t),t}catch(e){let n=_(e);if(n)return s.console.log(`[trails-sdk] executeIntent returned terminal/non-committed status, treating as current state`,{intentId:t,intentStatus:n}),{intentId:t,intentStatus:n};throw e}}async function Fm(e,t,n,r={}){_f({transactionType:`origin_call`,chainId:n.chain.id,userAddress:e.address,...r});let i=$(n.chain.id);if(!i)throw Error(`Chain ${n.chain.id} not found`);let o=W(i.id)?void 0:Va(i.id),c;n.gasLimit?(c=n.gasLimit,s.console.log(`[trails-sdk][gas-estimation] using provided gasLimit:`,c)):s.console.log(`[trails-sdk][gas-estimation] no gasLimit provided, let wallet estimate`);let l=n.maxFeePerGas,u=n.maxPriorityFeePerGas,d;if(!l&&o)try{let e=await Mp(o);e.maxFeePerGas?(l=e.maxFeePerGas,u=e.maxPriorityFeePerGas,s.console.log(`[trails-sdk][gas-estimation] Using boosted EIP-1559 fees in sendOriginTransaction:`,{maxFeePerGas:l,maxPriorityFeePerGas:u})):e.gasPrice&&(d=e.gasPrice,s.console.log(`[trails-sdk][gas-estimation] Using boosted legacy gas price in sendOriginTransaction:`,{gasPrice:d}))}catch{s.console.log(`[trails-sdk][gas-estimation] Fee data fetch failed in sendOriginTransaction, wallet will use default`)}s.console.log(`[trails-sdk] sending origin tx with sendTransaction()`);let f=Date.now();s.console.time(`[trails-sdk] sendTransaction-${f}`);try{let i={account:e,to:n.to,data:n.data,value:BigInt(n.value),chain:n.chain};c&&(i.gas=c),l&&u?(i.maxFeePerGas=l,i.maxPriorityFeePerGas=u):d&&(i.gasPrice=d);let a=await t.sendTransaction(i);if(s.console.timeEnd(`[trails-sdk] sendTransaction-${f}`),s.console.log(`[trails-sdk] done sending, origin tx hash`,a),vf({transactionHash:a,chainId:n.chain.id,userAddress:e.address,...r}),!a)throw Error(`No transaction hash returned from sendTransaction`);return a}catch(t){throw s.console.timeEnd(`[trails-sdk] sendTransaction-${f}`),bf({transactionHash:``,error:a(t),userAddress:e.address,...r}),t}}async function Im(e,t){let n={intentId:t};return await e.getIntent(n)}async function Lm(e,t,n,r){s.console.log(`[trails-sdk] Aborting intent after recovery:`,{intentId:t,chainId:n,abortTransactionHash:r});try{let i={intentId:t,chainId:n,abortTransactionHash:r},a=await e.abortIntent(i);return s.console.log(`[trails-sdk] Intent aborted successfully:`,{intentId:t,status:a.status}),a}catch(e){throw s.console.error(`[trails-sdk] Failed to abort intent:`,{intentId:t,chainId:n,abortTransactionHash:r,error:e instanceof Error?e.message:String(e)}),e}}const Rm=xn(`event CallSucceeded(bytes32 _opHash, uint256 _index)`),zm=xn(`event CallFailed(bytes32 _opHash, uint256 _index, bytes _returnData)`),Bm=xn(`event CallAborted(bytes32 _opHash, uint256 _index, bytes _returnData)`),Vm=xn(`event CallSkipped(bytes32 indexed deploymentId, uint256 actionIndex)`),Hm=xn(`event Refund(address indexed token, address indexed recipient, uint256 amount)`),Um=xn(`event Sweep(address indexed token, address indexed recipient, uint256 amount)`),Wm=xn(`event RefundAndSweep(address indexed token, address indexed refundRecipient, uint256 refundAmount, address indexed sweepRecipient, uint256 actualRefund, uint256 remaining)`);function Gm(e){try{let t=mn({abi:[Rm],data:e.data,topics:e.topics,strict:!1});return{type:`CallSucceeded`,opHash:t.args._opHash,index:t.args._index,log:e}}catch{return null}}function Km(e){try{let t=mn({abi:[zm],data:e.data,topics:e.topics,strict:!1});return{type:`CallFailed`,opHash:t.args._opHash,index:t.args._index,returnData:t.args._returnData,log:e}}catch{return null}}function qm(e){try{let t=mn({abi:[Bm],data:e.data,topics:e.topics,strict:!1});return{type:`CallAborted`,opHash:t.args._opHash,index:t.args._index,returnData:t.args._returnData,log:e}}catch{return null}}function Jm(e){try{let t=mn({abi:[Vm],data:e.data,topics:e.topics,strict:!1});return{type:`CallSkipped`,deploymentId:t.args.deploymentId,actionIndex:t.args.actionIndex,log:e}}catch{return null}}function Ym(e){try{let t=mn({abi:[Hm],data:e.data,topics:e.topics,strict:!1});return{type:`Refund`,token:t.args.token,recipient:t.args.recipient,amount:t.args.amount,log:e}}catch{return null}}function Xm(e){try{let t=mn({abi:[Wm],data:e.data,topics:e.topics,strict:!1});return{type:`RefundAndSweep`,token:t.args.token,refundRecipient:t.args.refundRecipient,refundAmount:t.args.refundAmount,sweepRecipient:t.args.sweepRecipient,actualRefund:t.args.actualRefund,remaining:t.args.remaining,log:e}}catch{return null}}function Zm(e){try{let t=mn({abi:[Um],data:e.data,topics:e.topics,strict:!1});return{type:`Sweep`,token:t.args.token,recipient:t.args.recipient,amount:t.args.amount,log:e}}catch{return null}}function Qm(e){let t=[];for(let n of e.logs){let e=Ym(n);if(e){t.push(e);continue}let r=Xm(n);if(r){t.push(r);continue}let i=Zm(n);i&&t.push(i)}return t}function $m(e){let t=[];for(let n of e.logs){let e=Gm(n);if(e){t.push(e);continue}let r=Km(n);if(r){t.push(r);continue}let i=qm(n);if(i){t.push(i);continue}let a=Jm(n);a&&t.push(a)}return t}const eh=[`TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA`,`TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb`],th=15e3;async function nh(e,t,n,r=th){let i=new AbortController,a=setTimeout(()=>i.abort(),r);try{let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:t,params:n}),signal:i.signal});if(!r.ok)throw Error(`Solana RPC HTTP ${r.status}`);let a=await r.json();if(a.error)throw Error(a.error.message||`Solana RPC error`);return a.result}catch(e){throw e instanceof DOMException&&e.name===`AbortError`?Error(`Solana RPC timeout after ${r}ms`,{cause:e}):e}finally{clearTimeout(a)}}async function rh(e,t,n,r=th){let i=[];for(let a of e)try{return await nh(a,t,n,r)}catch(e){let t=e instanceof Error?e.message:`unknown Solana RPC error`;i.push(`${a}: ${t}`)}throw Error(`Solana RPC ${t} failed on all configured endpoints: ${i.join(` | `)}`)}function ih(e){let t=new Map,n=e?.value;if(!Array.isArray(n))return t;for(let e of n){let n=e,r=n?.account?.data?.parsed?.info?.mint,i=n?.account?.data?.parsed?.info?.tokenAmount?.amount;typeof r==`string`&&typeof i==`string`&&i.length>0&&t.set(r,i)}return t}async function ah(e,t){let n=e.trim();if(!n)return`0`;let r=(await rh(so(t),`getBalance`,[n,{commitment:`confirmed`}]))?.value;return typeof r==`number`?r.toString():`0`}async function oh(e,t,n){return ih(await rh(n,`getTokenAccountsByOwner`,[e,{programId:t},{encoding:`jsonParsed`}]))}async function sh(e,t){let n=e.trim();if(!n)return new Map;let r=so(t),i=await Promise.all(eh.map(e=>oh(n,e,r))),a=new Map;for(let e of i)for(let[t,n]of e)a.set(t,n);return a}async function ch(e,t,n){let r=t.trim();return r?(await sh(e,n)).get(r)??`0`:`0`}function lh(e,t,n){let r=`priceUSD`in t&&typeof t.priceUSD==`string`?t.priceUSD:void 0,i=`balanceUSD`in t&&typeof t.balanceUSD==`string`?t.balanceUSD:void 0,a=n?.priceUsd,o=r?parseFloat(r):NaN,s=a===void 0?Number.isNaN(o)?void 0:o:a;if(s!==void 0){let n=ec(s);if(e.priceUsd=n.priceUsd,e.priceUsdFormatted=n.priceUsdFormatted,e.priceUsdDisplay=n.priceUsdDisplay,t.balance){let n=Zs(t,{value:s,currency:`USD`});if(n!==void 0){let t=$s(n);e.balanceUsd=t.balanceUsd,e.balanceUsdFormatted=t.balanceUsdFormatted,e.balanceUsdDisplay=t.balanceUsdDisplay,e.balanceUsdLocaleDisplay=t.balanceUsdLocaleDisplay}}else if(i!==void 0){let t=parseFloat(i);if(Number.isNaN(t))return;let n=$s(t);e.balanceUsd=n.balanceUsd,e.balanceUsdFormatted=n.balanceUsdFormatted,e.balanceUsdDisplay=n.balanceUsdDisplay,e.balanceUsdLocaleDisplay=n.balanceUsdLocaleDisplay}}}function uh(e,t,n){let r=e.contractInfo?.chainId||0,i=n||$(r),a=e.contractAddress||Cn,o={symbol:e.contractInfo?.symbol||`???`,name:e.contractInfo?.name||`Unknown Token`,decimals:e.contractInfo?.decimals??18,contractAddress:a,chainId:r,chainName:i?.name||`Chain ${r}`,imageUrl:Oc({chainId:r,contractAddress:a,symbol:e.contractInfo?.symbol||`???`,fallbackImageUrl:e.contractInfo?.logoURI}),isNativeToken:!1};if(e.balance){let t=o.decimals,n=Qs(e.balance,t);o.balance=n.balance,o.balanceFormatted=n.balanceFormatted,o.balanceDisplay=n.balanceDisplay,o.balanceLocaleDisplay=n.balanceLocaleDisplay}return lh(o,e,t),o.isSufficientBalance=!0,o}function dh(e,t,n){let r=e.chainId,i=n||$(r),a=i?.nativeCurrency.symbol||`Unknown`,o={symbol:a,name:i?.nativeCurrency.name||`Unknown`,decimals:i?.nativeCurrency.decimals??18,contractAddress:Cn,chainId:r,chainName:i?.name||`Chain ${r}`,imageUrl:Oc({chainId:r,contractAddress:Cn,symbol:a}),isNativeToken:!0};if(e.balance){let t=o.decimals,n=Qs(e.balance,t);o.balance=n.balance,o.balanceFormatted=n.balanceFormatted,o.balanceDisplay=n.balanceDisplay,o.balanceLocaleDisplay=n.balanceLocaleDisplay}return lh(o,e,t),o.isSufficientBalance=!0,o}function fh(e,t){try{return yh(e)?dh(e,t):uh(e,t)}catch(t){return s.console.warn(`[trails-sdk] Skipping malformed token balance:`,e,t),null}}const ph={page:1,pageSize:10,more:!1};function mh(e,t){if(!(e===void 0&&t===void 0))return{page:e,pageSize:t}}function hh(e){let t={};for(let n of e)t[n.toLowerCase()]={tokens:[],nativeTokens:[],erc20Tokens:[],page:ph};return t}function gh(e,t,n,r){for(let i of e){if(!$(i.chainId)){s.console.warn(`[tokenBalances] Skipping unsupported chain ID: ${i.chainId}`);continue}for(let e of i.results||[]){let i=e.accountAddress?.toLowerCase(),a=i?t[i]:void 0;if(!a)continue;let o=n(e);o&&(a[r].push(o),a.tokens.push(o))}}}function _h(e,t){return`${e}:${t||Cn}`}function vh(e){let t=new Map;for(let n of e.balances)for(let e of n.results)`contractAddress`in e&&`contractInfo`in e&&t.set(`${e.contractAddress}-${e.chainId}-${e.contractInfo?.symbol}`,e);for(let n of e.nativeBalances)for(let e of n.results)t.set(`${Cn}-${e.chainId}-native`,e);return t}function yh(e){return!(`contractAddress`in e)||e.contractAddress===Cn}function bh(e,t){let n=e.balanceUsd??0,r=t.balanceUsd??0;if(n>0&&r>0)return r-n;if(n>0&&r===0)return-1;if(n===0&&r>0)return 1;if(e.isNativeToken&&!t.isNativeToken)return-1;if(!e.isNativeToken&&t.isNativeToken)return 1;try{let n=BigInt(e.balance||`0`),r=BigInt(t.balance||`0`);if(n>r)return-1;if(n<r)return 1}catch(n){s.console.warn(`[trails-sdk] Failed to compare token balances:`,{tokenA:e.symbol,tokenB:t.symbol,err:n})}return 0}async function xh({account:e,tokenAddress:t,indexerGatewayClient:n,page:r,pageSize:i}){if(!e||!n)throw Error(`Account address and indexer client are required`);try{return await n.getTokenBalancesSummary({filter:{accountAddresses:[e],contractStatus:Oa.VERIFIED,contractTypes:[`ERC20`],contractWhitelist:t?[t]:void 0,omitNativeBalances:!1},page:mh(r,i)})}catch(t){if(os(t))return s.console.warn(`[trails-sdk] Network error fetching token balances, returning empty result:`,{error:t,account:e}),{balances:[],nativeBalances:[],page:ph};throw s.console.error(`[trails-sdk] Failed to fetch token balances summary:`,t),t}}async function Sh({accounts:e,indexerGatewayClient:t,page:n,pageSize:r}){if(!e.length||!t)throw Error(`At least one account address and indexer client are required`);let i=e.filter(e=>e&&e.length>0);if(!i.length)return{};try{let e=await t.getTokenBalancesSummary({filter:{accountAddresses:i,contractStatus:Oa.VERIFIED,contractTypes:[`ERC20`],omitNativeBalances:!1},page:mh(n,r)}),a=hh(i);gh(e.balances,a,fh,`erc20Tokens`),gh(e.nativeBalances,a,fh,`nativeTokens`);for(let t of i){let n=a[t.toLowerCase()];n&&(n.page=e.page??ph)}return a}catch(t){if(os(t))return s.console.warn(`[trails-sdk] Network error fetching token balances, returning empty result:`,{error:t,accounts:e}),hh(i);throw s.console.error(`[trails-sdk] Failed to fetch token balances summary for multiple accounts:`,t),t}}async function Ch({account:e,indexerGatewayClient:t,trailsClient:n}){let r=vh(await xh({account:e,indexerGatewayClient:t})),i=Array.from(r.values()),a=[];try{a=await op(n,i.map(e=>({chainId:e.chainId,tokenAddress:yh(e)?Cn:e.contractAddress,tokenSymbol:yh(e)?``:e.contractInfo?.symbol||``})))}catch(e){s.console.warn(`[trails-sdk] Price fetch failed, returning balances without prices:`,e)}let o=new Map;for(let e of a)o.set(_h(e.token.chainId,e.token.tokenAddress),e);return{balances:i.flatMap(e=>{let t=fh(e,o.get(_h(e.chainId,yh(e)?Cn:e.contractAddress)));return t?[t]:[]})}}async function wh({token:e,accountAddress:t,solanaRpcUrls:n}){let r=e.chainId;if(!r)throw Error(`Token must have a chainId`);if(W(r)){let r=t.trim(),i=e.contractAddress?.trim()??``;if(!i)throw Error(`Solana token must have contractAddress (mint)`);if(!Je(r,He.SOLANA)){s.console.warn(`[balances] Solana SPL balance needs a base58 owner (SVM wallet); got non-Solana address — returning 0`);let t=Qs(`0`,e.decimals??6);return{token:{...e,...t,isSufficientBalance:!0}}}let a=bt(i,e.chainId),o=Qs(a?await ah(r,n):await ch(r,i,n),a?e.decimals??9:e.decimals??6);return{token:{...e,...o,isSufficientBalance:!0}}}let i=Va(r),a=bt(e.contractAddress,r),o;o=a?await i.getBalance({address:t}):await i.readContract({address:e.contractAddress,abi:_n,functionName:`balanceOf`,args:[t]});let c=Qs(o.toString(),e.decimals);return{token:{...e,...c,isSufficientBalance:!0}}}async function Th({token:e,accountAddress:t,trailsClient:n,solanaRpcUrls:r}){let{token:i}=await wh({token:e,accountAddress:t,solanaRpcUrls:r}),a=e.chainId,o=bt(e.contractAddress,a),c;if(W(a)&&!o&&ze(e.contractAddress))c=1;else try{let t=await op(n,[W(a)&&Eh(e)?Dh(e):{chainId:a,tokenAddress:o?Cn:e.contractAddress,tokenSymbol:o?``:e.symbol}]);t.length>0&&t[0]?.priceUsd!==void 0&&(c=t[0].priceUsd)}catch(e){s.console.warn(`[trails-sdk] Price fetch failed, returning balance without prices:`,e)}let l=c===void 0?{}:ec(c),u={};if(c!==void 0&&i.balance){let t=Ys(i.balance,e.decimals)*c;Number.isFinite(t)&&(u=$s(t))}return{token:{...i,...l,...u}}}function Eh(e){return bt(e.contractAddress,e.chainId)}function Dh(e){if(Eh(e)){let t=e.contractAddress?.trim()||`11111111111111111111111111111111`;return{chainId:e.chainId,tokenAddress:t,tokenSymbol:e.symbol||`SOL`}}return{chainId:e.chainId,tokenAddress:e.contractAddress,tokenSymbol:e.symbol}}function Oh(e){let t=Dh(e);return`${t.chainId}:${t.tokenAddress}`}function kh(e){return`${e.token.chainId}:${e.token.tokenAddress}`}function Ah(e,t,n){let r=Eh(e),i=Qs(t,r?e.decimals??9:e.decimals??6),a=n===void 0?{}:ec(n),o={};if(n!==void 0&&t){let i=Ys(t,r?e.decimals??9:e.decimals??6)*n;Number.isFinite(i)&&(o=$s(i))}return{...e,...i,...a,...o,isSufficientBalance:!0}}async function jh({tokens:e,accountAddress:t,trailsClient:n,solanaRpcUrls:r}){let i=t.trim();if(!i||e.length===0)return[];let a=e.some(e=>Eh(e)),o=e.filter(e=>!Eh(e)),[c,l]=await Promise.all([a?ah(i,r):Promise.resolve(`0`),o.length>0?sh(i,r):Promise.resolve(new Map)]),u=e.filter(e=>Xe(e)===void 0),d=new Map;if(u.length>0)try{let e=await op(n,u.map(e=>Dh(e)));d=new Map(e.map(e=>[kh(e),e.priceUsd??0]))}catch(e){s.console.warn(`[trails-sdk] Solana funding token price fetch failed:`,e)}return e.map(e=>Ah(e,Eh(e)?c:l.get(e.contractAddress.trim())??`0`,Xe(e)??d.get(Oh(e))))}function Mh(e,t,n,r){let i=e.find(e=>(e.chainId??0)===r&&(ft(e.contractAddress,t,r)||!e.contractAddress&&t===Cn));if(!i?.balance)return!1;try{return typeof n==`bigint`?BigInt(i.balance)>=n:i.decimals==null?!1:BigInt(i.balance)>=Sn(n,i.decimals)}catch{return!1}}const Nh=5*Ee,Ph=30*Ee;function Fh(e){return e.map(e=>`${e.chainId}:${e.contractAddress??``}`).sort().join(`,`)}const Ih={all:[`balances`],multiAccounts:()=>[...Ih.all,`multiAccount`],multiAccount:(e,t,n)=>{let r=[...e].sort(),i=e.length>0&&!!t;return wr({queryKey:[...Ih.multiAccounts(),r.join(`,`),n?.page??null,n?.pageSize??null],queryFn:i?()=>Sh({accounts:r,indexerGatewayClient:t,page:n?.page,pageSize:n?.pageSize}):Tr,staleTime:Nh,gcTime:Ph,retry:ss(3),retryDelay:De})},details:()=>[...Ih.all,`detail`],withPrices:(e,t,n)=>{let r=!!e&&!!t&&!!n;return wr({queryKey:[...Ih.details(),e??null],queryFn:r?()=>Ch({account:e,indexerGatewayClient:t,trailsClient:n}):Tr,staleTime:Nh,gcTime:Ph,retry:ss(2),retryDelay:De})},totalUsd:(e,t,n)=>wr({...Ih.withPrices(e,t,n),select:({balances:e})=>e.reduce((e,t)=>e+(t.balanceUsd??0),0)}),sufficientToken:(e,t,n,r,i,a)=>{let o=Ih.withPrices(e,i,a),s=!!e&&!!t&&!!n&&!!r;return wr({...o,queryFn:s?o.queryFn:Tr,select:({balances:e})=>!t||!n||!r?!1:Mh(e,t,n,r)})},sufficientUsd:(e,t,n,r)=>{let i=Ih.withPrices(e,n,r);return wr({...i,queryFn:e&&t!=null?i.queryFn:Tr,select:({balances:e})=>e.reduce((e,t)=>e+(t.balanceUsd??0),0)>=Number(t)})},onchain:(e,t,n)=>{let r=!!e&&!!e.chainId&&!!t;return wr({queryKey:[...Ih.all,`onchain`,t??null,e?.contractAddress??null,e?.chainId??null],queryFn:r?()=>wh({token:e,accountAddress:t,solanaRpcUrls:n}):Tr,staleTime:Nh,gcTime:Ph,retry:ss(2),retryDelay:De})},onchainWithPrices:(e,t,n,r)=>{let i=!!e&&!!e.chainId&&!!t&&!!n;return wr({queryKey:[...Ih.all,`onchainWithPrices`,t??null,e?.contractAddress??null,e?.chainId??null],queryFn:i?()=>Th({token:e,accountAddress:t,trailsClient:n,solanaRpcUrls:r}):Tr,staleTime:Nh,gcTime:Ph,retry:ss(2),retryDelay:De})},solanaFundingTokens:(e,t,n,r)=>{let i=e.length>0&&!!t?.trim()&&!!n;return wr({queryKey:[...Ih.all,`solanaFundingTokens`,t??null,Fh(e),r?.join(`|`)??null],queryFn:i?()=>jh({tokens:e,accountAddress:t,trailsClient:n,solanaRpcUrls:r}):Tr,staleTime:Nh,gcTime:Ph,retry:ss(1),retryDelay:De})}};function Lh(e,t){let n=t??yo,r=new Date().toISOString();s.console.log(`[CACHE-FLOW] INVALIDATING cache`,{timestamp:r,account:e||`all`,action:`INVALIDATE_START`}),n.invalidateQueries({queryKey:Ih.all,refetchType:`all`}),s.console.log(`[CACHE-FLOW] INVALIDATE complete + ALL REFETCH triggered`,{timestamp:r,account:e||`all`,action:`INVALIDATE_AND_REFETCH_COMPLETE`})}async function Rh({account:e,token:t,amount:n,chainId:r,indexerGatewayClient:i,trailsClient:a}){let{balances:o}=await yo.ensureQueryData(Ih.withPrices(e,i,a));return Mh(o,t,n,r)}async function zh({account:e,targetAmountUsd:t,indexerGatewayClient:n,trailsClient:r}){let{balances:i}=await yo.ensureQueryData(Ih.withPrices(e,n,r));return i.reduce((e,t)=>e+(t.balanceUsd??0),0)>=Number(t)}async function Bh({account:e,indexerGatewayClient:t,trailsClient:n}){let{balances:r}=await yo.ensureQueryData(Ih.withPrices(e,t,n));return r.reduce((e,t)=>e+(t.balanceUsd??0),0)}function Vh(e){let t=e=>typeof e==`object`&&!!e,n=(e,n)=>t(e)&&e.code===n,r=e=>t(e)&&e.name===`InternalRpcError`&&typeof e.details==`string`&&e.details.includes(`Unrecognized chain ID`)&&e.details.includes(`wallet_switchEthereumChain`);if(n(e,4902)||e instanceof fn&&e.walk(e=>n(e,4902)||r(e)))return!0;if(t(e)){let r=e.data;if(t(r)){let e=r.originalError;if(n(e,4902))return!0}}return!1}async function Hh({walletClient:e,desiredChainId:t}){let n=!1;try{let n=await e.getChainId();if(n===t){s.console.log(`[trails-sdk] Chain already switched to:`,t);return}if(s.console.log(`[trails-sdk] Switching to chain:`,t,`currentChainId`,n),await e.switchChain({id:t}),n=await e.getChainId(),n!==t)throw Error(`Failed to switch chain`);s.console.log(`[trails-sdk] Chain switched to:`,t)}catch(r){let i=r;if(Vh(i)){let r=$(t,{usePublicRpc:!0});if(r){n=!0;try{return await e.addChain({chain:r}),Hh({walletClient:e,desiredChainId:t})}catch(e){i=e}}}if(R(i))throw s.console.error(`[trails-sdk] Chain switch failed:`,{boundary:i.boundary,code:i.code,details:i.details??null,error:i}),i;let a=k(i,{boundary:`wallet`,code:n?`chain.add`:`chain.switch`,message:`[trails-sdk] Failed to switch chain`,details:{desiredChainId:t}});throw s.console.error(`[trails-sdk] Chain switch failed:`,{boundary:a.boundary,code:a.code,details:a.details??null,error:a}),a}}function Uh(e){let t=e.slice(2);return{r:`0x${t.slice(0,64)}`,s:`0x${t.slice(64,128)}`,v:parseInt(t.slice(128,130),16)}}async function Wh({walletClient:e,signer:t,spender:n,tokenAddress:r,amount:i,chain:a,deadline:o=BigInt(xe(ye())+Se)}){if(!e.account)throw Error(`No account found`);let c=Va(a.id,0);if(!Pe(e.account.address,t))throw Error(`Connected wallet (${e.account.address}) does not match token owner (${t}). Please connect the wallet that owns the tokens.`);let l=await c.readContract({address:r,abi:[{name:`nonces`,type:`function`,stateMutability:`view`,inputs:[{name:`owner`,type:`address`}],outputs:[{name:``,type:`uint256`}]}],functionName:`nonces`,args:[t]}),u,d;try{let e=await c.readContract({address:r,abi:[{name:`eip712Domain`,type:`function`,stateMutability:`view`,inputs:[],outputs:[{name:`fields`,type:`bytes1`},{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`},{name:`salt`,type:`bytes32`},{name:`extensions`,type:`uint256[]`}]}],functionName:`eip712Domain`});u=e[1],d=e[2],s.console.log(`[trails-sdk] EIP-5267 eip712Domain() supported, using domain:`,{name:u,version:d})}catch{s.console.log(`[trails-sdk] EIP-5267 not supported, falling back to name()/version()`),u=await c.readContract({address:r,abi:[{name:`name`,type:`function`,stateMutability:`view`,inputs:[],outputs:[{name:``,type:`string`}]}],functionName:`name`}),d=`1`;try{d=await c.readContract({address:r,abi:[{name:`version`,type:`function`,stateMutability:`view`,inputs:[],outputs:[{name:``,type:`string`}]}],functionName:`version`}),s.console.log(`[trails-sdk] Token version from contract:`,d)}catch(e){s.console.warn(`[trails-sdk] Token does not implement version(), defaulting to '1'`,e)}}s.console.log(`[trails-sdk] Permit domain parameters:`,{name:u,version:d,chainId:a.id,verifyingContract:r,signer:t,spender:n,amount:i.toString(),nonce:l.toString(),deadline:o.toString()});let f=null;try{f=await c.readContract({address:r,abi:[{name:`DOMAIN_SEPARATOR`,type:`function`,stateMutability:`view`,inputs:[],outputs:[{name:``,type:`bytes32`}]}],functionName:`DOMAIN_SEPARATOR`}),s.console.log(`[trails-sdk] Contract domain separator:`,f)}catch(e){s.console.warn(`[trails-sdk] Could not read DOMAIN_SEPARATOR from contract:`,e)}let p={name:u,version:d,chainId:a.id,verifyingContract:r};if(f){let e=hn({domain:p});if(e.toLowerCase()!==f.toLowerCase()){s.console.debug(`[trails-sdk] Domain separator mismatch with chainId domain, retrying with salt`,{computedUint256Separator:e,onChain:f});let t=`0x${BigInt(a.id).toString(16).padStart(64,`0`)}`,n={name:u,version:d,verifyingContract:r,salt:t},i=hn({domain:n});i.toLowerCase()===f.toLowerCase()?p=n:s.console.warn(`[trails-sdk] Salt domain separator also mismatches, falling back to chainId domain`,{computedBytes32Separator:i,onChain:f})}}let m={Permit:[{name:`owner`,type:`address`},{name:`spender`,type:`address`},{name:`value`,type:`uint256`},{name:`nonce`,type:`uint256`},{name:`deadline`,type:`uint256`}]},h={owner:t,spender:n,value:i,nonce:l,deadline:o};await Hh({walletClient:e,desiredChainId:a.id}),s.console.log(`[trails-sdk] Requesting permit signature...`),s.console.log(`[trails-sdk] Permit data:`,h),await Nr(e);let g=await Wr(e.signTypedData({account:e.account,domain:p,types:m,primaryType:`Permit`,message:h}),`Permit signature`);s.console.log(`[trails-sdk] Permit signature created:`,g);let{v:_,r:v,s:y}=Uh(g);return{signature:g,deadline:o,v:_,r:v,s:y}}async function Gh({depositTokenAddress:e,depositTokenAmount:t,depositRecipient:n,onOriginSend:r,walletClient:i,chain:a,account:o,trailsClient:c,feeOptions:l,selectedFeeOption:u,checkoutOnHandlers:d,intentId:f,onTransactionStateChange:p,transactionStates:m,executeIntentFn:h,intentProtocol:g}){let _=a.id;if(s.console.log(`[trails-sdk] [gasless-flow] [fee-select] attemptGaslessDeposit called with:`,{originChainId:_,depositTokenAddress:e,depositTokenAmount:t,depositRecipient:n,hasFeeOptions:!!l,feeOptionsLength:l?.feeOptions?.length,selectedFeeOption:u,hasSelectedFeeOption:!!u}),g!==nn.v1_5)throw Error(`Unsupported intent protocol "${g}" for gasless deposits. Supported: ${nn.v1_5}`);s.console.log(`[trails-sdk] Using permit signature flow for gasless deposit`),s.console.log(`[trails-sdk] [gasless-flow] Switching to chain before permit/intent signatures`,{originChainId:_}),await Hh({walletClient:i,desiredChainId:_});try{let v=xe(ye())+Se,y=l?.feeOptions??[],b=y.length>0,x=u===null,S=BigInt(t),C=x?null:u??void 0;if(C&&b){let e=Pl(y,C);e&&(C=e,s.console.log(`[trails-sdk] Matched selectedFeeOption to latest fee option:`,{selectedFeeOption:C,matchedOption:e}))}let w=St(e);C?.amount&&C?.tokenAddress&&(St(C.tokenAddress)===w?(S+=BigInt(C.amount),s.console.log(`[trails-sdk] Fee token matches deposit token, including fee in required approval amount:`,{depositAmount:t,feeAmount:C.amount,feeOptionAddress:C.tokenAddress,depositTokenAddress:e,totalRequired:S.toString()})):s.console.log(`[trails-sdk] Fee token differs from deposit token, separate approval will be needed:`,{depositAmount:t,depositTokenAddress:e,feeAmount:C.amount,feeOptionAddress:C.tokenAddress,depositTokenRequired:S.toString()}));let T=!bt(w);s.console.log(`[trails-sdk] [gasless-flow] Checking permit requirements`,{userAddress:o.address,tokenAddress:e,depositAmount:t,requiredAmount:S.toString(),intentAddress:n,chainID:_,deadline:v,intentProtocol:g,shouldAttachPermit:T});let E,D,O;if(T){s.console.log(`[trails-sdk] Getting permit signature for deposit token`),O=S;let r=n;s.console.log(`[trails-sdk] [intent-protocol] [gasless-flow] Using specific permit to intent address`,{permitAmount:O.toString(),spender:r,target:`depositRecipient (intent address)`}),s.console.log(`[trails-sdk] Using permit amount for gasless deposits`,{depositAmount:t,depositTokenAddress:e,requiredAmount:S.toString(),permitAmount:O.toString(),spender:r}),d?.triggerCheckoutSignatureRequest&&d.triggerCheckoutSignatureRequest();let c;try{c=await Wh({walletClient:i,signer:o.address,spender:r,tokenAddress:e,amount:O,chain:a,deadline:BigInt(v)}),E=c.signature,D=Number(c.deadline),d?.triggerCheckoutSignatureConfirmed&&d.triggerCheckoutSignatureConfirmed()}catch(e){throw F(e)&&d?.triggerCheckoutSignatureRejected&&d.triggerCheckoutSignatureRejected(e),e}s.console.log(`[trails-sdk] Deposit token permit signature obtained`)}if(s.console.log(`[trails-sdk] Calling executeIntent with depositSignature`,{usePermit:T,hasFee:!!l,hasIntentId:!!f}),!f)throw Error(`[trails-sdk] intentId is required for gasless deposits. The calling code must commit the intent first using commitIntent() and pass the intentId.`);if(!C)throw s.console.error(`[trails-sdk] Missing selected fee option for gasless deposit signature`,{selectedFeeOption:C}),Error(`[trails-sdk] selectedFeeOption is required for gasless deposits`);let k={permitSignature:E,permitDeadline:D,permitAmount:O,selectedGasFeeOption:C,deadline:v};if(s.console.log(`[trails-sdk] Executing intent with gasless deposit signature`,{intentId:f,depositSignature:k}),await(h||c.executeIntent.bind(c))({intentId:f,depositSignature:k}),s.console.log(`[trails-sdk] Intent execution submitted to backend. Transaction monitoring should happen via intent status polling.`),r&&r(),m?.[0]&&p){m[0].state=`pending`;try{p(m)}catch(e){s.console.error(`[trails-sdk] Error calling onTransactionStateChange:`,e)}}}catch(e){throw s.console.error(`[trails-sdk] Error in Intent Entrypoint gasless deposit with EIP-2162 permit signature`,e),e}}function Kh(e,t,n,r,i){if(i!=null&&W(i))return s.console.log(`[trails-sdk] [gasless-flow] getDoGasless: Skipping gasless flow for Solana origin chain`),!1;if(ma(r))return s.console.log(`[trails-sdk] [gasless-flow] getDoGasless: Skipping gasless flow for Sequence Embedded wallet`),!1;let a=!!(t&&t.feeOptions?.length>0);if(n===null)return s.console.log(`[trails-sdk] [gasless-flow] [fee-select] getDoGasless: User explicitly selected native gas (null)`),!1;if(!n&&!a)return s.console.log(`[trails-sdk] [gasless-flow] [fee-select] getDoGasless: No fee token selected and no fee options available`),!1;let o=!n||bt(n.tokenAddress);return bt(e)?(s.console.log(`[trails-sdk] [gasless-flow] getDoGasless: Origin token is native, skipping gasless`),!1):o?(s.console.log(`[trails-sdk] [gasless-flow] [fee-select] getDoGasless: Fee token is native gas, skipping gasless`,{selectedFeeOption:n}),!1):(s.console.log(`[trails-sdk] [gasless-flow] [fee-select] getDoGasless decision: Using gasless`,{originTokenAddress:e,hasFeeOptions:a,selectedFeeOption:n,feeOptionsCount:t?.feeOptions?.length||0}),!0)}async function qh({publicClient:e,depositAmount:t,txHash:n,abortSignal:r,maxRetries:i=60,onDepositDetected:a}){if(s.console.log(`[trails-sdk] Starting resilient deposit tracking`,{hasHash:!!n,txHash:n,depositAmount:t}),!n)return s.console.warn(`[trails-sdk] Resilient deposit tracker requires a tx hash; skipping receipt wait`),null;if(r?.aborted)return s.console.log(`[trails-sdk] Deposit tracking aborted by signal`),null;let o=n,c=i*vp.TRANSACTION_RECEIPT,l=null;try{let t=e.waitForTransactionReceipt({hash:n,retryCount:i,retryDelay:vp.TRANSACTION_RECEIPT,onReplaced:e=>{o=e.transaction.hash,s.console.log(`[trails-sdk] Deposit transaction replaced while waiting for receipt`,{reason:e.reason,replacedHash:e.replacedTransaction.hash,replacementHash:e.transaction.hash})}}),u=new Promise((e,t)=>{l=setTimeout(()=>{t(Error(`Timed out waiting for transaction receipt`))},c)}),d=new Promise((e,t)=>{r&&r.addEventListener(`abort`,()=>t(Error(`Aborted while waiting for transaction receipt`)),{once:!0})}),f=await Promise.race([t,u,d]);return s.console.log(`[trails-sdk] Deposit transaction receipt found`,{hash:f.transactionHash,status:f.status,blockNumber:f.blockNumber}),a&&a(o,f),f}catch(e){return s.console.warn(`[trails-sdk] Could not get receipt for known transaction hash`,{txHash:n,resolvedHash:o,timeoutMs:c,error:e?.message}),null}finally{l&&clearTimeout(l)}}function Jh(e){if(!e)return!1;let t=e?.message?.toLowerCase()||``,n=e?.code,r=typeof n==`string`?n.toLowerCase():n;return n===4001||r===`action_rejected`||t.includes(`user rejected`)||t.includes(`user denied`)||t.includes(`rejected by user`)?!1:!!(t.includes(`wallet timeout`)||t.includes(`an unknown rpc error occurred`)||t.includes(`network`)||t.includes(`timeout`)||t.includes(`rpc`)||t.includes(`connection`)||t.includes(`fetch`)||r===`network_error`||r===`timeout`||n===-32603)}async function Yh({originTokenAddress:e,depositAmount:t,onOriginSend:n,publicClient:r,walletClient:i,originChainId:a,chain:o,account:c,originIntentAddress:l,onTransactionStateChange:u,depositTransaction:d,transactionStates:f,originTokenSymbol:p,destinationTokenSymbol:m,depositAmountUsd:h,checkoutOnHandlers:g,sequenceProjectAccessKey:_,sequenceIndexerUrl:v,abortSignal:y}){s.console.log(`[trails-sdk] [standard-deposit] initiating deposit...`);let b=null;if(!d)throw Error(`depositTransaction is required from API`);if(!d.to)throw Error(`depositTransaction.to is required from API`);if(!d.data)throw Error(`depositTransaction.data is required from API`);if(d.value==null)throw Error(`depositTransaction.value is required from API`);if(o.id!==d.chainId)throw Error(`Chain ID mismatch: expected ${o.id}, got ${d.chainId}`);let x={to:d.to,data:d.data,value:BigInt(d.value),chain:o};await Hh({walletClient:i,desiredChainId:a}),s.console.log(`[trails-sdk] using sendTransaction`),Bo(`Payment Started`,`Waiting for wallet confirmation...`,`info`),g?.triggerCheckoutSignatureRequest&&g.triggerCheckoutSignatureRequest();let S=null,C=null;try{S=await Fm(c,i,x,{depositTokenAmountUsd:h?.toString()}),s.console.log(`[trails-sdk] origin tx`,S),g?.triggerCheckoutSignatureConfirmed&&g?.triggerCheckoutSignatureConfirmed?.()}catch(e){if(C=e,s.console.error(`[trails-sdk] Error sending deposit transaction`,e),F(e))throw g?.triggerCheckoutSignatureRejected&&g.triggerCheckoutSignatureRejected(e),e;if(!Jh(e))throw e;s.console.log(`[trails-sdk] Deposit send failed with recoverable error, will attempt polling`,{error:e?.message})}if(S){if(n&&n(),f[0]){f[0].state=`pending`,f[0].transactionHash=S;try{u(f)}catch(e){s.console.error(`[trails-sdk] Error calling onTransactionStateChange:`,e)}}try{let e=await r.waitForTransactionReceipt({hash:S,retryCount:10,onReplaced:e=>{s.console.log(`[trails-sdk] Deposit transaction replaced`,{reason:e.reason,replacedHash:e.replacedTransaction.hash,replacementHash:e.transaction.hash})}});Bo(`Transfer Confirmed`,`Your transaction on ${$(a)?.name||`chain`} has been confirmed`,`info`),yf({transactionHash:S,chainId:a,userAddress:c.address,blockNumber:Number(e.blockNumber),originIntentAddress:l,originTokenSymbol:p,destinationTokenSymbol:m,depositTokenAmountUsd:h?.toString()}),s.console.log(`[trails-sdk] receipt`,e),b=e}catch(n){s.console.warn(`[trails-sdk] Could not get receipt, using resilient tracking`,{txHash:S,error:n?.message}),b=await qh({publicClient:r,originChainId:a,originIntentAddress:l,originTokenAddress:e,depositAmount:t,txHash:S,abortSignal:y,sequenceProjectAccessKey:_,sequenceIndexerUrl:v,onDepositDetected:(e,t)=>{Bo(`Transfer Confirmed`,`Your transaction on ${$(a)?.name||`chain`} has been confirmed`,`info`),t?.status===`success`&&e&&yf({transactionHash:e,chainId:a,userAddress:c.address,blockNumber:Number(t.blockNumber||0),originIntentAddress:l,originTokenSymbol:p,destinationTokenSymbol:m,depositTokenAmountUsd:h?.toString()})}})}}else if(C&&Jh(C)&&(s.console.log(`[trails-sdk] Starting resilient deposit tracking after send failure`),Bo(`Checking Transaction`,`Verifying transaction status...`,`info`),b=await qh({publicClient:r,originChainId:a,originIntentAddress:l,originTokenAddress:e,depositAmount:t,txHash:null,abortSignal:y,sequenceProjectAccessKey:_,sequenceIndexerUrl:v,onDepositDetected:(e,t)=>{if(s.console.log(`[trails-sdk] Deposit detected via resilient tracking`,{hash:e}),n&&n(),f[0]&&e){f[0].state=`pending`,f[0].transactionHash=e;try{u(f)}catch(e){s.console.error(`[trails-sdk] Error calling onTransactionStateChange:`,e)}}Bo(`Transfer Confirmed`,`Your transaction on ${$(a)?.name||`chain`} has been confirmed`,`info`),t?.status===`success`&&e&&yf({transactionHash:e,chainId:a,userAddress:c.address,blockNumber:Number(t.blockNumber||0),originIntentAddress:l,originTokenSymbol:p,destinationTokenSymbol:m,depositTokenAmountUsd:h?.toString()})}}),!b))throw Error(`Deposit transaction could not be confirmed. Please check your wallet and try again.`);return b}async function Xh({queryClient:e,originTokenAddress:t,chain:n,account:r,depositAmount:i,originIntentAddress:a,onOriginSend:o,publicClient:c,walletClient:l,destinationTokenDecimals:u,sourceTokenDecimals:d,sourceTokenPriceUsd:f,destinationTokenPriceUsd:p,swapAmount:m,onTransactionStateChange:h,transactionStates:g,fundMethod:_,originTokenSymbol:v,destinationTokenSymbol:y,depositAmountUsd:b,feeOptions:x,trailsClient:S,selectedFeeOption:C,walletId:w,abortSignal:T,checkoutOnHandlers:E,intentId:D,executeIntentFn:O,depositRecipientOverride:k,isSameChainSameToken:A,destinationCalldata:j,sequenceProjectAccessKey:M,sequenceIndexerUrl:N,depositTransaction:P,intentProtocol:F}){let I=null,ee=n.id,te=k||a;if(s.console.log(`[trails-sdk] [intent-protocol] attemptUserDepositTx called`,{intentProtocol:F,fundMethod:_,intentId:D,depositRecipientOverride:k,effectiveDepositRecipient:te,isSameChainSameToken:A}),_&&_!==`wallet`)return s.console.log(`[trails-sdk] Skipping wallet deposit for external funding mode - fundMethod is:`,_),null;let ne=Kh(t,x,C,w,ee);if(s.console.log(`[trails-sdk] [gasless-flow] [fee-select] doGasless check results:`,{doGasless:ne,hasFeeOptions:!!x,feeOptionsCount:x?.feeOptions?.length||0,selectedFeeOption:C,selectedFeeOptionSet:C!=null,originTokenAddress:t,isNotNative:!bt(t)}),ne){s.console.log(`[trails-sdk] [intent-protocol] [gasless-flow] Entering gasless deposit flow`,{intentProtocol:F,doGasless:ne});try{await Gh({depositTokenAddress:t,depositTokenAmount:i,depositRecipient:a,onOriginSend:o,walletClient:l,chain:n,account:r,trailsClient:S,feeOptions:x,selectedFeeOption:C,abortSignal:T,checkoutOnHandlers:E,intentId:D,onTransactionStateChange:h,transactionStates:g,executeIntentFn:O,intentProtocol:F}),I=null}catch(e){if(s.console.log(`[trails-sdk] gassless attempt failed`,e),ne)throw e}}return!I&&!ne&&(I=await Yh({queryClient:e,originTokenAddress:t,depositAmount:i,originIntentAddress:a,onOriginSend:o,publicClient:c,walletClient:l,originChainId:ee,chain:n,account:r,sourceTokenPriceUsd:f,destinationTokenPriceUsd:p,swapAmount:m,destinationTokenDecimals:u,sourceTokenDecimals:d,onTransactionStateChange:h,transactionStates:g,originTokenSymbol:v,destinationTokenSymbol:y,depositAmountUsd:b,checkoutOnHandlers:E,sequenceProjectAccessKey:M,sequenceIndexerUrl:N,abortSignal:T,depositTransaction:P})),I}function Zh(e,t){let n=t?.includes(`dev`),r=new URL(t),i=r.hostname,a;return a=n?i.replace(/^dev-indexer\./,`dev-${e}-indexer.`):i.replace(/^indexer\./,`${e}-indexer.`),`${r.protocol}//${a}`}function Qh(e,t){let n={[Tn.id]:`arbitrum`,[Mn.id]:`base`,[Nn.id]:`base-sepolia`,[Yn.id]:`optimism`,[Zn.id]:`polygon`,[Kn.id]:`mainnet`,[wn.id]:`apechain`,[En.id]:`arbitrum-nova`,[On.id]:`avalanche`,[An.id]:`b3`,[Vn.id]:`gnosis`,[tr.id]:`soneium`,[Ln.id]:`bsc`,421613:`arbitrum-nova-sepolia`,[zn.id]:`etherlink`,[Gn.id]:`katana`,[qn.id]:`monad`}[e];if(n)return Zh(n,t)}function $h(){let{sequenceIndexerUrl:e,trailsApiKey:t}=Vx();return J(()=>new Aa(e,t),[e,t])}function eg(e){let t=e?.toLowerCase();return!!(t&&/0{10,}$/.test(t))}function tg(e){return!!(e&&!eg(e))}function ng(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.txnHash==`string`&&typeof t.chainId==`number`&&typeof t.timestamp==`string`&&Array.isArray(t.transfers)}async function rg(e,t){if(!e?.chainId||!t?.chainId||!e||!t||!(e.blockNumber||e.transactionHash)||!(t.blockNumber||t.transactionHash)||e.blockNumber===t.blockNumber&&e.transactionHash===t.transactionHash)return 0;try{if(e.txnMinedAt&&t.txnMinedAt){let n=xe(new Date(e.txnMinedAt).getTime()),r=xe(new Date(t.txnMinedAt).getTime())-n;return r<1?1:r}return s.console.warn(`[trails-sdk] txnMinedAt not available for transactions, cannot calculate time difference`),0}catch(e){return s.console.error(`[trails-sdk] Error calculating transaction time difference:`,e),0}}async function ig({chainId:e,accountAddress:t,pageSize:n=10,page:r=1,includeMetadata:i=!0,abortSignal:a,apiKey:o,indexerUrl:c}){if(!o)throw Error(`Trails api key is required`);let l=`account-tx-history-${e}-${t}-${r}-${Date.now()}`,u=new AbortController;$a.register(l,u);try{if(a?.aborted||u.signal.aborted)throw s.console.log(`[trails-sdk] Aborting account transaction history fetch`),Error(`Operation aborted`);let l=Qh(e,c);if(!l)throw Error(`Unsupported chain ID: ${e}`);if(a?.aborted||u.signal.aborted)throw s.console.log(`[trails-sdk] Aborting account transaction history fetch before request`),Error(`Operation aborted`);let d=await new ka(l,o).getTransactionHistory({filter:{accountAddress:St(t)},includeMetadata:i,page:{page:r,pageSize:n}},{},a||u.signal),f=d.transactions.filter(ng).map(e=>({...e,transfers:e.transfers??[],explorerUrl:Xa({txHash:e.txnHash,chainId:e.chainId}),chainName:$(e.chainId)?.name}));return{...d,transactions:f}}catch(e){throw e instanceof Error&&e.name===`AbortError`?(s.console.log(`[trails-sdk] Account transaction history fetch was aborted`),Error(`Operation aborted`,{cause:e})):(s.console.error(`[trails-sdk] Error fetching transaction history:`,e),e)}finally{$a.unregister(l)}}function ag({chainId:e,accountAddress:t,pageSize:n=10,page:r=1,includeMetadata:i=!0,abortSignal:a,refetchInterval:o=!1}){let{trailsApiKey:s,sequenceIndexerUrl:c}=Vx(),{data:l,isLoading:u,error:d}=Or({queryKey:[`accountTransactionHistory`,e,t,n,r,i],queryFn:async({signal:o})=>{if(!(!e||!t))return await ig({chainId:e,accountAddress:t,pageSize:n,page:r,includeMetadata:i,abortSignal:a||o,apiKey:s||``,indexerUrl:c})},enabled:!!(e&&t),staleTime:5*Ee,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchInterval:o,retry:10,refetchOnReconnect:!0});return{data:l,isLoading:u,error:d}}const og=15*ge;function sg(e){switch(e){case`onDepositTransactionFound`:return`receipt-poller.on-deposit-transaction-found`;case`onOriginTransactionFound`:return`receipt-poller.on-origin-transaction-found`;case`onDestinationTransactionFound`:return`receipt-poller.on-destination-transaction-found`;case`onReceiptUpdate`:return`receipt-poller.on-receipt-update`}}function cg(e){return e===rn.SUCCEEDED||e===rn.FAILED||e===rn.REFUNDED||e===rn.ABORTED}function lg(e){return e===$t.FILLED||e===$t.REFUNDED||e===$t.FAILED}function ug(e,t){return!!(t&&(!e.edge||!lg(e.edge.edgeStatus)))}async function dg(e){let{intentId:t,trailsClient:n,callbacks:r,maxWaitTime:i=og,pollInterval:o=150,abortSignal:c,waitForEdgeCompletion:l}=e,u=Date.now(),d,f,p,m=null,h=[],g={onDepositTransactionFound:0,onOriginTransactionFound:0,onDestinationTransactionFound:0,onReceiptUpdate:0},_=e=>{g[e]=0},v=(e,n,r)=>{let i=g[e]+1;g[e]=i;let o=k(n,{boundary:`sdk`,code:sg(e),details:{intentId:t,receiptStatus:r.status,callbackName:e,failureStreak:i}});s.console.error(`[trails-sdk] Poller callback failed`,{intentId:t,callbackName:e,receiptStatus:r.status,failureStreak:i,boundary:o.boundary,code:o.code,error:a(o)}),i>=3&&i%3==0&&s.console.warn(`[trails-sdk] Poller callback failure escalation`,{intentId:t,callbackName:e,receiptStatus:r.status,failureStreak:i,escalationThreshold:3,boundary:o.boundary,code:o.code,details:o.details??null})};s.console.log(`[trails-sdk] Starting unified intent receipt polling`,{intentId:t,maxWaitTime:i,pollInterval:o});try{for(;Date.now()-u<i;){if(c?.aborted)return s.console.log(`[trails-sdk] Intent receipt polling aborted via signal`,{intentId:t}),m;try{let e=await n.waitIntentReceipt({intentId:t,lastReceiptStates:h},void 0,c),i=e.intentReceipt;if(m=i,h=e.receiptStates,s.console.log(`[trails-sdk] Unified intent receipt update`,{intentId:t,status:i.status,done:e.done,depositTxHash:i.depositTransaction?.txnHash,originTxHash:i.originTransaction?.txnHash,destinationTxHash:i.destinationTransaction?.txnHash,edgeStatus:i.edge?.edgeStatus}),i.depositTransaction?.txnHash&&i.depositTransaction.txnHash!==d&&(d=i.depositTransaction.txnHash,s.console.log(`[trails-sdk] Deposit transaction discovered via unified poller`,{intentId:t,txHash:d}),r?.onDepositTransactionFound))try{await r.onDepositTransactionFound(d,i),_(`onDepositTransactionFound`)}catch(e){v(`onDepositTransactionFound`,e,i)}if(i.originTransaction?.txnHash&&i.originTransaction.txnHash!==f&&(f=i.originTransaction.txnHash,s.console.log(`[trails-sdk] Origin transaction discovered via unified poller`,{intentId:t,txHash:f}),r?.onOriginTransactionFound))try{await r.onOriginTransactionFound(f,i),_(`onOriginTransactionFound`)}catch(e){v(`onOriginTransactionFound`,e,i)}if(i.destinationTransaction?.txnHash&&i.destinationTransaction.txnHash!==p&&(p=i.destinationTransaction.txnHash,s.console.log(`[trails-sdk] Destination transaction discovered via unified poller`,{intentId:t,txHash:p}),r?.onDestinationTransactionFound))try{await r.onDestinationTransactionFound(p,i),_(`onDestinationTransactionFound`)}catch(e){v(`onDestinationTransactionFound`,e,i)}if(r?.onReceiptUpdate)try{await r.onReceiptUpdate(i,e.done,e.receiptStates),_(`onReceiptUpdate`)}catch(e){v(`onReceiptUpdate`,e,i)}let a=!!(i.summary?.finishedAt||i.destinationTransaction?.txnMinedAt||i.destinationTransaction?.txnHash),u=i.destinationTransaction?.status===`SUCCEEDED`,g=ug(i,l);if(u&&a&&!g)return s.console.warn(`[trails-sdk] Treating receipt as complete via destination-success fallback`,{intentId:t,status:i.status,destinationTxHash:i.destinationTransaction?.txnHash,hasFinishedMarker:a}),i;if(e.done){if(g){s.console.log(`[trails-sdk] Intent receipt done, waiting for edge completion`,{intentId:t,status:i.status,edgeStatus:i.edge?.edgeStatus}),await new Promise(e=>setTimeout(e,o));continue}return s.console.log(`[trails-sdk] Intent receipt polling complete`,{intentId:t,status:i.status}),i}}catch(e){if(c?.aborted)return s.console.log(`[trails-sdk] Intent receipt request aborted via signal`,{intentId:t}),m;let n=ee(e,{boundary:`sdk`,code:`receipt-poller.wait`,apiBoundary:`trails-api`,details:{intentId:t}});s.console.warn(`[trails-sdk] Error polling intent receipt`,{intentId:t,boundary:n.boundary,code:n.code,error:a(n)})}await new Promise(e=>setTimeout(e,o))}return s.console.warn(`[trails-sdk] Intent receipt polling timeout`,{intentId:t,maxWaitTime:i}),m}catch(e){let n=ee(e,{boundary:`sdk`,code:`receipt-poller.poll`,apiBoundary:`trails-api`,details:{intentId:t}});return s.console.error(`[trails-sdk] Unexpected error in intent receipt polling`,{intentId:t,boundary:n.boundary,code:n.code,error:a(n)}),m}}function fg(e){let{transactionStates:t}=e;return t.map(e=>({id:e.id,transactionHash:``,explorerUrl:``,blockNumber:void 0,chainId:e.chainId,state:`pending`,label:e.label,txnMinedAt:void 0}))}function pg(e,t,n,r){return e.map(e=>{if(e.label!==t)return e;let i={...e};i.transactionHash=n.transactionHash,i.explorerUrl=Xa({txHash:n.transactionHash,chainId:r}),i.blockNumber=Number(n.blockNumber),i.state=n.status===`success`?`confirmed`:`failed`;try{let e=Qm(n);i.decodedTokenSweeperEvents=e;let a=$m(n);i.decodedGuestModuleEvents=a;let o=e.findIndex(e=>e.type===`Refund`||e.type===`RefundAndSweep`)!==-1,c=e.findIndex(e=>e.type===`Sweep`)!==-1&&a.findIndex(e=>e.type===`CallFailed`)!==-1;i.refunded=o||c,s.console.log(`[trails-sdk] Transaction state decoded events`,{id:i.id,label:t,chainId:r,callFailed:a.filter(e=>e.type===`CallFailed`).length,sweeperEvents:e.length,refunded:i.refunded})}catch(e){s.console.error(`[trails-sdk] Error decoding transaction events`,e)}return i})}function mg(e,t,n){return t<0||t>=e.length?e:e.map((e,r)=>r===t?{...e,...n}:e)}function hg(e){return e?e===`SUCCEEDED`?`confirmed`:e===`ABORTED`?`aborted`:e===`FAILED`||e===`ERRORED`||e===`REVERTED`?`failed`:`pending`:null}function gg(e){return e.trim().toLowerCase()}function _g(e){let t=e?.trim().toUpperCase();return t?t===`FILLED`||t===`SUCCEEDED`?`confirmed`:t===`FAILED`||t===`REFUNDED`||t===`ABORTED`?t===`ABORTED`?`aborted`:`failed`:`pending`:null}function vg(e){let t=gg(e.id??``),n=gg(e.label??``);return t===`edge`||t.startsWith(`edge.`)||t.startsWith(`edge-`)||/deposit.*(?:solana|edge)/.test(n)?`edge`:t.startsWith(`destination.`)||t===`origin.execute`?`destination`:t===`origin.deposit`||t===`origin.fund`?`deposit`:t.startsWith(`origin.`)?`origin`:n.includes(`fund intent`)||n.includes(`deposit on`)||n.includes(`deposit`)&&!n.includes(`swap`)?`deposit`:n.includes(`swap`)||n.includes(`bridge`)?`origin`:n.includes(`receive`)||n.includes(`execute`)?`destination`:null}function yg(e,t){return e.findIndex(e=>vg(e)===t)}function bg(e,t,n){let r=yg(e,`edge`);return r<0?(s.console.warn(`[trails-sdk] Unable to attach edge deposit transaction hash; no edge transaction state found`,{chainId:n,transactionHash:t,stateIds:e.map(e=>e.id)}),[{id:`edge-deposit`,label:`Deposit on Solana`,chainId:n,transactionHash:t,explorerUrl:Xa({txHash:t,chainId:n}),blockNumber:void 0,state:`confirmed`,txnMinedAt:void 0},...e]):mg(e,r,{chainId:n,transactionHash:t,explorerUrl:Xa({txHash:t,chainId:n}),state:`confirmed`})}function xg(e){return e?{status:e.status,txnHash:e.txnHash,txnMinedAt:e.txnMinedAt,chainId:e.chainId}:null}function Sg(e){return tg(e.depositTransaction?.txnHash)}function Cg(e,t){if(t===`edge`){let t=e.edge;if(!t)return null;let n=t.initTransactionHash||t.edgeStatus===`FILLED`?`SUCCEEDED`:t.edgeStatus??null;return n===`PENDING`||n===`DEPOSITED`?null:{status:n,txnHash:t.initTransactionHash??null,txnMinedAt:t.createdAt??null,chainId:101}}if(t===`deposit`)return xg(e.depositTransaction);if(t===`origin`)return xg(e.originTransaction);let n=xg(e.destinationTransaction);return tg(n?.txnHash)||n?.status?n:Sg(e)?xg(e.originTransaction):n}function wg(e,t){if(!(!t?.length||e===`edge`)){if(e===`deposit`)return t[0];if(e===`origin`)return t[1];if(e===`destination`)return t[2]}}function Tg(e,t){return t!==void 0&&t===101&&e.chainId===792703809?e.chainId:t??e.chainId}function Eg(e){let{currentStates:t,receipt:n,receiptStates:r}=e;if(t.length===0)return{transactionStates:t,changed:!1};let i=[...t],a=!1,o=(e,t,n,r,o)=>{let s=i[e];if(!s)return;let c=vg(s)===`edge`?_g(t)??hg(t):hg(t);if(!c)return;let l=s.state===`confirmed`||s.state===`failed`||s.state===`aborted`;if(c===`pending`&&l)return;let u=Tg(s,o),d=tg(n)?n:s.transactionHash||``,f=d?Xa({txHash:d,chainId:u}):s.explorerUrl||``;(s.state!==c||s.transactionHash!==d||s.explorerUrl!==f||s.txnMinedAt!==(r||void 0)||s.chainId!==u)&&(i[e]={...s,chainId:u,state:c,transactionHash:d,explorerUrl:f,txnMinedAt:r||void 0},a=!0)};for(let e=0;e<i.length;e++){let t=i[e];if(!t)continue;let a=vg(t);if(!a)continue;let s=Cg(n,a);if(!s)continue;let c=wg(a,r);o(e,c??s.status,s.txnHash,s.txnMinedAt,s.chainId)}return{transactionStates:a?i:t,changed:a}}function Dg(e){return e.depositTransaction?.status===`SUCCEEDED`||e.originTransaction?.status===`MINING`||e.originTransaction?.status===`SUCCEEDED`||e.destinationTransaction?.status===`MINING`||e.destinationTransaction?.status===`SUCCEEDED`}function Og(e){return e===`SUCCEEDED`?`confirmed`:e===`FAILED`||e===`ERRORED`||e===`ABORTED`||e===`REVERTED`?`failed`:`pending`}function kg(e,t){let n=e.findIndex(e=>e.label===`Refund`||e.id?.includes(`refund`));if(n>=0){let r=e[n],i=t.chainId??r?.chainId??0;return mg(e,n,{transactionHash:t.txnHash,explorerUrl:t.txnHash?Xa({txHash:t.txnHash,chainId:i}):``,state:Og(t.status)})}let r=t.chainId??0,i={id:`refund-${r}`,label:`Refund`,chainId:r,transactionHash:t.txnHash??``,explorerUrl:t.txnHash?Xa({txHash:t.txnHash,chainId:r}):``,state:Og(t.status),refunded:!0},a=[...e],o=a.length;for(let e=a.length-1;e>=0;e--)if(a[e]?.chainId===r){o=e+1;break}return a.splice(o,0,i),a}function Ag(e,t){return e===void 0?!1:e===null?t?.find(e=>bt(e.tokenAddress))?.isPassthroughEligible===!0:e.isPassthroughEligible===!0}function jg(e,t,n){return e===!0&&Ag(t,n)}function Mg(e){return e?e.originToken?.contractAddress?.toLowerCase()===e.destinationToken?.contractAddress?.toLowerCase()&&e.originChain?.id===e.destinationChain?.id:!1}function Ng(e){return e?.decodedGuestModuleEvents?.some(e=>e.type===`CallFailed`)??!1}const Pg=new Set([`edge.destination.receive`,`solana-fill`]);function Fg(e){let t=e.id?.trim().toLowerCase();return!!t&&Pg.has(t)}function Ig(e){return e.some(Fg)}function Lg(e){let t=e.findIndex(e=>e.id===`origin.execute`||e.label===`Execute`);if(t>=0)return t;for(let t=e.length-1;t>=0;t--){let n=e[t];if(n&&n.state===`pending`&&!Fg(n))return t}return-1}function Rg(e,t){let n=!1,r=e.map(e=>Fg(e)?(n=!0,{...e,transactionHash:t,explorerUrl:Xa({txHash:t,chainId:e.chainId}),state:`confirmed`}):e);return n?r:e}async function zg(e,t,n,r){let i=e.walletClient,{queryClient:a,account:o,onTransactionStateChange:c,originTokenDecimals:l,originTokenSymbol:u,destinationTokenSymbol:d,swapAmount:f,destinationCalldata:p,sourceTokenPriceUsd:m,mode:h,fundMethod:g=`wallet`,checkoutOnHandlers:_,walletId:v}=e,y=a??yo,{onOriginSend:b,depositTransactionHash:x}=r,S=e.chain,C=S.id,w=W(C),T=e.publicClient??Va(w?e.destinationChainId:S.id),E=Number(vn(BigInt(f),l)),D=nc({amount:E,usdPrice:m});if(n[0]){n[0].state=`pending`;try{c(n)}catch(e){s.console.error(`[trails-sdk] Error calling onTransactionStateChange:`,e)}}if(Bo(`Payment Started`,`Waiting for wallet confirmation...`,`info`),t.chainId!==C)throw Error(`Chain ID mismatch: expected ${C}, got ${t.chainId}`);let{to:O,data:k,value:A,chainId:j}=t;s.console.log(`[trails-sdk] Executing passthrough with depositTransaction:`,{to:O,data:k,value:A,chainId:j});let M=x;M||(M=await Fm(o,i,{to:O,data:k,value:BigInt(A),chain:S},{transactionType:`origin_call`,depositTokenAmountUsd:D?.toString()}));let N=M;b&&b();let P=await T.waitForTransactionReceipt({hash:N,onReplaced:e=>{s.console.log(`[trails-sdk] Passthrough deposit transaction replaced`,{reason:e.reason,replacedHash:e.replacedTransaction.hash,replacementHash:e.transaction.hash})}});return s.console.log(`[trails-sdk] Passthrough receipt:`,P),yf({transactionHash:N,chainId:C,userAddress:o.address,blockNumber:Number(P.blockNumber),originTokenAddress:e.originTokenAddress,depositTokenAmountUsd:D}),Bo(`Transfer Confirmed`,`Your transaction on ${$(C)?.name||`chain`} has been confirmed`,`info`),c(pg(n,n[0]?.label||`Execute`,P,C)),P.status===`success`?(cf({userAddress:o.address,originTxHash:P.transactionHash,originChainId:C,mode:h,fundMethod:g,originTokenAddress:e.originTokenAddress,originTokenSymbol:u,originTokenAmount:f,originTokenAmountFormatted:E.toString(),destinationTokenAddress:e.originTokenAddress,destinationTokenSymbol:d,depositTokenAmount:f,depositTokenAmountFormatted:E.toString(),depositTokenAmountUsd:D,destinationTokenAmount:f,destinationTokenAmountFormatted:E.toString(),destinationTokenAmountUsd:D,originTokenDecimals:l,destinationTokenDecimals:l,walletId:v,destinationCalldata:p}),Lh(void 0,y),_?.triggerCheckoutComplete&&_.triggerCheckoutComplete(`success`,o.address)):(lf({error:`Transaction failed`,userAddress:o.address,mode:h,fundMethod:g,originTokenAddress:e.originTokenAddress}),Lh(void 0,y),_?.triggerCheckoutError&&_.triggerCheckoutError(`Transaction failed`)),{depositUserTxnReceipt:P,originIntentTransaction:null,destinationIntentTransaction:null}}async function Bg(e,t,n,r,i){let{queryClient:o,account:c,onTransactionStateChange:l,originTokenDecimals:u,originTokenSymbol:d,destinationTokenSymbol:f,swapAmount:p,destinationCalldata:h,sourceTokenPriceUsd:_,destinationTokenPriceUsd:v,mode:y,fundMethod:b=`wallet`,checkoutOnHandlers:x,walletId:S,trailsClient:C,abortSignal:w,executeIntentFn:T,destinationTokenDecimals:E,swapProvider:D,bridgeProvider:O,tradeType:k,walletClient:A}=e,j=o??yo,{onOriginSend:M,selectedFeeOption:N,depositTransactionHash:P}=i,F=N,I=!!e.edgeMeta,ee=e.chain,te=ee.id,ne=W(te),re=e.publicClient??Va(te),ie=I?t.depositTransaction.tokenAddress:e.originTokenAddress,L=yp(e.originChainId,e.destinationChainId),R=bp(e.originTokenAddress,e.destinationTokenAddress),ae=L&&R,z=t.depositTransaction.amount.toString(),B=Xs(z,u),V=nc({amount:Ys(z,u),usdPrice:_}),oe=null,H=null,se=null,ce=!1,U=W(e.destinationChainId)?void 0:Va(e.destinationChainId),le=b===`wallet`&&Kh(ie,r,F,S,te);if(t.intentId&&!le&&!I)try{T?await T({intentId:t.intentId}):await Pm(C,t.intentId,void 0),ce=!0,s.console.log(`[trails-sdk] executeIntent called immediately after commit`,{intentId:t.intentId,fundMethod:b,depositTransactionHash:P})}catch(e){if(g(e))ce=!0,s.console.log(`[trails-sdk] Intent already executing after early executeIntent call`);else throw e}else t.intentId&&le&&s.console.log(`[trails-sdk] Skipping early executeIntent for gasless flow, waiting for deposit signature`,{intentId:t.intentId,fundMethod:b,hasSelectedFeeOption:F!==void 0});let ue=e=>{l(e),x?.triggerCheckoutStatusUpdate&&x.triggerCheckoutStatusUpdate(e)};if(_p(b)&&!P)return ue(n),s.console.log(`[trails-sdk] External funding flow: intent committed, returning early`,{fundMethod:b,intentId:t.intentId}),{depositUserTxnReceipt:null,originIntentTransaction:null,destinationIntentTransaction:null,totalCompletionSeconds:0};if(b===`wallet`&&!I&&!ne){let{hasEnoughBalance:e,balanceError:t}=await xp({account:c,tokenAddress:ie,depositAmount:z,publicClient:re});if(!e)throw t}if(b===`wallet`&&!P&&!I){if(!A)throw Error(`[trails-sdk] Wallet client not provided. Connect a wallet to execute transactions.`);await Hh({walletClient:A,desiredChainId:te})}ue(n);let de=t.intentProtocol,fe=mp(de);if(s.console.log(`[trails-sdk] [intent-protocol] === Intent Protocol Version ===`,{version:fe,intentId:t.intentId,fundMethod:b}),P&&(b!==`wallet`||I)){let e=P;if(P.startsWith(`0x`)&&!I?(e=P,oe=await re.waitForTransactionReceipt({hash:P,onReplaced:t=>{e=t.transaction.hash,s.console.log(`[trails-sdk] External deposit transaction replaced`,{reason:t.reason,replacedHash:t.replacedTransaction.hash,replacementHash:t.transaction.hash})}}),oe?.transactionHash&&(e=oe.transactionHash),s.console.log(`[trails-sdk] External deposit receipt resolved`,{providedHash:P,resolvedHash:e,status:oe.status}),oe&&(n[0]=Gp(oe,te,n[0]?.label),ue(n))):s.console.log(`[trails-sdk] Skipping viem receipt wait`,{depositTransactionHash:P}),(!oe||oe.status===`success`)&&t.intentId&&(M&&(s.console.log(`[trails-sdk] Calling onOriginSend for external deposit`),M()),!ce))try{T?await T({intentId:t.intentId,depositTransactionHash:e}):await Pm(C,t.intentId,e)}catch(e){if(g(e))s.console.log(`[trails-sdk] Intent already executing, continuing...`);else throw e}}else if(b===`wallet`){if(!A)throw Error(`[trails-sdk] Wallet client not provided. Connect a wallet to execute transactions.`);if(oe=await Xh({queryClient:j,originTokenAddress:ie,chain:ee,account:c,depositAmount:z,originIntentAddress:t.originIntentAddress,onOriginSend:M,publicClient:re,walletClient:A,destinationTokenDecimals:E,sourceTokenDecimals:u,sourceTokenPriceUsd:_??null,destinationTokenPriceUsd:v??null,swapAmount:p,onTransactionStateChange:l,transactionStates:n,fundMethod:b,originTokenSymbol:d,destinationTokenSymbol:f,depositAmountUsd:V,feeOptions:r,trailsClient:C,selectedFeeOption:F,walletId:S,abortSignal:w,checkoutOnHandlers:x,intentId:t.intentId,executeIntentFn:T,isSameChainSameToken:ae,destinationCalldata:h,depositTransaction:t.depositTransaction,intentProtocol:fe}),oe){n[0]=Gp(oe,te,n[0]?.label);try{n[0].decodedTokenSweeperEvents=Qm(oe),n[0].decodedGuestModuleEvents=$m(oe),n[0].refunded=n[0].decodedTokenSweeperEvents.findIndex(e=>e.type===`Refund`||e.type===`RefundAndSweep`)!==-1}catch(e){s.console.error(`[trails-sdk] Error decoding deposit events`,e)}ue(n)}}let pe=null,me=0;if(t.intentId){let r=t.quote?.routeProviders?.some(e=>e===`LZ_OFT`),i=r?Oe:600*1e3;s.console.log(`[trails-sdk] Intent polling configuration:`,{isOFTRoute:r,maxWaitTime:i,routeProviders:t.quote?.routeProviders});try{if(me=Date.now(),pe=await dg({intentId:t.intentId,trailsClient:C,abortSignal:w,callbacks:{onDepositTransactionFound:async(e,t)=>{s.console.log(`[trails-sdk] Deposit transaction found:`,e);let r=yg(n,`deposit`);if(r>=0&&n[r]){if(eg(e)){if(s.console.log(`[trails-sdk] Deposit transaction hash is synthetic, marking deposit from status`,{txHash:e,status:t.depositTransaction?.status}),t.depositTransaction?.status===`SUCCEEDED`){let e=n[r],i=e.transactionHash,a=e.explorerUrl,o=tg(i);n[r]={...e,state:`confirmed`,transactionHash:o?i:``,explorerUrl:o?a:``,txnMinedAt:t.depositTransaction?.txnMinedAt||void 0},ue(n)}return}try{let i=await re.getTransactionReceipt({hash:e});n[r]=Gp(i,t.depositTransaction?.chainId??te,n[r]?.label),n[r].decodedTokenSweeperEvents=Qm(i),n[r].decodedGuestModuleEvents=$m(i),ue(n)}catch(e){s.console.error(`[trails-sdk] Error fetching deposit receipt:`,e)}}},onOriginTransactionFound:async(e,t)=>{s.console.log(`[trails-sdk] Origin transaction found:`,e),H={txnHash:e};try{let r=await re.getTransactionReceipt({hash:e}),i=yg(n,`origin`),a=yg(n,`destination`),o=i>=0?i:a;if(o>=0&&n[o]){n[o]=Gp(r,te,n[o]?.label),n[o].decodedTokenSweeperEvents=Qm(r),n[o].decodedGuestModuleEvents=$m(r);let e=yg(n,`deposit`);!t.depositTransaction?.txnHash&&!t.depositTransaction?.status&&e>=0&&n[e]&&(n[e]=Gp(r,te,n[e]?.label),n[e].decodedTokenSweeperEvents=Qm(r),n[e].decodedGuestModuleEvents=$m(r)),ue(n)}}catch(e){s.console.error(`[trails-sdk] Error fetching origin receipt:`,e)}},onDestinationTransactionFound:async t=>{s.console.log(`[trails-sdk] Destination transaction found:`,t),se={txnHash:t};try{if(!U)return;let r=await U.getTransactionReceipt({hash:t}),i=yg(n,`destination`);i>=0&&n[i]&&(n[i]=Gp(r,e.destinationChainId,n[i]?.label),n[i].decodedTokenSweeperEvents=Qm(r),n[i].decodedGuestModuleEvents=$m(r),ue(n))}catch(e){s.console.error(`[trails-sdk] Error fetching destination receipt:`,e)}},onReceiptUpdate:async(e,t,r)=>{s.console.log(`[trails-sdk] Receipt update:`,{status:e.status,done:t,hasOrigin:!!e.originTransaction,hasDestination:!!e.destinationTransaction,hasRefund:!!e.refundTransaction});let i=Eg({currentStates:n,receipt:e,receiptStates:r});if(i.changed&&(n.length=0,n.push(...i.transactionStates),ue(n)),t&&(e.status===`ABORTED`||e.status===`FAILED`)){let t=e.status===`ABORTED`?`aborted`:`failed`,r=e.depositTransaction?.statusReason||e.originTransaction?.statusReason||e.destinationTransaction?.statusReason;for(let e of n)e.state===`pending`&&(e.state=t,r&&(e.statusReason=r));ue(n)}if(e.depositTransaction?.status===`REVERTED`){let t=e.depositTransaction.statusReason||`deposit reverted`;for(let e of n)e.state===`pending`&&(e.state=`failed`,e.statusReason=t);ue(n)}if(e.refundTransaction){let t=kg(n,{chainId:e.refundTransaction.chainId,txnHash:e.refundTransaction.txnHash,status:e.refundTransaction.status});(t.length!==n.length||JSON.stringify(t)!==JSON.stringify(n))&&(n.length=0,n.push(...t),ue(n))}}},maxWaitTime:i}),w?.aborted)throw new m(`Intent receipt polling aborted (widget closed)`);let r=!!(pe?.summary?.finishedAt||pe?.destinationTransaction?.txnMinedAt||pe?.destinationTransaction?.txnHash),a=pe?.destinationTransaction?.status===`SUCCEEDED`,o=!!pe&&a&&r;if(!(pe&&(cg(pe.status)||o))){let n=me>0?Date.now()-me:0,r=n>=i,a=r?`Intent execution timed out after ${Math.round(i/6e4)} minutes.`:`Unable to confirm final intent status from receipt polling.`;throw s.console.warn(`[trails-sdk] Intent polling ended without terminal status`,{intentId:t.intentId,status:pe?.status,maxWaitTime:i,elapsedMs:n,timedOut:r}),lf({error:`${a} Please check transaction history or query GetIntentReceipt.`,userAddress:c.address,mode:y,fundMethod:b,originTokenAddress:e.originTokenAddress}),Lh(void 0,j),x?.triggerCheckoutError&&x.triggerCheckoutError(`Unable to confirm final transaction status`),Error(`${a} Please check transaction history or query GetIntentReceipt with this intent ID.`)}}catch(n){throw n instanceof m?(s.console.log(`[trails-sdk] Intent receipt polling cancelled; skipping completion handling`,{intentId:t.intentId}),n):(s.console.error(`[trails-sdk] Error polling for intent receipt:`,n),lf({error:`Polling failed: ${a(n)}`,userAddress:c.address,mode:y,fundMethod:b,originTokenAddress:e.originTokenAddress}),Lh(void 0,j),x?.triggerCheckoutError&&x.triggerCheckoutError(`Unable to confirm transaction status`),Error(`Unable to confirm transaction status: polling for intent receipt failed`,{cause:n}))}}if(pe&&(pe.status===`ABORTED`||pe.status===`FAILED`)){let r=n[0]?.statusReason,i=r?`Transaction ${pe.status.toLowerCase()}: ${r}`:`Transaction ${pe.status.toLowerCase()}`;throw s.console.error(`[trails-sdk] Intent ${pe.status}:`,t.intentId),lf({error:i,userAddress:c.address,mode:y,fundMethod:b,originTokenAddress:e.originTokenAddress}),Lh(void 0,j),x?.triggerCheckoutError&&x.triggerCheckoutError(i),Error(i)}let he=n.some(e=>e?.decodedGuestModuleEvents?.some(e=>e?.type===`CallFailed`)),ge=n.some(e=>e?.refunded),_e=n.some(e=>e?.state===`failed`),ve=!he&&!ge&&!_e?`success`:`fail`;return cf({userAddress:c.address,originIntentAddress:t.originIntentAddress,originTxHash:oe?.transactionHash,destinationTxHash:se?.txnHash,originChainId:e.originChainId,destinationChainId:e.destinationChainId,swapProvider:D||void 0,bridgeProvider:O||void 0,mode:y,fundMethod:b,originTokenAddress:e.originTokenAddress,originTokenSymbol:d,originTokenAmount:z,originTokenAmountFormatted:B,destinationTokenAddress:e.destinationTokenAddress,destinationTokenSymbol:f,depositTokenAmount:z,depositTokenAmountFormatted:B,depositTokenAmountUsd:V,destinationTokenAmount:t.quote?.toAmount?.toString()||z,destinationTokenAmountFormatted:Xs(t.quote?.toAmount?.toString()||z,E),originTokenDecimals:u,destinationTokenDecimals:E,tradeType:k?.toString(),sourceTokenPriceUsd:_,destinationTokenPriceUsd:v,walletId:S,destinationCalldata:h}),Lh(void 0,j),x?.triggerCheckoutComplete&&x.triggerCheckoutComplete(ve,c.address),{depositUserTxnReceipt:oe,originIntentTransaction:H,destinationIntentTransaction:se,totalCompletionSeconds:await rg(n[0],n[n.length-1])}}async function Vg(e){let{mainSignerAddress:t,originChainId:n,originTokenAddress:r,originTokenBalance:i,originTokenDecimals:o,originTokenSymbol:c,destinationChainId:l,destinationTokenAddress:u,destinationTokenSymbol:d,destinationTokenDecimals:f,swapAmount:p,recipient:h,destinationApproveAddress:g,destinationCalldata:_,account:v,chain:y,trailsClient:b,sourceTokenPriceUsd:x,destinationTokenPriceUsd:S,originNativeTokenPriceUsd:C,slippageTolerance:w,tradeType:T=ln.EXACT_INPUT,swapProvider:E,bridgeProvider:D,swapProviderFallback:O,bridgeProviderFallback:k,fundMethod:A,mode:j,checkoutOnHandlers:M,selectedFeeOption:N,walletId:P,abortSignal:F,commitIntentFn:I,isSmartWallet:ee,isSenderContractOnOrigin:te,trailsApiKey:ne,trailsApiUrl:re,sequenceMetadataUrl:ie,intentProtocolVersion:L}=e;s.console.log(`[trails-sdk] handleIntent called`);let R=A??`wallet`,ae=y,z=r,B=W(n),V=e.publicClient??Va(B?l:ae.id),oe=yp(n,l),H=bp(r,u),se=oe&&H,ce=E,U=D,le=!1,ue=ro(_),de=bt(z),fe=e.edge?.solana,pe=B&&!!e.edgePlugin&&!!fe?.signerPublicKeyBase58?.trim(),me=h?.trim(),he=e.destinationEdgePlugin?.buildEdgeDestinationConfig?.(l,{recipient:me||void 0})??gl(l,me)??null,ge=!pe&&!!he&&!ue,_e=await Cp(t,n,r,p,l,u,T===ln.EXACT_OUTPUT?p:`0`,h,g,_,w,T,ce,U,O,k,void 0,P,ee,te,L,j);se&&ue&&de&&(_e.destinationCallValue=BigInt(p));let ve,ye,be,xe,Se,Ce,we,Te,Ee,De;if(pe){let e=po({inner:fo(_e,T,Zt.ORIGIN),edge:go(fe,{originTokenMint:r,edgeTradeType:T,originTokenAmount:T===ln.EXACT_INPUT?_e.originTokenAmount:void 0})});s.console.log(`[trails-sdk] quoteIntentEdge request:`,e);let t=await Mm(b,e,{originTokenSymbol:c,destinationTokenSymbol:d,feeTokenSymbol:c},F);if(!t.intent)throw Error(`Solana edge quote returned no Trails intent (direct Relay settlement is not supported in this SDK build).`);ve=t.intent,ye=t.gasFeeOptions,be=t.passthrough,xe=t.transactionStates,Se={edgeId:t.edgeId,providerQuote:t.edge.providerQuote},Ce=t.edge.originTokenAmount?.toString()}else if(ge){let e=po({inner:fo(_e,T,Zt.DESTINATION),edge:_o(he,{destinationTokenAddress:u,edgeTradeType:T,originTokenAmount:T===ln.EXACT_OUTPUT?_e.destinationTokenAmount:void 0})});s.console.log(`[trails-sdk] quoteIntentEdge (destination) request:`,e);let t=await Mm(b,e,{originTokenSymbol:c,destinationTokenSymbol:d,feeTokenSymbol:c},F);if(!t.intent)throw Error(`[trails-sdk] Edge destination quote returned no Trails intent.`);ve=t.intent,ye=t.gasFeeOptions,be=t.passthrough,xe=t.transactionStates,De=t.edgeId;let n=hl(t.edge.providerQuote,t.edge.originTokenAmount);n&&(we=n.amount,Te=n.minimumAmount??t.edge.originTokenAmount?.toString(),Ee=n.amountUsd)}else{if(B)throw Error(`[trails-sdk] Solana origin must use QuoteIntentEdge, not QuoteIntent. Configure @0xtrails/svm (svmAdapter) and connect a Solana wallet before quoting.`);_e.fundMethod=hp(R),s.console.log(`[trails-sdk] Creating intent with args:`,_e);let e=await jm(b,_e,{originTokenSymbol:c,destinationTokenSymbol:d,feeTokenSymbol:c},F);ve=e.intent,ye=e.gasFeeOptions,be=e.passthrough,xe=e.transactionStates}if(s.console.log(`[trails-sdk] Quote intent:`,ve),s.console.log(`[trails-sdk] Quote intent gasFeeOptions:`,ye),s.console.log(`[trails-sdk] Quote passthrough:`,be),s.console.log(`[trails-sdk] Quote transactionStates:`,xe),!ve.originPrecondition||!ve.originCalls)throw Error(`Invalid intent`);let Oe=!pe&&se&&!e.isMultiCallEncoding&&R===`wallet`&&be?.eligible===!0&&!!be?.passthroughTransaction&&Ag(N,ye?.feeOptions);s.console.log(`[trails-sdk] Passthrough decision:`,{usePassthrough:Oe,isSameChainSameToken:se,fundMethod:R,passthroughEligible:be?.eligible,hasPassthroughTransaction:!!be?.passthroughTransaction,feeOptionPassthroughEligible:N?.isPassthroughEligible,selectedFeeOption:N});let ke=(Oe&&be?.passthroughTransaction?be.passthroughTransaction:ve.depositTransaction).amount.toString(),Ae=be?.eligible===!0?be?.quote:void 0,je=!!Ae,Me=Ae??ve.quote,Ne=Me.toAmount.toString(),Pe=Me.toAmountMin.toString()||Ne,Fe=ge&&T===ln.EXACT_OUTPUT?p:ge&&we?we:Ne,Ie=ge&&T===ln.EXACT_OUTPUT?p:ge&&Te?Te:Pe,Le=be?.transactionStates?.length?fg({transactionStates:be.transactionStates}):[],Re=xe?.length?fg({transactionStates:xe}):pe?[{id:`deposit`,label:`Deposit on Solana`,chainId:101,transactionHash:``,explorerUrl:``,blockNumber:void 0,state:`pending`,txnMinedAt:void 0},{id:`relay-bridge`,label:`Swap & Bridge`,chainId:Number(ve.depositTransaction.chainId),transactionHash:``,explorerUrl:``,blockNumber:void 0,state:`pending`,txnMinedAt:void 0},{id:`execute`,label:`Execute`,chainId:l,transactionHash:``,explorerUrl:``,blockNumber:void 0,state:`pending`,txnMinedAt:void 0}]:[],ze=Oe?Le:Re,[Ve,He]=await Promise.all([R===`wallet`&&!pe&&!B?xp({account:v,tokenAddress:r,depositAmount:ke,publicClient:V,knownBalance:i&&i!==`0`?i:void 0,decimals:o}):Promise.resolve({hasEnoughBalance:!0}),Up({originDepositAddress:Oe?h:ve.originIntentAddress,destinationDepositAddress:Oe?h:ve.destinationIntentAddress,destinationAddress:h,trailsApiKey:ne||``,trailsApiUrl:re||``,sequenceMetadataUrl:ie||``,destinationCalldata:_,originAmount:pe&&Ce?Ce:ke,destinationAmount:Fe,originAmountMin:pe&&Ce?Ce:ke,destinationAmountMin:Ie,originTokenAddress:r,destinationTokenAddress:u,originTokenPriceUsd:x?.toString()||null,destinationTokenPriceUsd:S?.toString()||null,fees:se?void 0:je&&be?.fees?Dp(be.fees):wp(ve,{tradeType:T,fromAmountUsd:nc({amount:Ys(ke,o),usdPrice:x}),toAmountUsd:nc({amount:Ys(Fe,f),usdPrice:S})}),originChainId:n,destinationChainId:l,slippageTolerance:w,priceImpact:Ae?Ae.priceImpact?.toString()??`0`:Tp(ve),priceImpactUsd:Ae?Ae.priceImpactUsd?.toString()??`0`:Ep(ve),transactionStates:ze,originNativeTokenPriceUsd:C,intent:Oe?void 0:ve,resolvedOriginToken:pe?Be(r)??void 0:void 0,destinationAmountUsdOverride:Ee,edgeId:Se?.edgeId})]);return le=!Ve.hasEnoughBalance,He.noSufficientBalance=le,R===`wallet`&&s.console.log(`[trails-sdk] Balance check with actual deposit amount:`,{depositAmount:ke,originTokenAddress:r,hasEnoughBalance:Ve.hasEnoughBalance,noSufficientBalance:le}),He.passthroughTransactionStates=Le,He.passthroughEligible=be?.eligible===!0,M?.triggerCheckoutQuote&&M.triggerCheckoutQuote(He),s.console.log(`[trails-sdk] handleIntent returning quote and send function`),{quote:He,feeOptions:ye,send:async t=>{let n=!!Se&&!!e.edgePlugin?.executeDeposit;if(!e.walletClient&&!n)throw Error(`[trails-sdk] Wallet client not provided. Connect a wallet to execute transactions.`);let{skipCommit:i}=t;try{let n=t.selectedFeeOption,r=!Se&&R===`wallet`&&be?.eligible===!0&&!!be?.passthroughTransaction&&Ag(n,ye?.feeOptions);s.console.log(`[trails-sdk] Send passthrough decision:`,{sendUsePassthrough:r,passthroughEligible:be?.eligible,hasPassthroughTransaction:!!be?.passthroughTransaction,sendFeeOptionPassthroughEligible:n?.isPassthroughEligible,sendFeeOption:n});let l=r&&be?.passthroughTransaction?be.passthroughTransaction:ve.depositTransaction,u=r?Le:Re,h=async()=>{if(!i)try{s.console.log(`[trails-sdk] intentHandler: About to commit intent`,{hasCommitIntentFn:!!I,intentId:ve.intentId}),await(I||(e=>Nm(b,e,{originTokenSymbol:c,destinationTokenSymbol:d})))(ve),s.console.log(`[trails-sdk] Intent committed successfully`)}catch(e){throw s.console.error(`[trails-sdk] Error committing intent`,e),e}};if(r&&l)return zg(e,l,u,t);if(Se){await h();let n=e.queryClient??yo,r=ve.depositTransaction.amount.toString(),i=Xs(r,o),l=nc({amount:Ys(r,o),usdPrice:x}),g=u,y=t=>{g=t,e.onTransactionStateChange(t),M?.triggerCheckoutStatusUpdate&&M.triggerCheckoutStatusUpdate(t)},S=()=>{let e=!1,t=g.map(t=>t.refunded||t.state===`confirmed`?t:(e=!0,{...t,state:`confirmed`}));e&&y(t)},C=await e.edgePlugin.executeDeposit({providerQuote:Se.providerQuote});t.onOriginSend?.();let w=C[0];if(w&&(g=bg(g,w,101)),y(g),s.console.log(`[trails-sdk] Edge deposit submitted; polling WaitIntentReceipt for progress`,{edgeId:Se.edgeId,intentId:ve.intentId,solanaTxHash:w}),ve.intentId){let t=600*1e3,u=Date.now(),h=null;try{h=await dg({intentId:ve.intentId,trailsClient:b,abortSignal:F,callbacks:{onReceiptUpdate:async(e,t)=>{let n=e.edge?.edgeStatus;if(s.console.log(`[trails-sdk] Edge receipt update:`,{status:e.status,edgeStatus:n,done:t}),n&&g.length>0){let t=g.findIndex(e=>e.id===`relay-bridge`),r=t>=0?t:0,i=g[r];if(i&&i.state===`pending`&&(n===$t.FILLED||n===$t.REFUNDED||n===$t.FAILED)){let t=e.edge?.fillTransactionHash??e.edge?.refundTransactionHash??i.transactionHash;g[r]={...i,state:n===$t.FILLED?`confirmed`:n===$t.REFUNDED?`aborted`:`failed`,transactionHash:t,explorerUrl:t?Xa({txHash:t,chainId:i.chainId}):i.explorerUrl},y(g)}}let r=Eg({currentStates:g,receipt:e});if(r.changed&&(g=r.transactionStates,y(g)),t&&(e.status===`ABORTED`||e.status===`FAILED`)){let t=e.status===`ABORTED`?`aborted`:`failed`;for(let e of g)e.state===`pending`&&(e.state=t);y(g)}if(e.refundTransaction){let t=kg(g,{chainId:e.refundTransaction.chainId,txnHash:e.refundTransaction.txnHash,status:e.refundTransaction.status});t.length!==g.length&&(g=t,y(g))}}},maxWaitTime:t})}catch(t){throw F?.aborted||t instanceof m?t instanceof m?t:new m(`Edge intent receipt polling aborted (widget closed)`):(s.console.error(`[trails-sdk] Error polling edge intent receipt:`,t),lf({error:`Edge polling failed: ${a(t)}`,userAddress:v.address,mode:j,fundMethod:R,originTokenAddress:e.originTokenAddress}),Lh(void 0,n),M?.triggerCheckoutError&&M.triggerCheckoutError(`Unable to confirm edge transaction status`),Error(`Unable to confirm edge transaction status: polling failed`,{cause:t}))}if(F?.aborted)throw new m(`Edge intent receipt polling aborted (widget closed)`);let x=!!(h?.summary?.finishedAt||h?.destinationTransaction?.txnMinedAt||h?.destinationTransaction?.txnHash),C=h?.destinationTransaction?.status===`SUCCEEDED`,w=!!h&&C&&x;if(!(h&&(cg(h.status)||w))){let r=(u>0?Date.now()-u:0)>=t?`Edge intent timed out after 10 minutes.`:`Unable to confirm final edge intent status.`;throw s.console.warn(`[trails-sdk] Edge polling ended without terminal status`,{intentId:ve.intentId,status:h?.status}),lf({error:r,userAddress:v.address,mode:j,fundMethod:R,originTokenAddress:e.originTokenAddress}),Lh(void 0,n),M?.triggerCheckoutError&&M.triggerCheckoutError(r),Error(r)}if(h.status===`ABORTED`||h.status===`FAILED`){let t=`Transaction ${h.status.toLowerCase()}`;throw lf({error:t,userAddress:v.address,mode:j,fundMethod:R,originTokenAddress:e.originTokenAddress}),Lh(void 0,n),M?.triggerCheckoutError&&M.triggerCheckoutError(t),Error(t)}h.status===rn.SUCCEEDED&&S();let T=h.status===`REFUNDED`||g.some(e=>e?.refunded||e?.state===`aborted`||e?.state===`failed`)?`fail`:`success`;cf({userAddress:v.address,originChainId:e.originChainId,destinationChainId:e.destinationChainId,mode:j,fundMethod:R,originTokenAddress:e.originTokenAddress,originTokenSymbol:c,originTokenAmount:p,originTokenAmountFormatted:i,destinationTokenAddress:e.destinationTokenAddress,destinationTokenSymbol:d,depositTokenAmount:r,depositTokenAmountFormatted:i,depositTokenAmountUsd:l,destinationTokenAmount:ve.quote?.toAmount?.toString()||r,destinationTokenAmountFormatted:Xs(ve.quote?.toAmount?.toString()||r,f),originTokenDecimals:o,destinationTokenDecimals:f,walletId:P,destinationCalldata:_}),Lh(void 0,n),M?.triggerCheckoutComplete&&M.triggerCheckoutComplete(T,v.address)}return{depositUserTxnReceipt:null,originIntentTransaction:null,destinationIntentTransaction:null}}if(await h(),!De)return Bg(e,ve,u,ye,t);let g={id:`solana-fill`,label:`Fill`,chainId:101,transactionHash:``,explorerUrl:``,blockNumber:void 0,state:`pending`,txnMinedAt:void 0},y=!Ig(u),S=e=>y?[...e,g]:e,C=await Bg({...e,onTransactionStateChange:t=>e.onTransactionStateChange(S(t))},ve,u,ye,t),w=[...u],T=await dg({intentId:ve.intentId,trailsClient:b,abortSignal:F,maxWaitTime:600*1e3,pollInterval:2e3,waitForEdgeCompletion:!0}).catch(t=>{throw F?.aborted||t instanceof m?t instanceof m?t:new m(`Destination edge receipt polling aborted (widget closed)`):(e.onTransactionStateChange(y?[...w,{...g,state:`aborted`}]:w),t)});if(F?.aborted)throw new m(`Destination edge receipt polling aborted (widget closed)`);let E=T?.edge,D=E?.initTransactionHash?.trim(),O=E?.fillTransactionHash?.trim();if(E?.edgeStatus!==$t.FILLED||!O)throw e.onTransactionStateChange(y?[...w,{...g,state:`aborted`}]:w),Error(`Unable to confirm destination edge fill status`);let k=Lg(w),A=D&&k>=0?w.map((t,n)=>n===k&&(t.state===`pending`||t.state===`confirmed`&&!tg(t.transactionHash))?{...t,transactionHash:D,explorerUrl:Xa({txHash:D,chainId:e.originChainId}),state:`confirmed`}:t):w;return e.onTransactionStateChange(y?[...A,O?{...g,transactionHash:O,explorerUrl:Xa({txHash:O,chainId:101}),state:`confirmed`}:{...g,state:`aborted`}]:Rg(A,O)),C}catch(e){if(e instanceof m)throw s.console.log(`[trails-sdk] handleIntent send cancelled (superseded); skipping error handling`),e;let t=a(e);throw s.console.error(`[trails-sdk] Error in handleIntent send:`,e),lf({error:t,userAddress:v.address,mode:j,fundMethod:R,originTokenAddress:r}),M?.triggerCheckoutError&&M.triggerCheckoutError(t),e}}}}var Hg=class extends Error{constructor(e,t,n){super(t,n===void 0?void 0:{cause:n}),me(this,`code`,void 0),this.name=`DestinationEncodingError`,this.code=e}};function Ug(e){if(e instanceof Hg)return e;if(e instanceof Lt){if(e.code===`MULTIPLE_AMOUNT_SLOTS`)return new Hg(`MULTIPLE_AMOUNT_SLOTS`,e.message,e);if(e.code===`INVALID_AMOUNT_OFFSET`)return new Hg(`UNSAFE_PLACEHOLDER_MATCH`,e.message,e)}return e}function Wg(e){let t=e.destinationAddress,n=e.destinationCalldata,r=e.destinationApprovalAddress;if(!e.hasCustomCalldata||!e.isExactInput)return{destinationAddress:t,destinationCalldata:n,destinationApprovalAddress:r,strategy:`none`};if(e.intentProtocol!==nn.v1_5)throw Error(`Unsupported intent protocol "${e.intentProtocol}" for destination encoding. Supported: ${nn.v1_5}`);if(!e.trailsUtilsAddress)throw Error(`trailsUtilsAddress is required for v1.5 destination encoding`);if(!Da.validate(n))return{destinationAddress:t,destinationCalldata:n,destinationApprovalAddress:r,strategy:`none`};if(Da.assert(n),!Ca.validate(t))throw new Hg(`INVALID_DESTINATION_CALLDATA`,`Invalid destination address "${t}" for v1.5 hydrate encoding`);Ca.assert(t);let i;try{i=bt(e.destinationTokenAddress)?0:Rt(n,Ht)}catch(e){throw Ug(e)}if(i<0)return{destinationAddress:t,destinationCalldata:n,destinationApprovalAddress:r,strategy:`none`};let a=wa.from([]);if(bt(e.destinationTokenAddress))a=It.from([{data:n}]).hydrateCall({callIndex:0,value:Ut.self()}).build();else{Ca.assert(e.destinationTokenAddress);let t=wa.fromHex(n);t.fill(0,i,i+32),n=wa.toHex(t),a=It.from([{data:n}]).hydrateCall({callIndex:0,data:[{kind:`erc20Balance`,selector:Bt.offset(i,32),token:e.destinationTokenAddress,address:Ut.self()}]}).build()}return n=Vt({target:t,calldata:n,hydratePayload:a}),r??(r=t),t=e.trailsUtilsAddress,{destinationAddress:t,destinationCalldata:n,destinationApprovalAddress:r,strategy:`v1_5_trails_utils_hydrate`}}function Gg(e,t,n){return Le(e,t,n)??void 0}function Kg(e,t,n){return Ie(e,t,n)??void 0}function qg(e,t){if(!(!e||t==null))return e.find(e=>e.chainId===t)}function Jg(){let e=gs();return Dr({mutationFn:async t=>{s.console.log(`[trails-sdk] useCommitIntent: mutationFn called`,{intentId:t.intentId,originIntentAddress:t.originIntentAddress,stackTrace:Error().stack}),s.console.log(`[trails-sdk] useCommitIntent: Starting commit`,{intentId:t.intentId,originIntentAddress:t.originIntentAddress});let n=t.quoteRequest.originChainId.toString(),r=t.quoteRequest.destinationChainId.toString();try{mf({intentAddress:t.originIntentAddress,userAddress:t.ownerAddress,originChainId:n?Number(n):void 0,destinationChainId:r?Number(r):void 0});let i=await e.commitIntent({intent:t});return s.console.log(`[trails-sdk] useCommitIntent: Commit successful`,{intentId:t.intentId,response:i}),Dm(t),hf({intentAddress:t.originIntentAddress,userAddress:t.ownerAddress,originChainId:n?Number(n):void 0,destinationChainId:r?Number(r):void 0}),i}catch(e){throw gf({error:a(e),userAddress:t.ownerAddress,intentAddress:t.originIntentAddress,originChainId:n?Number(n):void 0,destinationChainId:r?Number(r):void 0}),e}}})}function Yg(){let e=gs();return Dr({mutationFn:async({intentId:t,depositTransactionHash:n,depositSignature:r})=>{s.console.log(`[trails-sdk] useExecuteIntent: Starting execution`,{intentId:t,providedDepositTransactionHash:n,hasDepositSignature:!!r});let i;try{i=await e.executeIntent({intentId:t,depositTransactionHash:n,depositSignature:r})}catch(e){s.console.error(`[trails-sdk] useExecuteIntent: Error executing intent`,{intentId:t,error:e,errorJSON:JSON.stringify(e,null,2)});let n=_(e);if(n)return s.console.error(`[trails-sdk] useExecuteIntent: Intent already advanced, treating as current state`,{intentId:t,intentStatus:n}),{intentId:t,intentStatus:n};throw s.console.error(`[trails-sdk] useExecuteIntent did not return an intent status`,{intentId:t,error:e,errorJSON:JSON.stringify(e,null,2)}),e}return s.console.log(`[trails-sdk] useExecuteIntent: Execution successful`,{intentId:t,response:i}),i}})}function Xg(e){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}function Zg(e){let{actions:t,chainId:n,destinationChain:r,userWalletAddress:i,trailsClient:a,publicClient:o}=e,[s,c]=X(null),[l,u]=X(null),[d,f]=X(!1),p=J(()=>t,[Xg(t)]);return q(()=>{if(!i||!n||!a){c(null),f(!1),u(null);return}let e=p;if(e.length===0){c(null),f(!1),u(null);return}let t=new AbortController;return f(!0),u(null),c(null),(async()=>{try{let n=await nt({actions:e,destinationChain:r,userWalletAddress:i,trailsClient:a,publicClient:o,abortSignal:t.signal});if(t.signal.aborted)return;c(n),u(null)}catch(e){if(t.signal.aborted)return;u(e instanceof Ye?e:new Ye(`CALL_RESOLUTION_FAILED`,e instanceof Error?e.message:`Failed to resolve actions`)),c(null)}finally{t.signal.aborted||f(!1)}})(),()=>{t.abort()}},[i,p,r,n,a,o]),{calls:s,isLoading:d,error:l}}async function Qg(e){return(await e.getEdges()).edges}const $g={all:[`edges`],edges:e=>{let t=!!e;return wr({queryKey:[...$g.all],queryFn:t?()=>Qg(e):Tr,staleTime:5*ge,gcTime:5*ge,...cs})}};function e_(){let e=gs();return Or($g.edges(e))}function t_(e){let{data:t}=e_();return t?.some(t=>t.rail===e)??!1}function n_(){return t_(Qt.SOLANA)}function r_(t){if(t instanceof Ye)return t;let n=a(t);return o(t)===`quote.timeout`?new Ye(`TIMEOUT`,n):F(t)?new Ye(`USER_REJECTED`,n):u(t)?new Ye(`INSUFFICIENT_BALANCE`,n):E(t)?new Ye(`INSUFFICIENT_LIQUIDITY`,n):e(t)?new Ye(`HIGH_PRICE_IMPACT`,n):oe(t)?new Ye(`RATE_LIMITED`,n):ie(t)?new Ye(`INVALID_TOKEN`,n):S(t)?new Ye(`INVALID_INPUT`,n):ne(t)?new Ye(`NO_QUOTE`,n):B(t)?new Ye(`ONRAMP_AMOUNT_TOO_LOW`,n):se(t)?new Ye(`NETWORK_ERROR`,n):/no route available|no edge landing route found|edge candidate miss/i.test(n)?new Ye(`NO_ROUTE`,n):v(t)?new Ye(`API_ERROR`,n):new Ye(`UNKNOWN`,n)}const i_={all:[`trails`],quotes:()=>[...i_.all,`quote`],quote:e=>[...i_.quotes(),e]};function a_({walletClient:e,walletAddress:t,from:n,to:r,actions:i,slippageTolerance:a,onStatusUpdate:o,checkoutOnHandlers:c,swapProvider:l,bridgeProvider:u,swapProviderFallback:d,bridgeProviderFallback:f,selectedFeeOption:p,nodeGatewayEnv:m,abortSignal:h,apiKey:g,isSmartWallet:_,fundMethod:v,onramp:y,mode:b,intentProtocolVersion:x,disabled:S}){let C=ti(),{address:w}=Yr(),E=C?.session.session.activeConnection?.walletId,D=oi(),O=ui(),k=ri(e),A=ri(C?.evm?.walletClient),M=J(()=>{let e=[t,k?.account?.address,A?.account?.address,w];for(let t of e){let e=t?.trim();if(e&&bn(e))return e.toLowerCase()}for(let e of C?.session.session.connections??[]){if(e.namespace!==`eip155`)continue;let t=((e.activeAccount?.namespace===`eip155`?e.activeAccount.address:void 0)??e.accounts.find(e=>e.namespace===`eip155`)?.address)?.trim();if(t&&bn(t))return t.toLowerCase()}return null},[t,k?.account?.address,A?.account?.address,w,C?.session.session.connections]),N=M?yn(M):null;if(n?.amount!==void 0&&n?.amountRaw!==void 0)throw Error('[trails-sdk] [useQuote] Cannot specify both `from.amount` and `from.amountRaw`. Use `amount` for human-readable decimals (e.g. "1.5") or `amountRaw` for raw wei (e.g. 1500000000000000000n).');if(r?.amount!==void 0&&r?.amountRaw!==void 0)throw Error('[trails-sdk] [useQuote] Cannot specify both `to.amount` and `to.amountRaw`. Use `amount` for human-readable decimals (e.g. "1.5") or `amountRaw` for raw wei (e.g. 1500000000000000000n).');let P=n?.amount!==void 0||n?.amountRaw!==void 0,F=r?.amount!==void 0||r?.amountRaw!==void 0;if(P&&F)throw Error(`[trails-sdk] [useQuote] Cannot specify amount on both from and to. Place amount/amountRaw on from for EXACT_INPUT or to for EXACT_OUTPUT.`);let I=!!i?.length,te=!!r.calls?.flat().length,ne=!!(r.calldata&&r.calldata!==`0x`);if(Number(I)+Number(te)+Number(ne)>1)throw Error("[trails-sdk] [useQuote] Only one of `actions`, `to.calls`, or `to.calldata` may be specified. Prefer `actions` for composable DeFi actions or `to.calls` for raw calls. `to.calldata` is deprecated.");if((I||te)&&r?.recipient)throw Error("[trails-sdk] [useQuote] `to.recipient` is not supported when using `actions` or `to.calls`. Use per-action recipients instead; residual balances always sweep to the owner wallet.");let re=r?.recipient??N,ie=n?.amountRaw===void 0?n?.amount:Os(n.amountRaw,`[useQuote] from.amountRaw`),L=r?.amountRaw===void 0?r?.amount:Os(r.amountRaw,`[useQuote] to.amountRaw`),R=ie??L,ae=ie===void 0?ln.EXACT_OUTPUT:ln.EXACT_INPUT,z=n?.amountRaw!==void 0||r?.amountRaw!==void 0,B=n?.chain?dt(n.chain):null,V=r?.chain?dt(r.chain):null,oe=n?.token??null,H=r?.token??null,se=(oe?!bn(oe):!1)||(H?!bn(H):!1),ce=r?.approve??null,U=r?.calldata??null,le=Y(!1);q(()=>{ne&&!le.current&&(le.current=!0,s.console.warn("[trails-sdk] [useQuote] `to.calldata` is deprecated and will be removed in a future major release. Migrate to `to.calls` (raw calls) or the top-level `actions` option (composable DeFi). See https://docs.trails.build/sdk/hooks#usequote-hook for the migration guide."))},[ne]),q(()=>(m&&(globalThis.__testNodeGatewayEnv=m),()=>{m&&delete globalThis.__testNodeGatewayEnv}),[m]);let ue=Y(new AbortController),de=J(()=>JSON.stringify({fromTokenInput:oe,fromChainId:B,toTokenInput:H,toChainId:V,tradeType:ae,fundMethod:v,isAmountRaw:z}),[oe,B,H,V,ae,v,z]),[fe,pe]=X(()=>({amount:R,contextKey:de}));q(()=>{let e={amount:R,contextKey:de},t=fe.contextKey===de;if(v===`onramp-meld`&&t){pe(t=>t.amount===e.amount&&t.contextKey===e.contextKey?t:e);return}let n=setTimeout(()=>{pe(t=>t.amount===e.amount&&t.contextKey===e.contextKey?t:e)},300);return()=>clearTimeout(n)},[R,v,de,fe.contextKey]);let me=fe.amount,he=fe.contextKey===de,{trailsApiKey:ge,trailsApiUrl:_e,sequenceIndexerUrl:ve,sequenceMetadataUrl:ye}=Vx(),be=ge,xe=gs({apiKey:ge,hostname:_e}),Se=$h(),Ce=Nt(B),we=J(()=>Ce&&B?Ce.buildEdgeConfig(B):null,[Ce,B]),Te=we!==null,Ee=n_(),De=Ft(V),ke=Wx(B??void 0),je=Wx(V??void 0),Me=B!=null&&D===B,Ne=V!=null&&D===V,Ie=Me?O??ke:ke,Le=Ne?O??je:je,Re=Zg({actions:i??[],chainId:V??void 0,destinationChain:r.chain,userWalletAddress:N,trailsClient:xe,publicClient:Le}),ze=J(()=>Re.calls??r.calls?.flat()??[],[Re.calls,r.calls]),Ve=!!(r.calldata&&r.calldata!==`0x`),He=!!(!Ve&&ze.length),Ue=V!=null&&W(V)&&(Ve||He),We=He?Ae.trailsUtilsAddress:re,{supportedTokens:Ge}=Rc({disabled:!se&&(!!oe||!!H)}),Ke=J(()=>{if(!oe||!B)return null;let e=Fe(oe,B,Ge);return e||s.console.warn(`[trails-sdk] [useQuote] Could not resolve source token symbol "${oe}" on chain ${B}. Pass a contract address instead.`),e},[oe,B,Ge]),qe=J(()=>{if(!H||!V)return null;let e=W(V)?[...Ge,...Ze()]:Ge,t=Fe(H,V,e);return t||s.console.warn(`[trails-sdk] [useQuote] Could not resolve destination token symbol "${H}" on chain ${V}. Pass a contract address instead.`),t},[H,V,Ge]),Je=Ke?.address??null,Ye=qe?.address??null,Xe=J(()=>{if(!He)return{encodedCalldata:null,intentProtocolVersion:null,error:null};if(!Ye)return{encodedCalldata:null,intentProtocolVersion:null,error:`toTokenAddress is required`};try{let e=N;if(!e||!bn(e))throw Error("Provide a valid `walletAddress` or a connected `walletClient`.");let t=ht({calls:ze,tokenAddress:Ye,sweepTarget:e,intentProtocolVersion:x});return{encodedCalldata:t.destinationCalldata,intentProtocolVersion:t.intentProtocolVersion,error:null}}catch(e){return{encodedCalldata:null,intentProtocolVersion:null,error:e instanceof Error?e.message:`Unknown encoding error`}}},[He,ze,Ye,x,N]),Qe=He?Xe.encodedCalldata:U,$e=He?Xe.intentProtocolVersion:x,et=Jg(),tt=Yg(),nt=!l&&(B===zn.id||V===zn.id)?`lifi`:l??null,it=!u&&(B===zn.id||V===zn.id)?`lifi`:u??null,at=kr(),ot=M,st=We?.toLowerCase(),ct=ot&&st&&ot===st,lt=B&&V&&B===V,ut=(e,t)=>!e||!t?!1:at.getQueryData([`isContract`,e,t])===!0,{data:G}=Or({queryKey:[`isContract`,ot,B],queryFn:async()=>!ot||!B?null:eo(ot,B,Ie??void 0),enabled:!!ot&&!!B&&!ut(ot,B),staleTime:e=>e.state.data===!0?1/0:0,gcTime:Oe}),{data:ft}=Or({queryKey:[`isContract`,ot,V],queryFn:async()=>!ot||!V?null:eo(ot,V,Le??void 0),enabled:!!ot&&!!V&&!lt&&!ut(ot,V),staleTime:e=>e.state.data===!0?1/0:0,gcTime:Oe}),{data:pt}=Or({queryKey:[`isContract`,st,V],queryFn:async()=>!st||!V?null:eo(st,V,Le??void 0),enabled:!!st&&!!V&&!ct&&!ut(st,V),staleTime:e=>e.state.data===!0?1/0:0,gcTime:Oe}),mt=G??null,gt=lt?G:ft??null,_t=ct?lt?G:ft:pt??null,vt=!!(M||Te),yt=he&&ks(R)&&ks(me),bt=!I||!Re.isLoading&&Re.calls!==null&&Re.error===null,xt=!!(!S&&vt&&xe&&Je&&Ye&&yt&&We&&B&&V&&Se&&bt&&!Ue&&(!Te||Ee&&M)),St=Y(null);q(()=>{if(xt){St.current=null;return}let e=[];M||e.push(Te?`walletClient (EVM wallet required for Solana edge — used as refund owner)`:`walletClient or walletAddress`),xe||e.push(`trailsClient (check TrailsProvider)`),Je||(oe&&!bn(oe)?e.push(`from.token (symbol "${oe}" not found on chain ${B??`unknown`})`):e.push(`from.token`)),Ye||(H&&!bn(H)?e.push(`to.token (symbol "${H}" not found on chain ${V??`unknown`})`):e.push(`to.token`)),B||e.push(`from.chain`),V||e.push(`to.chain`),R==null?e.push(`amount or amountRaw (set on from or to)`):he?yt||e.push(z?`amountRaw (malformed or zero: ${JSON.stringify(R)} — expected a positive bigint or integer-only string in the token's smallest unit, e.g. 1000000n)`:`amount (malformed or zero: ${JSON.stringify(R)} — expected a positive human-readable decimal string like "0.5")`):e.push(`amount (waiting for updated quote params)`),We||e.push(`to.recipient (or connect a wallet / provide walletAddress)`),Se||e.push(`indexerGatewayClient (check TrailsProvider)`),I&&!bt&&(Re.error?e.push(`actions (resolution failed: ${Re.error.message})`):e.push(`actions (resolving)`));let t=e.join(`, `);t!==St.current&&(St.current=t,console.warn(`[trails-sdk] [useQuote] Quote disabled. Missing: ${t}`))},[xt,M,Te,xe,Je,oe,B,Ye,H,V,R,z,he,yt,We,Se,I,bt,Re.error]);let{data:Ct,isFetching:wt,error:Tt,refetch:Et}=Or({queryKey:i_.quote({senderAddress:ot??null,fromToken:Je,fromChainId:B,toToken:Ye,toChainId:V,amount:he?me?.toString()??null:null,isAmountRaw:z,recipient:We,calldata:Qe,tradeType:ae,slippage:a,swapProvider:l,bridgeProvider:u,swapProviderFallback:d,bridgeProviderFallback:f,intentProtocolVersion:$e,apiKey:g,isSmartWallet:_,fundMethod:v}),queryFn:async()=>{try{if(s.console.log(`[trails-sdk] [useQuote] prepareSend queryFn entered`),ue.current.signal.aborted&&(s.console.log(`[trails-sdk] Resetting aborted controller for new query`),ue.current=new AbortController),!M&&Te)return s.console.log(`[trails-sdk] [useQuote] Solana edge quote skipped: need an EVM 0x recipient or connected EVM wallet for inner intent owner`),null;if(!M||!xe||!Je||!Ye||!yt||!We||!B||!V||!Se)return s.console.log(`[trails-sdk] [useQuote] prepareSend queryFn guard failed, returning null`),null;if(He){if(Xe.error)throw Error(Xe.error);if(!Qe)throw Error(`Failed to encode to.calls into toCalldata`)}let e=h?(()=>{let e=new AbortController;return h.aborted?(e.abort(),ue.current?.abort(),e.signal):(h.addEventListener(`abort`,()=>{e.abort(),ue.current?.abort()},{once:!0}),ue.current.signal.addEventListener(`abort`,()=>e.abort(),{once:!0}),e.signal)})():ue.current.signal,i=setTimeout(()=>{s.console.warn(`[trails-sdk] [useQuote] Quote request timed out after 60 seconds`),ue.current.abort()},6e4);try{let l=$(B)?.nativeCurrency?.symbol??``,u=B!=null&&W(B),m=0,h=`0`;if(u){let e=we&&Mt(we)?we:null,t=e?.signerPublicKeyBase58;if(t&&xe){let n=Ke?.token??Gg(Ge,Je,B)??Be(Je),r=Be(Ot),i=[];n&&i.push(n),r&&r.contractAddress!==n?.contractAddress&&i.push(r);let a=i.length?await jh({tokens:i,accountAddress:t,trailsClient:xe,solanaRpcUrls:e?.rpcUrls}):[];h=a.find(e=>e.chainId===B&&rt(e.contractAddress,Je))?.balance??`0`,m=a.find(e=>e.isNativeToken)?.priceUsd??0,!m&&l&&(m=(await ap(xe,{tokenSymbol:l,tokenAddress:`11111111111111111111111111111111`,chainId:B}).catch(e=>(s.console.error(`[trails-sdk] [useQuote] Error getting origin native token price:`,e),null)))?.priceUsd??0)}}else{let e=(await at.ensureQueryData(Ih.withPrices(M,Se,xe)).catch(e=>{if(os(e))return s.console.warn(`[trails-sdk] [useQuote] Network error fetching balances, proceeding with quote using zero balance:`,{error:e,account:M}),{balances:[]};throw e})).balances;m=e.find(e=>e.chainId===B&&(Pe(e.contractAddress,Cn)||e.isNativeToken))?.priceUsd??0,!m&&l&&(m=(await ap(xe,{tokenSymbol:l,tokenAddress:Cn,chainId:B}).catch(e=>(s.console.error(`[trails-sdk] [useQuote] Error getting origin native token price:`,e),null)))?.priceUsd??0),h=e.find(e=>e.chainId===B&&(e.contractAddress?.toLowerCase()===Je.toLowerCase()||!e.contractAddress&&Je===Cn))?.balance??`0`}m&&s.console.log(`[trails-sdk] [useQuote] Origin native token price:`,{chainId:B,symbol:l,priceUsd:m});let g=async(e,t)=>{try{let n=t===B?Ie:t===V?Le:null;if(!n)return s.console.warn(`[trails-sdk] No RPC client available for chain ${t}`),null;if(Pe(e,Cn))return $(t)?.nativeCurrency.decimals??18;let r=await n.readContract({address:e,abi:_n,functionName:`decimals`});return s.console.log(`[trails-sdk] Fetched decimals on-chain for token ${e} on chain ${t}: ${r}`),r}catch(n){return s.console.error(`[trails-sdk] Error fetching decimals on-chain for token ${e} on chain ${t}:`,n),null}},x=Ke?.token??Gg(Ge,Je,B),S=qe?.token??Gg(Ge,Ye,V),C=n?.decimals??x?.decimals??(B&&W(B)?6:void 0);if(!C&&Je&&B){s.console.warn(`[trails-sdk] [useQuote] Source token decimals not found in token list, fetching on-chain:`,{originToken:x,fromTokenAddress:Je,fromChainId:B});let e=await g(Je,B);e!==null&&(C=e)}if(!C)throw s.console.error(`[trails-sdk] [useQuote] Source token decimals not found:`,{originToken:x,fromTokenAddress:Je,fromChainId:B}),Error("Source token decimals not found. Pass `from.decimals` explicitly, register the token via TrailsProvider's token list, or ensure the chain RPC is reachable.");let w=r?.decimals??S?.decimals;if(!w&&Ye&&V){s.console.warn(`[trails-sdk] Destination token decimals not found in token list, fetching on-chain:`,{destinationToken:S,toTokenAddress:Ye,toChainId:V});let e=await g(Ye,V);e!==null&&(w=e)}if(!w)throw s.console.error(`[trails-sdk] Destination token decimals not found:`,{destinationToken:S,toTokenAddress:Ye,toChainId:V}),Error("Destination token decimals not found. Pass `to.decimals` explicitly, register the token via TrailsProvider's token list, or ensure the chain RPC is reachable.");let T=S?.symbol??``,D=x?.symbol??``,O;if(z)try{O=BigInt(me)}catch(e){throw Error(`Invalid raw amount "${String(me)}". Pass a positive bigint or integer-only string in the token's smallest unit (e.g. 1000000n or "1000000"). Underlying error: ${e instanceof Error?e.message:String(e)}`,{cause:e})}else{let e=ae===ln.EXACT_INPUT?C:w;try{O=Sn(me,e)}catch(e){throw Error(`Invalid amount "${String(me)}". Pass a human-readable decimal string (e.g. "0.5"). Underlying error: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}let A=v===`direct-transfer`||v===`onramp-mesh`||v===`onramp-meld`?Sn(`100`,C).toString():h,j={queryClient:at,account:t?{address:M,type:`json-rpc`}:k?.account??{address:M,type:`json-rpc`},originTokenAddress:Je,originChainId:B,originTokenBalance:A,destinationChainId:V,recipient:We,destinationApproveAddress:ce??void 0,destinationTokenAddress:Ye,swapAmount:O.toString(),tradeType:ae??ln.EXACT_OUTPUT,originTokenSymbol:D,destinationTokenSymbol:T,destinationCalldata:Qe??void 0,client:k??void 0,trailsClient:xe,sourceTokenDecimals:C,destinationTokenDecimals:w,onTransactionStateChange:o??(()=>{}),slippageTolerance:a?.toString(),swapProvider:nt,bridgeProvider:it,swapProviderFallback:d,bridgeProviderFallback:f,selectedFeeOption:p??null,abortSignal:e,originNativeTokenPriceUsd:m,commitIntentFn:e=>et.mutateAsync(e),executeIntentFn:tt.mutateAsync,checkoutOnHandlers:c,sequenceIndexerUrl:ve,sequenceProjectAccessKey:be,originPublicClient:Ie??void 0,destinationPublicClient:Le??void 0,isSmartWallet:_??void 0,isSenderContractOnOrigin:mt??void 0,trailsApiKey:ge,trailsApiUrl:_e,intentProtocolVersion:$e??void 0,sequenceMetadataUrl:ye,fundMethod:v??`wallet`,onramp:y??void 0,mode:b??void 0,walletId:E??void 0,isMultiCallEncoding:He,...we?{edge:mo(we)}:{},...Ce?{edgePlugin:Ce}:{},...De?{destinationEdgePlugin:De}:{}};s.console.log(`[trails-sdk] options`,j);let{quote:N,send:P,feeOptions:F}=await s_(j),I={originAmount:N.originAmount,originAmountMin:N.originAmountMin,destinationAmount:N.destinationAmount,destinationAmountMin:N.destinationAmountMin,originAmountUsdDisplay:N.originAmountUsdDisplay??``,destinationAmountUsdDisplay:N.destinationAmountUsdDisplay??``,originAmountDisplay:N.originAmountDisplay??``,destinationAmountDisplay:N.destinationAmountDisplay??``,originAmountMinDisplay:N.originAmountMinDisplay??``,originAmountMinUsdFormatted:N.originAmountMinUsdFormatted??``,originAmountMinUsdDisplay:N.originAmountMinUsdDisplay??``,destinationAmountMinDisplay:N.destinationAmountMinDisplay??``,destinationAmountMinUsdFormatted:N.destinationAmountMinUsdFormatted??``,destinationAmountMinUsdDisplay:N.destinationAmountMinUsdDisplay??``,originAmountUsdFormatted:N.originAmountUsdFormatted??``,destinationAmountUsdFormatted:N.destinationAmountUsdFormatted??``,originAmountFormattedLocale:N.originAmountFormattedLocale,originAmountUsdLocaleDisplay:N.originAmountUsdLocaleDisplay,destinationAmountFormattedLocale:N.destinationAmountFormattedLocale,destinationAmountUsdLocaleDisplay:N.destinationAmountUsdLocaleDisplay,originAmountUsd:N.originAmountUsd,originAmountFormatted:N.originAmountFormatted??``,destinationAmountFormatted:N.destinationAmountFormatted??``,intentProtocol:N.intentProtocol,originToken:N.originToken,destinationToken:N.destinationToken,originChain:N.originChain,destinationChain:N.destinationChain,fees:N.fees,priceImpact:N.priceImpact,priceImpactUsd:N.priceImpactUsd??null,priceImpactUsdDisplay:N.priceImpactUsdDisplay??``,priceImpactUsdLocaleDisplay:N.priceImpactUsdLocaleDisplay,completionEstimateSeconds:N.completionEstimateSeconds,completionEstimateDisplay:N.completionEstimateDisplay??``,slippageTolerance:N.slippageTolerance,transactionStates:N.transactionStates??[],originTokenRate:N.originTokenRate??``,destinationTokenRate:N.destinationTokenRate??``,originTokenPriceUsd:N.originTokenPriceUsd??0,destinationTokenPriceUsd:N.destinationTokenPriceUsd??0,routeProviders:N.routeProviders??[],gasCostUsd:N.gasCostUsd??null,gasCostUsdDisplay:N.gasCostUsdDisplay??``,gasCost:N.gasCost??``,gasCostFormatted:N.gasCostFormatted??``,totalFeesUsd:N.totalFeesUsd??null,totalFeesUsdDisplay:N.totalFeesUsdDisplay??``,totalGasUsd:N.totalGasUsd??null,totalGasUsdDisplay:N.totalGasUsdDisplay??``,intentId:N.intentId??null,edgeId:N.edgeId??null,originDepositAddress:N.originDepositAddress??``,destinationDepositAddress:N.destinationDepositAddress??``,destinationAddress:N.destinationAddress??``,destinationApproveAddress:N.destinationApproveAddress??``,destinationCalldata:N.destinationCalldata??``,trailsFeeBreakdown:N.trailsFeeBreakdown??null,originGasUsd:N.originGasUsd??null,originGasUsdDisplay:N.originGasUsdDisplay??``,destinationGasUsd:N.destinationGasUsd??null,destinationGasUsdDisplay:N.destinationGasUsdDisplay??``,providerFeeUsd:N.providerFeeUsd??null,providerFeeUsdDisplay:N.providerFeeUsdDisplay??``,trailsFeeUsd:N.trailsFeeUsd??null,trailsFeeUsdDisplay:N.trailsFeeUsdDisplay??``,totalProviderFeesUsd:N.totalProviderFeesUsd??null,totalProviderFeesUsdDisplay:N.totalProviderFeesUsdDisplay??``,totalGasUsdLocaleDisplay:N.totalGasUsdLocaleDisplay,originGasUsdLocaleDisplay:N.originGasUsdLocaleDisplay,destinationGasUsdLocaleDisplay:N.destinationGasUsdLocaleDisplay,totalProviderFeesUsdLocaleDisplay:N.totalProviderFeesUsdLocaleDisplay,providerFeeUsdLocaleDisplay:N.providerFeeUsdLocaleDisplay,trailsFeeUsdLocaleDisplay:N.trailsFeeUsdLocaleDisplay,noSufficientBalance:N.noSufficientBalance??!1,expiresAt:N.expiresAt??null,priceImpactDetails:N.priceImpactDetails??null,passthroughEligible:N.passthroughEligible,passthroughTransactionStates:N.passthroughTransactionStates};return clearTimeout(i),{quote:I,send:async e=>{let t=e?.selectedFeeOption===void 0?p??null:e.selectedFeeOption,{depositUserTxnReceipt:n,destinationIntentTransaction:r,totalCompletionSeconds:i}=await P({selectedFeeOption:t,onOriginSend:e?.onOriginSend,depositTransactionHash:e?.depositTransactionHash,skipCommit:e?.skipCommit});return{originTransaction:{transactionHash:n?.transactionHash,explorerUrl:Xa({txHash:n?.transactionHash,chainId:B}),receipt:n},destinationTransaction:{transactionHash:r?.txnHash,explorerUrl:Xa({txHash:r?.txnHash,chainId:V}),receipt:r},totalCompletionSeconds:i}},feeOptions:F?.feeOptions??[]}}finally{clearTimeout(i)}}catch(e){if(e instanceof Error&&e.name===`AbortError`||ue.current.signal.aborted){let t=j(e,{boundary:`sdk`,code:`quote.timeout`,message:`No route available`,details:{aborted:ue.current.signal.aborted}});throw s.console.error(`[trails-sdk] [useQuote] Quote request timed out:`,t),r_(t)}let t=ee(e,{boundary:`sdk`,code:`quote.request`,apiBoundary:`trails-api`});throw s.console.error(`[trails-sdk] [useQuote] Error getting quote:`,t),r_(t)}},enabled:xt,staleTime:0,refetchOnWindowFocus:!1,refetchOnMount:`always`,refetchInterval:!1,retry:!1,refetchOnReconnect:!0}),Dt=(k||Te)&&Ct?.send||null;return{quote:xt&&Ct?.quote||null,send:Dt,isLoadingQuote:Re.isLoading||wt,quoteError:Re.error??(Tt?r_(Tt):null),quoteErrorPrettified:Re.error?.message??T(Tt),refetchQuote:async()=>{await Et()},abort:()=>{s.console.log(`[trails-sdk] useQuote abort() called`),s.console.log(`[trails-sdk] Active operations before abort:`,$a.getAll()),ue.current.abort(),$a.abortAll(),s.console.log(`[trails-sdk] Abort completed, active operations:`,$a.getAll())},feeOptions:Ct?.feeOptions||[],isRecipientContract:_t??null,isSenderContractOnOrigin:mt??null,isSenderContractOnDestination:gt??null,isEdgeDestinationWithCalldata:Ue}}function o_(e){if(e instanceof Lt){if(e.code===`MULTIPLE_AMOUNT_SLOTS`)return new Hg(`MULTIPLE_AMOUNT_SLOTS`,e.message,e);if(e.code===`INVALID_AMOUNT_OFFSET`)return new Hg(`UNSAFE_PLACEHOLDER_MATCH`,e.message,e)}return e}async function s_(e){s.console.log(`[trails-sdk] New quote generated - aborting all existing operations`),$a.abortAll();let{account:t,originTokenAddress:n,originChainId:r,originTokenBalance:i,destinationChainId:a,recipient:o,destinationTokenAddress:c,swapAmount:l,tradeType:u=ln.EXACT_OUTPUT,originTokenSymbol:d,destinationTokenSymbol:f,client:p,trailsClient:m,destinationApproveAddress:h,destinationCalldata:g,onTransactionStateChange:_,sourceTokenDecimals:v,destinationTokenDecimals:y,slippageTolerance:b,originNativeTokenPriceUsd:x,swapProvider:S,bridgeProvider:C,swapProviderFallback:w,bridgeProviderFallback:T,fundMethod:E,mode:D,checkoutOnHandlers:O,selectedFeeOption:k,walletId:A,abortSignal:j,commitIntentFn:M,executeIntentFn:N,sequenceProjectAccessKey:P,sequenceIndexerUrl:F,isSmartWallet:I,isSenderContractOnOrigin:ee,trailsApiKey:te,trailsApiUrl:ne,sequenceMetadataUrl:re,onramp:ie,refundAddress:L,isMultiCallEncoding:R,intentProtocolVersion:ae}=e,{sourceTokenPriceUsd:z,destinationTokenPriceUsd:B}=e,V=E??`wallet`;if(!t?.address||gt(t.address))throw Error(`Account address is required and must not be the zero address`);if(!l||l===`0`)throw Error(`swapAmount is required and must be a positive numeric value`);if(!r)throw Error(`Origin chain ID is required`);if(!a)throw Error(`Destination chain ID is required`);if(e.originPublicClient){let t=e.originPublicClient?.chain?.id;if(t!==r)throw Error(`Origin public client chain ID mismatch: expected ${r}, got ${t}`)}if(e.destinationPublicClient){let t=e.destinationPublicClient?.chain?.id;if(t!==a)throw Error(`Destination public client chain ID mismatch: expected ${a}, got ${t}`)}let oe=b===void 0?jf(`0.01`):b;if(!v)throw Error(`Source token decimals not provided`);if(!y)throw Error(`Destination token decimals not provided`);let{intentProtocol:H}=await dp({trailsClient:m,override:ae}),se=ro(g);if(gt(o))throw Error(`Recipient address cannot be zero address`);let ce=o,U=h,le=g,ue=S,de=W(r),fe=W(a),pe=yp(r,a),me=Re(r);pe&&me&&(bt(n)&&Pe(c,me)||Pe(n,me)&&bt(c))&&Pe(o,t.address)&&(ce=t.address,ue=on.WETH,se||(le=void 0,se=!1));let he;try{he=zt(g)}catch(e){throw o_(e)}if(se&&he&&!R&&u===ln.EXACT_OUTPUT&&(le=Wt(le||``,l),s.console.log(`[trails-sdk] Same-chain same-token: Replaced placeholder with actual amount in calldata`,{swapAmount:l})),R&&se&&ae&&ae!==nn.v1_5)throw Error(`Multicall encoding (to.calls) requires v1.5 protocol, got "${ae}".`);s.console.log(`[trails-sdk] [intent-protocol] === Protocol Version Selected ===`,{intentProtocol:H});let ge=R;if(se&&u===ln.EXACT_INPUT&&!ge&&!fe){s.console.log(`[trails-sdk] [intent-protocol] Calldata wrapping required for custom calldata`,{intentProtocol:H,wrapperType:`TrailsUtils (Hydrate)`});let e=Wg({intentProtocol:H,destinationAddress:ce,destinationCalldata:le??`0x`,destinationApprovalAddress:U,isExactInput:u===ln.EXACT_INPUT,hasCustomCalldata:se,swapAmount:l,originChainId:r,destinationChainId:a,originTokenAddress:n,destinationTokenAddress:c,trailsUtilsAddress:Ae.trailsUtilsAddress});ce=e.destinationAddress,le=e.destinationCalldata,e.destinationApprovalAddress&&(U=e.destinationApprovalAddress),s.console.log(`[trails-sdk] [intent-protocol] Destination encoding`,{intentProtocol:H,strategy:{none:`none`,v1_5_trails_utils_hydrate:`TrailsUtils (Hydrate)`}[e.strategy],effectiveDestinationAddress:ce,hasApprovalAddress:!!U})}if(!z||!B)try{let e=await op(m,[{tokenSymbol:d,tokenAddress:n,chainId:r},{tokenSymbol:f,tokenAddress:c,chainId:a}]);z=e.find(e=>ft(e.token.tokenAddress,n,r))?.priceUsd??0,B=e.find(e=>ft(e.token.tokenAddress,c,a))?.priceUsd??0}catch(e){s.console.error(`[trails-sdk] Error getting token prices:`,e)}de&&!z&&ze(n)&&(z=1),fe&&!B&&ze(c)&&(B=1),sf({userAddress:t.address,originChainId:r,destinationChainId:a,originTokenAddress:n,originTokenAmount:u===ln.EXACT_INPUT?l:void 0,originTokenDecimals:v,destinationTokenAddress:c,destinationTokenSymbol:f||``,destinationTokenAmount:u===ln.EXACT_OUTPUT?l:void 0,destinationTokenDecimals:y,mode:D,fundMethod:V,sourceTokenPriceUsd:z?.toString(),destinationTokenPriceUsd:B?.toString(),tradeType:u.toString(),swapProvider:ue||void 0,bridgeProvider:C||void 0,onramp:ie,walletId:A,destinationCalldata:g});let _e=$(r);if(!_e)throw lf({error:`Chain ${r} not found`,userAddress:t.address,mode:D,fundMethod:V,originChainId:r,destinationChainId:a,originTokenAddress:n,destinationTokenAddress:c,destinationTokenSymbol:f}),Error(`Chain ${r} not found`);if(fe&&!e.destinationEdgePlugin&&!ut((ce??``).trim()))throw Error("[trails-sdk] prepareSend: Solana destination requires a Solana recipient address (pass `to.recipient`/`toAddress`) or a registered destination edge plugin (e.g. @0xtrails/svm).");let ve=e.originPublicClient??Va(de?a:r);O?.triggerCheckoutStart&&O.triggerCheckoutStart();let ye=new AbortController,be=()=>ye.abort();j&&(j.aborted?ye.abort():j.addEventListener(`abort`,be,{once:!0}));let xe;try{xe=await Vg({queryClient:e.queryClient,mainSignerAddress:t.address,originChainId:r,originTokenAddress:n,originTokenBalance:i,originTokenDecimals:v,originTokenSymbol:d,destinationChainId:a,destinationTokenAddress:c,destinationTokenSymbol:f,destinationTokenDecimals:y,swapAmount:l,recipient:ce,destinationApproveAddress:U,destinationCalldata:le,walletClient:p,publicClient:ve,account:t,chain:_e,onTransactionStateChange:_,transactionStates:[],trailsClient:m,sourceTokenPriceUsd:z,destinationTokenPriceUsd:B,originNativeTokenPriceUsd:x,slippageTolerance:oe,tradeType:u,swapProvider:ue,bridgeProvider:C,swapProviderFallback:w,bridgeProviderFallback:T,fundMethod:V,mode:D,checkoutOnHandlers:O,selectedFeeOption:k,walletId:A,abortSignal:ye.signal,commitIntentFn:M,executeIntentFn:N,sequenceProjectAccessKey:P,sequenceIndexerUrl:F,isSmartWallet:I,isSenderContractOnOrigin:ee,trailsApiKey:te,trailsApiUrl:ne,sequenceMetadataUrl:re,refundAddress:L,isMultiCallEncoding:R,intentProtocolVersion:H,edge:e.edge,edgePlugin:e.edgePlugin,destinationEdgePlugin:e.destinationEdgePlugin})}catch(e){throw j?.removeEventListener(`abort`,be),e}return{...xe,send:(...e)=>{let t=`intent-execution-${r}-${a}-${c_()}`;return $a.register(t,ye),xe.send(...e).finally(()=>{$a.unregister(t),j?.removeEventListener(`abort`,be)})}}}function c_(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}const l_=ur(void 0),u_=({children:e})=>{let[t,n]=X(ln.EXACT_INPUT),[r,i]=X(``),[a,o]=X(``),[s,c]=X(null),l=K(()=>{n(null),i(``),o(``)},[]),u=K((e,t)=>{if(e===t)return!0;if(e===null||t===null)return!1;let n=[`swap`,`fund-direct-transfer`,`fund-wallet`];return n.includes(e)&&n.includes(t)},[]),d=K(e=>s!==null&&s!==e&&!u(s,e)?(l(),c(e),!0):(c(e),!1),[s,l,u]);return Z(l_.Provider,{value:{tradeType:t,setTradeType:n,sellAmount:r,setSellAmount:i,buyAmount:a,setBuyAmount:o,resetSwapState:l,lastFormMode:s,enterFormMode:d},children:e})};function d_(){let e=hr(l_);if(e===void 0)throw Error(`useSwapState must be used within a SwapStateProvider`);return e}function f_(e){switch(e){case`swap`:return`swap`;case`earn`:return`earn`;case`fund`:return`fund-methods`;case`pay`:return`send-form`;case`withdraw`:return`withdraw`}}function p_(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID().slice(0,8):Math.random().toString(36).slice(2,10)}function m_(e,t){return{screen:e,backTarget:t,key:p_(),timestamp:Date.now()}}function h_(e,t){switch(t.type){case`NAVIGATE`:{let n=e.stack[e.stack.length-1],r=t.data??null;if(e.screen===t.screen&&n?.backTarget===t.backTarget&&e.screenData===r)return e;let i=m_(t.screen,t.backTarget);return{...e,screen:t.screen,stack:[...e.stack,i].slice(-20),direction:`forward`,screenData:t.data??null}}case`GO_BACK`:{if(e.stack.length<=1)return e;let t=e.stack[e.stack.length-1];if(t?.backTarget){let n=e.stack.findLastIndex((n,r)=>n.screen===t.backTarget&&r<e.stack.length-1),r=n>=0?e.stack.slice(0,n+1):e.stack.slice(0,-1),i=r[r.length-1]?.screen??f_(e.mode);return{...e,screen:i,stack:r,direction:`backward`,screenData:null}}let n=e.stack.slice(0,-1),r=n[n.length-1]?.screen??f_(e.mode);return{...e,screen:r,stack:n,direction:`backward`,screenData:null}}case`GO_BACK_TO`:{let n=e.stack.findLastIndex(e=>e.screen===t.screen);if(n<0)return e;let r=e.stack.slice(0,n+1);return{...e,screen:t.screen,stack:r,direction:`backward`,screenData:null}}case`REPLACE`:{let n=t.data??null;if(e.screen===t.screen&&e.screenData===n)return e;let r=[...e.stack];return r.length>0?r[r.length-1]=m_(t.screen):r.push(m_(t.screen)),{...e,screen:t.screen,stack:r,direction:`none`,screenData:t.data??null}}case`SET_MODE`:{let n=f_(t.mode);return{...e,mode:t.mode,configuredMode:t.mode,screen:n,stack:[m_(n)],direction:`none`,screenData:null}}case`OVERRIDE_MODE`:{let n=f_(t.mode);return{...e,mode:t.mode,screen:n,stack:[m_(n)],direction:`none`,screenData:null}}case`RESET_MODE`:{let t=f_(e.configuredMode);return{...e,mode:e.configuredMode,screen:t,stack:[m_(t)],direction:`none`,screenData:null}}case`GO_HOME`:{let t=f_(e.mode);return{...e,screen:t,stack:[m_(t)],direction:`backward`,screenData:null}}case`RESET`:{let n=t.initialScreen??f_(e.configuredMode);return{...e,mode:e.configuredMode,screen:n,stack:[m_(n)],direction:`none`,screenData:null}}default:return e}}function g_(e){let t=f_(e);return{screen:t,mode:e,configuredMode:e,stack:[m_(t)],direction:`none`,screenData:null}}const __=ur(null);function v_({children:e,configuredMode:t}){let[n,r]=br(h_,t,g_),i=Y(t);q(()=>{t!==i.current&&(i.current=t,r({type:`SET_MODE`,mode:t}))},[t]);let a=Y(new Set),o=Y(n.screen);q(()=>{let e=o.current;if(o.current=n.screen,e!==n.screen){let t={from:e,to:n.screen};for(let e of a.current)try{e(t)}catch(e){s.console.error(`[trails-sdk] Navigation listener error`,e)}}},[n.screen]);let c=K(e=>(a.current.add(e),()=>{a.current.delete(e)}),[]),l=K((e,t)=>{r({type:`NAVIGATE`,screen:e,backTarget:t?.backTarget,data:t?.data})},[]),u=K(()=>{r({type:`GO_BACK`})},[]),d=K(e=>{r({type:`GO_BACK_TO`,screen:e})},[]),f=K((e,t)=>{r({type:`REPLACE`,screen:e,data:t})},[]),p=K(()=>{r({type:`GO_HOME`})},[]),m=K(e=>{r({type:`RESET`,initialScreen:e})},[]),h=K(e=>r({type:`OVERRIDE_MODE`,mode:e}),[]),g=K(()=>r({type:`RESET_MODE`}),[]),_=n.stack.length>1,v=J(()=>{if(n.stack.length<=1)return null;let e=n.stack[n.stack.length-1];return e?.backTarget?e.backTarget:n.stack[n.stack.length-2]?.screen??null},[n.stack]),y=J(()=>({state:n,dispatch:r,navigate:l,goBack:u,goBackTo:d,replace:f,goHome:p,reset:m,overrideMode:h,resetMode:g,canGoBack:_,backScreen:v,direction:n.direction,mode:n.mode,configuredMode:n.configuredMode,screen:n.screen,subscribe:c}),[n,_,v]);return Z(__.Provider,{value:y,children:e})}function y_(){let e=hr(__);if(!e)throw Error(`useViewManager must be used within a ViewManagerProvider`);return e}function b_(e){let{subscribe:t}=y_(),n=Y(e);n.current=e,q(()=>t(e=>n.current(e)),[t])}function x_(e,t,n){let{replace:r,navigate:i}=y_(),a=Y(!1);return q(()=>{let o=a.current;a.current=e,e&&(o||(n?.backTarget?i(t,{backTarget:n.backTarget}):r(t)))},[e,t,n?.backTarget,r,i]),e}const S_={apiKey:``,renderInline:!1};function C_({children:e,props:t=S_,walletRuntimeMode:n=`none`}){let r=Z(Co,{props:t,children:Z(v_,{configuredMode:t?.mode??`pay`,children:Z(qo,{children:Z(Qo,{children:Z(ll,{children:Z(bl,{children:Z(Cl,{children:Z(Jl,{children:Z(su,{children:Z(uu,{children:Z(u_,{children:Z(pu,{children:Z(_u,{children:Z(xu,{children:Z(Ou,{children:Z(Lu,{children:Q(Bu,{children:[Z(Id,{}),Z(Rd,{children:e})]})})})})})})})})})})})})})})})})});return Z(Do,{mode:n,children:t?.solanaWallet==null?r:Z(Gu,{solanaWallet:t.solanaWallet,children:r})})}const w_=({isOpen:e,onClose:t,children:n})=>{let r=Y(null);return q(()=>{let n=e=>{e.key===`Escape`&&t()};return e&&document.addEventListener(`keydown`,n),()=>{document.removeEventListener(`keydown`,n)}},[e,t]),e?Q(hi,{children:[Z(`div`,{"aria-hidden":`true`,className:`fixed inset-0 bg-black/50 backdrop-blur-sm z-50 h-full w-full trails-modal-overlay`}),Z(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`modal-title`,className:`fixed inset-0 flex items-center justify-center z-50 p-0 sm:p-4 h-full w-full text-gray-900 dark:text-white`,onClick:n=>{e&&r.current&&!r.current.contains(n.target)&&t()},onKeyDown:e=>{e.key===`Escape`&&t?.()},children:Z(`div`,{ref:r,className:`pointer-events-auto relative trails-modal-frame`,children:n})})]}):null};function T_(e,t,n){return e===null||!n.requiresWalletFunding?{type:`apply`}:W(e)?t.hasEvmWallet?n.hasSvmAdapter?t.hasSolanaWallet?{type:`apply`}:{type:`connect-solana`}:{type:`apply`}:{type:`connect-evm`}:t.hasEvmWallet?t.activeEvmChainId!==void 0&&t.activeEvmChainId!==e?{type:`switch-evm`,chainId:e}:{type:`apply`}:{type:`connect-evm`}}function E_(e){let{isConnected:t}=Kr(),n=Jr(),r=qu(),i=Hu(),{selectedToken:a}=ul();return J(()=>{let o=t&&n.length>0;if(!Td({connectedWallets:n,svmWallet:r,selectedFundingWallet:i,hasActiveEvmConnection:o})&&!(a?.chainId!=null&&W(a.chainId)&&Zu(i)))return nd(e,i,n)},[n,e,t,a?.chainId,i,r])}function D_(e,t=!1){let{selectedChainId:n,setSelectedChainId:r,pendingChainId:i,setPendingChainId:a}=mu(),{address:o,chainId:c,isConnected:l}=Yr(),u=Jr(),d=ni(),f=E_(o),p=qu(),{data:m}=si(),{connect:h,switchAccount:g}=ai(),_=li(),{navigate:v,screen:y}=y_(),{selectedFundingWallet:b,setSelectedFundingWallet:x,setSelectedFundMethod:S}=Vu(),C=Y(!1),w=Y(!1),T=e===`wallet`&&!t,E=p!=null,D=J(()=>_.filter(e=>e.namespace===`eip155`),[_]),O=J(()=>({hasEvmWallet:l&&u.length>0,hasSolanaWallet:!!p?.connected&&!!p.publicKey,activeEvmChainId:c}),[c,u.length,l,p?.connected,p?.publicKey]),k=J(()=>({requiresWalletFunding:T,hasSvmAdapter:E}),[E,T]),A=K(()=>{if(i==null)return;if(W(i)){if(!O.hasSolanaWallet)return;let e=Od({connectedWallets:u,svmWallet:p,session:d});e&&!Qu(e,b)&&(x(e),S(`wallet`));return}if(!O.hasEvmWallet||!(Zu(b)||!f))return;let e=Dd({connectedWallets:u,svmWallet:p,session:d});e&&(x(e.selection),S(`wallet`),e.wallet.address.toLowerCase()!==o?.toLowerCase()&&g(e.wallet.connectionId,e.wallet.address))},[o,u,O.hasEvmWallet,O.hasSolanaWallet,f,i,b,S,x,d,g,p]),j=K(e=>{r(e),a(null)},[a,r]),M=K(async e=>{if(C.current||!m)return!1;C.current=!0;try{return await Hh({walletClient:m,desiredChainId:e}),j(e),!0}catch(e){return s.console.error(`[trails-sdk] Failed to switch EVM chain from token selector:`,e),a(null),!1}finally{C.current=!1}},[j,a,m]),N=K(async()=>{let e=p?cd(p):void 0,t=od(e,D.map(e=>({id:e.id,name:e.name})));if(!t){s.console.warn(`[trails-sdk] Could not resolve EVM wallet for connected Solana wallet brand:`,e),v(`wallet-list`,{backTarget:y});return}if(!w.current){w.current=!0;try{await h(t)}catch(e){s.console.error(`[trails-sdk] Failed to connect matching EVM wallet from chain selector:`,e),a(null)}finally{w.current=!1}}},[h,D,v,y,a,p]),P=K(async()=>{if(!p?.connect){v(`wallet-list`,{backTarget:y});return}let e=Ed(u,f),t=e?ud(e,d):void 0,n=od(t,(p.availableWallets??[]).map(e=>({id:e.walletId,name:e.walletName})))??od(t,[{id:t??``,name:t}]);if(!n){s.console.warn(`[trails-sdk] Could not resolve Solana wallet for connected EVM wallet brand:`,t),v(`wallet-list`,{backTarget:y});return}if(!w.current){w.current=!0;try{await Promise.resolve(p.connect(n))}catch(e){s.console.error(`[trails-sdk] Failed to connect matching Solana wallet from chain selector:`,e),a(null)}finally{w.current=!1}}},[u,f,v,y,a,p,d]),F=K(async e=>{let t=T_(e,O,k);switch(t.type){case`apply`:j(e);return;case`connect-evm`:e!==null&&a(e),await N();return;case`connect-solana`:e!==null&&a(e),await P();return;case`switch-evm`:a(t.chainId);return}},[j,N,P,O,k,a]);return q(()=>{if(i==null||!T)return;A();let e=T_(i,O,k);if(e.type===`apply`){r(i),a(null);return}if(e.type===`connect-evm`){N();return}if(e.type===`connect-solana`){P();return}e.type===`switch-evm`&&M(e.chainId)},[O,i,T,N,P,k,a,r,M,A]),{selectedChainId:n,handleChainSelect:F,pendingChainId:i}}function O_(){return ni()?.connections.some(e=>e.namespace===`eip155`)??!1}function k_(){let{screen:e}=y_(),t=Y(e);t.current=e;let n=Y({});return{trackClick:K((e={})=>{let{component:r=`unknown`,action:i=`click`,label:a,value:o,metadata:c,debounceMs:l=300}=e,u=`${r}-${i}-${a||``}`,d=Date.now(),f=n.current[u]||0;if(l>0&&d-f<l){s.console.debug(`Click debounced:`,u);return}n.current[u]=d;let p={};if(c)for(let[e,t]of Object.entries(c))p[e]=t?.toString()||``;wf({screen:t.current,component:r?.toString()||`unknown`,action:i?.toString()||`click`,label:a?.toString(),value:o?.toString(),...p,timestamp:d.toString()}),s.console.debug(`Click tracked:`,{component:r,action:i,label:a,value:o,metadata:c})},[])}}const A_=()=>{let{screen:e,navigate:t}=y_(),{trackClick:n}=k_();return Z(`button`,{type:`button`,onClick:()=>{n({component:`AccountActionsDropdown`,action:`open_settings`,metadata:{fromScreen:e}}),t(`account-settings`,{backTarget:e})},className:`flex h-8 w-8 justify-center items-center rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-600`,title:`Open account settings`,children:Z(Yi,{className:`w-4 h-4`})})},j_=()=>{let{screen:e,navigate:t}=y_(),{trackClick:n}=k_();return Z(`button`,{type:`button`,onClick:()=>{n({component:`AccountIntentTransactionHistoryButton`,action:`view_transaction_history`,metadata:{fromScreen:e}}),t(`account-history`,{backTarget:e})},className:`relative flex h-8 w-8 justify-center items-center rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-600`,title:`View transaction history`,children:Z(Bi,{className:`w-4 h-4`})})},M_=({onBack:e,headerContent:t,rightSideContent:n,headerContentAlign:r=`left`,showAccountActions:i=!1,customActions:a})=>{let o=O_(),{renderInline:s}=wo(),{getHandleCloseModal:c,isModalOpen:l}=wx(),{trackClick:u}=k_();return Q(`div`,{className:`flex items-center justify-between w-full mb-4`,children:[Q(`div`,{className:`flex items-center`,children:[e&&Z(`button`,{type:`button`,onClick:()=>{u({component:`ScreenHeader`,action:`navigate_back`,metadata:{headerContent:typeof t==`string`?t:`custom`}}),e()},className:`flex h-8 w-8 justify-center items-center rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600 mr-2`,title:`Back`,children:Z(Oi,{className:`h-4 w-4`})}),t&&Z(`h2`,{className:`text-lg font-bold ${r===`center`?`text-center`:`text-left`} text-gray-900 dark:text-white`,children:t})]}),Q(`div`,{className:`flex items-center gap-2`,children:[n&&Z(`div`,{className:`text-right max-w-[280px]`,children:n}),a,o&&i&&Q(hi,{children:[Z(`div`,{className:`m-0`,children:Z(j_,{})}),Z(A_,{})]}),!s&&l&&Z(`button`,{type:`button`,onClick:()=>{u({component:`ScreenHeader`,action:`close_modal`,metadata:{headerContent:typeof t==`string`?t:`custom`}});let e=c();e&&e()},className:`flex h-8 w-8 justify-center items-center rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600`,title:`Close`,children:Z(ra,{className:`h-4 w-4`})})]})]})};function N_(e){if(e==null)return!0;if(typeof e==`number`)return e===0;let t=e.replace(/[^0-9.-]/g,``);if(!t||t===`-`)return!0;let n=parseFloat(t);return!_s(n)||n===0}function P_(e){return e?{USD:`$`,EUR:`€`,GBP:`£`,JPY:`¥`,CAD:`$`,AUD:`$`,CHF:`₣`,BTC:`₿`,ETH:`Ξ`,USDC:`$`,USDT:`$`}[e.toUpperCase()]||e:``}function F_(e){if(!e)return{symbol:``};let t=e.split(`_`),n=t[0]||e,r=t[1];return{symbol:n,chainId:r?{BASE:8453,ETHEREUM:1,ETH:1,POLYGON:137,ARBITRUM:42161,OPTIMISM:10,BSC:56,AVALANCHE:43114}[r.toUpperCase()]:void 0}}function I_(e){if(e?.length!==2)return``;let t=e.toUpperCase().split(``).map(e=>127462+e.charCodeAt(0)-65);return String.fromCodePoint(...t)}function L_(e,t){let n=Sa.from(`function transfer(address,uint256) returns (bool)`);return Sa.encodeData(n,[e,t])}const R_=2*ge,z_=Ee,B_=ur({isUserActive:!0});function V_({children:e}){let[t,n]=X(!0),r=Y(void 0),i=Y(0);return q(()=>{let e=()=>{n(!0),r.current&&clearTimeout(r.current),r.current=setTimeout(()=>n(!1),R_)},t=()=>{let t=Date.now();t-i.current>=z_&&(i.current=t,e())},a=[`mousemove`,`keydown`,`click`,`scroll`,`touchstart`];return a.forEach(e=>{window.addEventListener(e,t,{passive:!0})}),e(),()=>{a.forEach(e=>{window.removeEventListener(e,t)}),r.current&&clearTimeout(r.current)}},[]),Z(B_.Provider,{value:{isUserActive:t},children:e})}function H_(){return hr(B_)}function U_(e,t){let n=[],r=e?.trim(),i=t?.trim();return r&&n.push(r),i&&n.push(i),n}function W_(){let e=hr(So)?.props,t=hr(zx)?.config,n=qu()?.connection?.rpcUrls;return J(()=>so([...U_(e?.solanaRpcUrl,t?.solanaRpcUrl),...n??[]]),[t?.solanaRpcUrl,e?.solanaRpcUrl,n])}function G_(){let e=hr(So)?.props,t=hr(zx)?.config,n=qu(),r=n?.connection?.rpcUrls,i=n?.connection?.rpcEndpoint;return J(()=>so([...U_(e?.solanaRpcUrl,t?.solanaRpcUrl),...r??[],...i?[i]:[]]),[t?.solanaRpcUrl,e?.solanaRpcUrl,r,i])}const K_=[];function q_(e,t){let n=Nt(101),r=gs(),i=J(()=>n?.getOriginTokens()??K_,[n]),a=!t?.disabled&&!!e&&i.length>0,o=W_(),{data:s=[],isLoading:c}=Or({...Ih.solanaFundingTokens(i,a?e:null,r,o),enabled:a});return{tokens:s,baseTokens:i,isLoading:a&&c}}const J_=5*Ee,Y_=[],X_=5*Ee;function Z_(e){return e===!1||e===void 0?!1:Math.max(e,X_)}function Q_(e,t,n){let r=$h(),i=gs(),{isUserActive:a}=H_(),{shouldSkipBalanceFetch:o}=Uu(),s=Zu(Hu()),{data:c=[]}=Hx(),l=(n?.disabled===void 0?o:n.disabled)||s?null:e,u=a?Z_(n?.refetchInterval):!1,d=n?.includeAllChains??!1,f=J(()=>!d&&c.length>0?new Set(c.map(e=>e.id)):null,[d,c]),p=K(({balances:e})=>{let t=e.filter(e=>{try{return e.balance&&BigInt(e.balance)>0n}catch{return!1}});if(!f)return t.sort(bh);let n=t.filter(e=>f.has(e.chainId||0));return n.length===0?t.sort(bh):n.sort(bh)},[f]),{data:m=Y_,isLoading:h,error:g,refetch:_}=Or({...Ih.withPrices(l,r,i),select:p,refetchOnWindowFocus:!0,refetchOnReconnect:!0,refetchInterval:u,refetchIntervalInBackground:!1,refetchOnMount:!0});return{isLoadingBalances:h,isLoadingPrices:h,isLoadingSortedTokens:h,balanceError:g,sortedTokens:m,refetch:async()=>{await _()}}}function $_(e,t){let n=$h(),{isUserActive:r}=H_(),i=r?Z_(t?.refetchInterval):!1,a=t?.staleTime,o=e.filter(e=>e!==null&&e.length>0).map(e=>e.toLowerCase()),{data:s,isLoading:c,error:l,refetch:u}=Or({...Ih.multiAccount(o,n,{page:t?.page,pageSize:t?.pageSize}),staleTime:a,refetchOnWindowFocus:!0,refetchOnReconnect:!0,refetchInterval:i,refetchIntervalInBackground:!0,refetchOnMount:!0}),d={};for(let e of o)d[e]={tokenBalancesData:s?.[e],isLoading:c,error:l};return{balancesByAccount:d,isLoading:c,error:l,refetch:async()=>{await u()}}}function ev(e,t,n){let r=gs(),{isUserActive:i}=H_(),a=G_(),o=n?.disabled||!t||!e,s=o?null:e,c=o?null:t,l=i?Z_(n?.refetchInterval):!1,{data:u,isLoading:d,error:f,refetch:p}=Or({...n?.withPrices?Ih.onchainWithPrices(s,c,r,a):Ih.onchain(s,c,a),refetchInterval:l,refetchIntervalInBackground:!1,refetchOnWindowFocus:!0,refetchOnReconnect:!0,refetchOnMount:!0}),m=u?.token??e??null;return{token:o?e:m,isLoadingBalance:d,error:f,refetch:p}}function tv({account:e,token:t,amount:n,chainId:r}){let i=$h(),a=gs();return Or({...Ih.sufficientToken(e,t,n,r,i,a),refetchOnWindowFocus:!1})}function nv({account:e,targetAmountUsd:t}){let n=$h(),r=gs();return Or({...Ih.sufficientUsd(e,t,n,r),refetchOnWindowFocus:!1})}function rv(e){let t=$h(),n=gs();return Or({...Ih.totalUsd(e,t,n),refetchOnWindowFocus:!1,refetchOnReconnect:!0,refetchIntervalInBackground:!1,refetchOnMount:!0})}function iv({evmAddress:e,solanaAddress:t,networks:n}){let r=!!t&&n.includes(`solana`),{data:i=0,isLoading:a}=rv(e??null),{tokens:o,isLoading:s}=q_(r?t:null),c=J(()=>o.reduce((e,t)=>e+Number(t.balanceUsd??0),0),[o]);return{totalBalanceUsd:(e?i:0)+(r?c:0),isLoading:!!e&&a||r&&s}}const av=90*Ee;function ov(e,t){let n=gs(),r=kr(),{isUserActive:i}=H_(),a=Or({...rp.byTokens(e,n,r),enabled:!t,refetchInterval:i?av:!1});return{...a,tokenPrices:a.data,isLoadingTokenPrices:a.isLoading}}function sv(e){let t=gs(),n=kr(),{isUserActive:r}=H_(),i=ep(n,e??null),a=Or({...rp.byToken(e??null,t,n),initialData:i.price,initialDataUpdatedAt:i.updatedAt,refetchInterval:r?av:!1});return{...a,tokenPrice:a.data,isLoadingTokenPrice:a.isLoading}}var cv=class extends Ma{static fromTrailsApiClient(e){return new Ma(e.getHostname(),e.getFetch())}constructor(e,t){let n=(n,r)=>{let i={};return t?.jwt&&t?.jwt.length>0&&(i.Authorization=`BEARER ${t?.jwt}`),e&&e.length>0&&(i[`X-Access-Key`]=e),r=r||{},r.headers={...r.headers,...i},fetch(n,r)},r=t?.hostname&&t?.hostname.length>0?t?.hostname:`https://trails-api.sequence.app`;super(r.endsWith(`/`)?r.slice(0,-1):r,n)}};const lv={},uv=ur(null);function dv({config:e=lv,children:t}){let n=J(()=>({config:e}),[e]);return Z(uv.Provider,{value:n,children:t})}function fv(){return hr(uv)}function pv(e){return!!e?.mesh}function mv(e){return e?.mesh?.environment??`production`}function hv({apiKey:e,jwt:t,hostname:n}){return new cv(e,{jwt:t,hostname:n})}const gv=e=>{let t=Vx(),n=fv();return J(()=>hv({apiKey:e?.apiKey||n?.config.apiKey||t.trailsApiKey||``,hostname:e?.hostname||n?.config.hostname||t.trailsApiUrl,jwt:e?.jwt??n?.config.jwt}),[e?.hostname,e?.apiKey,e?.jwt,n?.config.apiKey,n?.config.hostname,n?.config.jwt,t.trailsApiKey,t.trailsApiUrl])};function _v(e,t,n){if(!t||!n)return[];let r=n.toUpperCase();return e.filter(e=>Number(e.chainId)===t&&e.symbol?.toUpperCase()===r)}function vv(e,t,n){return _v(e,t,n).length>0}function yv(e){return e?.mesh?.environment??`production`}const bv=({onBack:e,title:t,className:n=``})=>Q(`div`,{className:`flex items-center gap-2 mb-4 ${n}`,children:[e&&Z(`button`,{type:`button`,onClick:e,className:`flex h-8 w-8 justify-center items-center rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600`,title:`Back`,children:Z(Oi,{className:`h-4 w-4`})}),t&&Z(`h2`,{className:`text-lg font-semibold text-left text-gray-900 dark:text-white`,children:t})]}),xv=3e4,Sv=new Map,Cv=new Map,wv=new Map,Tv=new Map,Ev=new Map,Dv=new Map;function Ov(e){return new Ma(e?.hostname&&e.hostname.length>0?e.hostname:`https://trails-api.sequence.app`,(t,n)=>{let r={};return e?.jwt&&e.jwt.length>0&&(r.Authorization=`BEARER ${e.jwt}`),e?.apiKey&&e.apiKey.length>0&&(r[`X-Access-Key`]=e.apiKey),n=n||{},n.headers={...n.headers,...r},fetch(t,n)})}function kv(e){return JSON.stringify({hostname:e?.hostname??``,apiKey:e?.apiKey??``,jwt:e?.jwt??``,environment:mv(e)})}async function Av(e){let t=kv(e),n=Sv.get(t);if(n&&n.expiresAt>Date.now())return n.integrations;let r=Cv.get(t);if(r)return r;let i=Ov(e),a={environment:mv(e)},o=i.getMeshIntegrations(a).then(e=>{let n=e.integrations||[];return Sv.set(t,{integrations:n,expiresAt:Date.now()+xv}),n}).finally(()=>{Cv.delete(t)});return Cv.set(t,o),o}async function jv(e,t){return(await Av(t)).find(t=>t.key===e)?.id}async function Mv(e){return await jv(`coinbaseRamp`,e)??jv(`coinbase`,e)}async function Nv(e){return await jv(`binanceInternationalDirect`,e)??jv(`binanceInternational`,e)}async function Pv(e){return await jv(`bitfinexDirect`,e)??jv(`bitfinex`,e)}async function Fv(e,t){let n=!!e.address&&!!e.symbol&&e.destinationChainId!==void 0&&e.destinationChainId!==null&&!!e.amount,r=e.authOnly===!0||!n,i=JSON.stringify({config:kv(t),request:{authOnly:r,userId:e.userId??``,address:r?``:e.address??``,symbol:r?``:e.symbol??``,amount:r?``:e.amount??``,destinationChainId:r?``:e.destinationChainId?.toString()??``,integrationId:e.integrationId??``,exchangeType:e.exchangeType??``,restrictMultipleAccounts:e.restrictMultipleAccounts??!1,transactionId:e.transactionId??``}}),a=wv.get(i);if(a&&a.expiresAt>Date.now())return a.response;let o=Tv.get(i);if(o)return o;let s=Ov(t),c={environment:mv(t),clientId:t?.mesh?.clientId??t?.clientId,authOnly:r,userId:e.userId,integrationId:e.integrationId,exchangeType:e.exchangeType,transactionId:e.transactionId,restrictMultipleAccounts:e.restrictMultipleAccounts};r||(c.recipientAddress=e.address,c.tokenSymbol=e.symbol,c.destinationChainId=e.destinationChainId?.toString(),c.amount=e.amount);let l=s.createMeshLinkToken(c).then(e=>(wv.set(i,{response:e,expiresAt:Date.now()+5e3}),e)).finally(()=>{Tv.delete(i)});return Tv.set(i,l),l}async function Iv(e,t){let n=JSON.stringify({config:kv(t),request:{integrationId:e.integrationId??``,exchangeType:e.exchangeType??``,chainIds:e.chainIds??[]}}),r=Ev.get(n);if(r&&r.expiresAt>Date.now())return r.tokens;let i=Dv.get(n);if(i)return i;let a=Ov(t),o={environment:mv(t),integrationId:e.integrationId,exchangeType:e.exchangeType,chainIds:e.chainIds},s=a.getMeshSupportedTokens(o).then(e=>{let t=e.tokens||[];return Ev.set(n,{tokens:t,expiresAt:Date.now()+xv}),t}).finally(()=>{Dv.delete(n)});return Dv.set(n,s),s}const Lv=`trails_mesh_access_tokens`,Rv=`trails_mesh_user_ids`,zv=`trails_mesh_session_key_v1`,Bv=`enc:v1:`;function Vv(){return typeof window>`u`?null:window.sessionStorage}function Hv(e){let t=``;for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return btoa(t)}function Uv(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function Wv(e){try{let t=e.getItem(zv);if(t)return Uv(t);let n=new Uint8Array(32);return crypto.getRandomValues(n),e.setItem(zv,Hv(n)),n}catch{return null}}function Gv(e,t){try{let n=Wv(t);if(!n||n.length===0)return null;let r=new Uint8Array(16);crypto.getRandomValues(r);let i=new TextEncoder().encode(e),a=new Uint8Array(i.length);for(let e=0;e<i.length;e+=1)a[e]=i[e]^n[e%n.length]^r[e%r.length];return`${Bv}${Hv(r)}:${Hv(a)}`}catch{return null}}function Kv(e,t){try{if(!e.startsWith(Bv))return e;let n=Wv(t);if(!n||n.length===0)return null;let[r,i]=e.slice(7).split(`:`);if(!r||!i)return null;let a=Uv(r),o=Uv(i),s=new Uint8Array(o.length);for(let e=0;e<o.length;e+=1)s[e]=o[e]^n[e%n.length]^a[e%a.length];return new TextDecoder().decode(s)}catch{return null}}function qv(e){let t=e.integrationId?.trim().toLowerCase();return t?[e.environment,t].join(`:`):null}function Jv(e){return Array.isArray(e)?e.filter(e=>!!(e&&typeof e==`object`&&typeof e.accountId==`string`&&typeof e.accountName==`string`&&typeof e.accessToken==`string`&&typeof e.brokerType==`string`&&typeof e.brokerName==`string`)).map(e=>({accountId:e.accountId,accountName:e.accountName,accessToken:e.accessToken,brokerType:e.brokerType,brokerName:e.brokerName})):[]}function Yv(){let e=Vv();if(!e)return{};try{let t=e.getItem(Rv);if(!t)return{};let n=Kv(t,e);if(!n)return{};let r=JSON.parse(n);return r&&typeof r==`object`?r:{}}catch{return{}}}function Xv(e){let t=Vv();if(t)try{let n=Gv(JSON.stringify(e),t);if(!n)return;t.setItem(Rv,n)}catch{}}function Zv(e){if(!e)return;let t=Yv(),n=t[e];if(typeof n==`string`&&n.trim().length>0)return n;let r=`trails_${e}_${Date.now()}`;return Xv({...t,[e]:r}),r}function Qv(e){let t=Vv();if(!(!t||!e))try{let n=t.getItem(Rv);if(!n)return;let r=Kv(n,t);if(!r)return;let i=JSON.parse(r);if(!(e in i))return;delete i[e],Xv(i)}catch{}}function $v(e){let t=Vv();if(!t||!e)return[];try{let n=t.getItem(Lv);if(!n)return[];let r=Kv(n,t);return r?Jv(JSON.parse(r)[e]):[]}catch{return[]}}function ey(e,t){let n=Vv();if(!n||!e||t.length===0)return;let r=Jv(t);if(r.length!==0)try{let t=n.getItem(Lv),i=t?Kv(t,n):null,a=i?JSON.parse(i):{},o=Jv(a[e]),s=new Map;for(let e of[...o,...r])s.set(e.accountId,e);a[e]=Array.from(s.values());let c=Gv(JSON.stringify(a),n);if(!c)return;n.setItem(Lv,c)}catch{}}function ty(e){let t=Vv();if(!(!t||!e))try{let n=t.getItem(Lv);if(!n)return;let r=Kv(n,t);if(!r)return;let i=JSON.parse(r);if(!(e in i))return;delete i[e];let a=Gv(JSON.stringify(i),t);if(!a)return;t.setItem(Lv,a)}catch{}}function ny(e){if(e&&typeof e==`object`){let t=e.cause;if(typeof t==`string`&&t.trim().length>0)return t;let n=e.message;if(typeof n==`string`&&n.trim().length>0)return n}return e instanceof Error?e.message:String(e)}function ry(e){return`${Math.floor(e/60)}:${(e%60).toString().padStart(2,`0`)}`}function iy(e){return!e||typeof e!=`object`?null:{...e,status:typeof e.status==`string`&&e.status.length>0?e.status:`pending`}}const ay=({onBack:e,onError:t,authOnly:n=!1,accessTokens:r,toTokenSymbol:i,toTokenAmount:a,toChainId:o,toRecipientAddress:c,onComplete:l,integrationId:u,exchangeName:d})=>{let f=fv(),p=mv(f?.config),m=f?.config.hostname,h=f?.config.apiKey,g=f?.config.jwt,_=f?.config.mesh,v=J(()=>({hostname:m,apiKey:h,jwt:g,mesh:_}),[m,h,g,_]);s.console.log(`[onramp] MeshConnect environment configuration:`,{meshSandbox:f?.config.mesh?.sandbox,environment:p,config:f?.config,defaultEnvironment:`production`,hasContext:!!f}),q(()=>{s.console.log(`[onramp] MeshConnect environment configuration (useEffect):`,{meshSandbox:f?.config.mesh?.sandbox,environment:p,config:f?.config,defaultEnvironment:`production`,hasContext:!!f})},[p,f]);let[y,b]=X(null),[x,S]=X(null),[C,w]=X(!0),[T,E]=X(null),[D,O]=X(null),[k,A]=X(null),[j,M]=X(null),[N,P]=X(`idle`),[F,I]=X(null),[ee,te]=X([]),[ne,re]=X(300),[ie,L]=X(0),R=Y(null),ae=Y(!1),z=Y(null),B=Y(!1),V=J(()=>qv({environment:p,integrationId:u}),[p,u]),oe=J(()=>Zv(V),[V]);q(()=>{let e=$v(V);te(e)},[V]);let H=K(()=>{R.current!==null&&typeof window<`u`&&(window.clearTimeout(R.current),R.current=null)},[]),se=K(async e=>{H();try{await j?.closeLink?.()}catch(e){s.console.warn(`[onramp] Failed to close Mesh popup after render failure:`,e)}P(`error`),I(e),t?.(e)},[H,j,t]);q(()=>{if(k||n)return;let e=setInterval(()=>{re(e=>e>0?e-1:0)},1e3);return()=>clearInterval(e)},[n,k]),q(()=>{s.console.log(`[onramp] generateLinkToken useEffect triggered:`,{environment:p,toRecipientAddress:!!c,toTokenSymbol:!!i,toChainId:!!o,toTokenAmount:!!a,integrationId:!!u}),(async()=>{try{if(w(!0),E(null),s.console.log(`[onramp] Starting link token generation:`,{environment:p,toRecipientAddress:c,toTokenSymbol:i,toChainId:o,toTokenAmount:a,integrationId:u}),!n&&(!c||!i||!o||!a))throw s.console.error(`[onramp] Missing required parameters`,{toRecipientAddress:c,toTokenSymbol:i,toChainId:o,toTokenAmount:a,authOnly:n}),Error(`Missing required parameters`);s.console.log(`[onramp] Generating link token with environment:`,{environment:p,toChainId:o,toTokenSymbol:i,toTokenAmount:a,integrationId:u,isSandbox:p===`sandbox`});let e=await Fv(n?{authOnly:!0,userId:oe,integrationId:u,transactionId:`txid_${ie}_${Date.now()}`}:{userId:oe,address:c,symbol:i,amount:a?.toString(),destinationChainId:o,transactionId:`txid_${ie}_${Date.now()}`,integrationId:u},v);if(s.console.log(`[onramp] Generated Mesh Connect link token response:`,e),s.console.log(`[onramp] Mesh link token generated successfully`),!e.linkToken||typeof e.linkToken!=`string`)throw Error(`Invalid link token received`);if(!e.clientId||typeof e.clientId!=`string`)throw Error(`Invalid Mesh client ID received`);b(e.linkToken),S(e.clientId),re(300)}catch(e){s.console.error(`[onramp] Failed to generate Mesh Connect link token:`,e),E(ny(e)||`Failed to generate link token`),t?.(e)}finally{w(!1)}})().catch(e=>{s.console.error(`[onramp] Error in generateLinkToken:`,e)})},[c,i,o,a,u,p,v,ie,n,oe,t]);let ce=K(e=>{if(s.console.log(`[onramp] MESH CONNECTED:`,e),O(e),e.accessToken&&s.console.log(`[onramp] Ready to transfer - access token available`),n&&e.accessToken&&!B.current){let t=e.accessToken,n=Array.isArray(t?.accountTokens)?t.accountTokens.filter(e=>e?.accessToken&&e?.account).map(e=>({accountId:e.account.accountId,accountName:e.account.accountName,accessToken:e.accessToken,brokerType:t.brokerType,brokerName:t.brokerName})):[];B.current=!0,n.length>0&&(ey(V,n),te(e=>{let t=new Map;for(let r of[...e,...n])t.set(r.accountId,r);return Array.from(t.values())})),H(),A({status:`authenticated`,integrationId:u,accessTokens:n})}},[n,H,u,V]),U=K((e,t)=>{let n=iy(e);if(n){if(ae.current){s.console.log(`[onramp] Ignoring duplicate Mesh transfer event after pending transition: ${t}`,n);return}ae.current=!0,H(),A(n)}},[H]),le=K(e=>{s.console.log(`[onramp] MESH TRANSFER FINISHED:`,e),U(e,`onTransferFinished`)},[U]),ue=K(e=>{if(s.console.log(`[onramp] MESH EXIT:`,e),e){H(),s.console.error(`[onramp] MESH ERROR:`,e),P(`error`),I(e),t?.(e);return}if(!ae.current&&z.current){s.console.log(`[onramp] Treating Mesh exit after initiated transfer as pending`,z.current),U(z.current,`onExitAfterTransferInitiated`);return}H(),P(`closed`),I(`Mesh window was closed before funding completed.`)},[H,U,t]);q(()=>{(async()=>{try{if(!x)return;let e=await import(`@meshconnect/web-link-sdk`);s.console.log(`[onramp] Creating Mesh Connect link...`);let i=e.createLink({clientId:x,language:`en`,accessTokens:(()=>{if(n)return;let e=Jv(r&&r.length>0?r:ee);return e.length>0?e:void 0})(),onIntegrationConnected:ce,onExit:ue,onTransferFinished:le,onEvent:e=>{if(s.console.log(`[onramp] MESH Event:`,e),e.type===`pageLoaded`&&H(),e.type===`integrationConnectionError`||e.type===`transferPreviewError`||e.type===`transferExecutionError`||e.type===`transferConfigureError`||e.type===`connectionUnavailable`){H(),P(`error`);let n=e.payload?.errorMessage||`Mesh Connect failed to load.`;I(n),t?.(n)}e.type===`transferInitiated`&&e.payload&&(H(),s.console.log(`[onramp] MESH TRANSFER INITIATED:`,e.payload),z.current=e.payload),e.type===`transferExecuted`&&e.payload&&U(e.payload,e.type),e.type===`transferCompleted`&&e.payload&&U(e.payload,e.type)}});s.console.log(`[onramp] Mesh Connect link created successfully`),M(i)}catch(e){s.console.error(`[onramp] Failed to create Mesh Connect link:`,e),E(`Failed to load Mesh Connect SDK: ${ny(e)}`),t?.(e)}})()},[H,ce,le,ue,x,r,n,ee,U,t]);let de=K(()=>{if(s.console.log(`[onramp] openMeshConnect called:`,{meshLink:!!j,linkToken:!!y}),!j||!y){s.console.log(`[onramp] Missing requirements for opening`);return}P(`idle`),I(null),setTimeout(()=>{s.console.log(`[onramp] Opening Mesh Connect with token:`,y);try{j.openLink(y),H(),R.current=window.setTimeout(()=>{se(`Mesh Connect did not finish loading. Please try again.`)},8e3),s.console.log(`[onramp] Opened in popup successfully`)}catch(e){H(),s.console.error(`[onramp] Failed to open popup link:`,e),P(`error`),I(`Failed to open Mesh Connect popup`),t?.(e)}},200)},[H,se,y,j,t]),fe=K(()=>{ae.current=!1,z.current=null,B.current=!1,O(null),b(null),S(null),A(null),P(`idle`),I(null),L(e=>e+1)},[]);return q(()=>{D&&s.console.log(`[onramp] Payload updated:`,D)},[D]),q(()=>{if(k)if(s.console.log(`[onramp] Transfer finished data updated:`,k),s.console.log(`[onramp] onComplete callback check:`,{hasOnComplete:!!l,onCompleteType:typeof l}),l)try{s.console.log(`[onramp] Calling onComplete with transfer data`),l(k),s.console.log(`[onramp] onComplete called successfully`)}catch(e){s.console.error(`[onramp] Error calling onComplete:`,e)}else s.console.warn(`[onramp] onComplete callback is not defined - cannot redirect`)},[k,l]),q(()=>()=>{H()},[H]),q(()=>()=>{let e=j?.closeLink;e&&Promise.resolve(e()).catch(e=>{s.console.warn(`[onramp] Failed to close Mesh popup on unmount:`,e)})},[j]),q(()=>{j&&y&&!D&&N===`idle`&&(s.console.log(`[onramp] Auto-clicking openMeshConnect button`),de())},[j,y,D,de,N]),C?Q(`div`,{className:`flex flex-col h-full`,children:[Z(bv,{onBack:e,title:`Mesh Connect`}),Z(`div`,{className:`flex-1 flex items-center justify-center`,children:Q(`div`,{className:`text-center`,children:[Z(`div`,{className:`mt-4 w-8 h-8 border-solid border-2 border-blue-500 border-t-transparent rounded-full animate-spin mx-auto mb-4`}),Z(`p`,{className:`text-gray-600 dark:text-gray-400`,children:`Generating secure connection...`})]})})]}):T?Q(`div`,{className:`flex flex-col h-full`,children:[Z(bv,{onBack:e,title:`Mesh Connect`}),Z(`div`,{className:`flex-1 flex items-center justify-center`,children:Q(`div`,{className:`text-center p-4 border border-solid border-red-200 rounded-lg bg-red-50 dark:bg-red-900/20 dark:border-red-800`,children:[Z(`p`,{className:`text-red-600 dark:text-red-200 mb-4`,children:T}),Z(`button`,{type:`button`,onClick:()=>{typeof window<`u`&&window.location.reload()},className:`px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors`,children:`Try Again`})]})})]}):Q(`div`,{className:`flex flex-col h-full`,children:[Z(bv,{onBack:e,title:`Fund with ${d||`Mesh Connect`}`}),k&&Q(`div`,{className:`mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 border border-solid border-blue-200 dark:border-blue-800 rounded-lg`,children:[Q(`p`,{className:`text-sm text-blue-600 dark:text-blue-200`,children:[`✓ Transfer completed: `,k.amount,` `,k.symbol]}),Z(`p`,{className:`text-xs text-blue-500 dark:text-blue-300 mt-1`,children:`Redirecting to pending screen...`})]}),Z(`div`,{className:`mb-4 flex items-center justify-center py-2`,children:Z(`div`,{className:`w-full max-w-md rounded-lg border border-solid border-gray-200 p-8 text-center dark:border-gray-700`,children:Q(`div`,{className:`space-y-6`,children:[Q(`div`,{className:`space-y-3`,children:[Z(`h3`,{className:`text-lg font-semibold`,children:n?`Connect ${d||`exchange`} account`:`Fund your account with ${d||`Mesh Connect`}`}),Q(`p`,{className:`text-gray-600 dark:text-gray-400`,children:[n&&`Sign in to ${d?.toLowerCase()||`your exchange`} to link your account.`,!n&&a&&i&&`Review and confirm sending ${a} ${i} from ${d?.toLowerCase()||`your exchange`} to your wallet.`,!n&&(!a||!i)&&`Review and confirm the transfer from ${d?.toLowerCase()||`your exchange`} to your wallet.`]})]}),N!==`idle`&&F&&Q(`div`,{className:`rounded-lg border border-solid border-yellow-200 bg-yellow-50 px-4 py-3 text-left dark:border-yellow-800 dark:bg-yellow-900/20`,children:[Z(`p`,{className:`text-sm font-medium text-yellow-900 dark:text-yellow-100`,children:N===`closed`?`Funding window closed`:`Mesh Connect error`}),Z(`p`,{className:`mt-2 text-sm text-yellow-700 dark:text-yellow-300`,children:F})]}),!n&&Q(`div`,{className:`rounded-lg border border-solid border-gray-200 bg-gray-50 px-4 py-3 dark:border-gray-700 dark:bg-gray-800/70`,children:[Q(`p`,{className:`text-sm font-medium text-gray-900 dark:text-gray-100`,children:[`Funding session expires in`,` `,ry(ne)]}),Z(`p`,{className:`mt-2 text-xs text-gray-500 dark:text-gray-400`,children:`Retry before expiry to keep the current funding session.`})]}),N!==`idle`&&Z(`button`,{type:`button`,onClick:fe,disabled:C,className:`w-full px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed`,children:C?`Preparing...`:!n&&ne<=0?`Refresh Session`:`Retry`})]})})}),p===`sandbox`&&Z(`div`,{className:`mt-4 p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-solid border-yellow-200 dark:border-yellow-800`,children:Q(`div`,{className:`text-center`,children:[Z(`p`,{className:`text-sm font-medium text-yellow-800 dark:text-yellow-200`,children:`Sandbox environment`}),Z(`p`,{className:`text-xs text-yellow-600 dark:text-yellow-300`,children:`No real funds are used`})]})})]})},oy=({onBack:e,onComplete:t,onError:n,authOnly:r,accessTokens:i,toTokenSymbol:a,toTokenAmount:o,toChainId:s,toRecipientAddress:c,toAmountUsd:l,selectedExchange:u})=>{let[d,f]=X(u||null),[p,m]=X(u?.integrationId||``),[h,g]=X(u?.exchangeName||``);return q(()=>{u?(f(u),m(u.integrationId),g(u.exchangeName)):(f(null),m(``),g(``))},[u]),d?Z(ay,{onBack:()=>{e&&e()},onComplete:t,onError:n,authOnly:r,accessTokens:i,toTokenSymbol:a,toTokenAmount:o,toChainId:s,toRecipientAddress:c,integrationId:p,exchangeName:h}):Q(`div`,{className:`flex flex-col h-full`,children:[Z(bv,{onBack:e,title:`Send From Exchange`}),Z(`div`,{className:`flex flex-1 items-center justify-center`,children:Z(`div`,{className:`rounded-lg border border-solid border-gray-200 bg-gray-50 p-4 text-sm text-gray-600 dark:border-gray-700 dark:bg-gray-800/70 dark:text-gray-300`,children:`No exchange selected.`})})]})};function sy(e){if(e)return e.mesh?{...e,mesh:{environment:`production`,...e.mesh},bluvo:e.bluvo?{environment:`production`,...e.bluvo}:e.bluvo}:e}function cy(e){return sy(e?.trailsOnrampConfig)}function ly(e){let t=sy(e.config),n=e=>{let{setCurrentScreen:n,onComplete:r,onError:i,onBack:a,authOnly:o,accessTokens:c,toTokenSymbol:l,toTokenAmount:u,toChainId:d,toRecipientAddress:f,toAmountUsd:p,selectedExchange:m,apiKey:h,hostname:g}=e,_=()=>{a?a():n(`home`)},v=e=>{if(s.console.log(`[onramp] handleComplete called:`,{hasOnComplete:!!r,transferData:e}),r)try{s.console.log(`[onramp] Calling onComplete from widget handlers`),r(e),s.console.log(`[onramp] onComplete called successfully`)}catch(e){s.console.error(`[onramp] Error in onComplete:`,e)}else s.console.warn(`[onramp] onComplete handler not provided by widget`)};return Z(dv,{config:{...t,apiKey:h||t?.apiKey,hostname:g||t?.hostname},children:Z(oy,{onBack:_,onComplete:v,onError:i,authOnly:o,accessTokens:c,toTokenSymbol:l,toTokenAmount:u,toChainId:d,toRecipientAddress:f,toAmountUsd:p,selectedExchange:m})})};return n.trailsOnrampConfig=t,n}function uy(e){return sy(e?typeof e==`function`?e?.trailsOnrampConfig:e:{mesh:{}})}function dy({searchQuery:e,filteredTokensFormatted:t,filterByChainId:n,allowedTokens:r,allowedTokenKeys:i,allowedTokenRestrictedChainIds:a,allowedChainIds:o,isApiAddressSearchComplete:c,balanceOnly:l=!1}){let{data:u=[]}=Hx(),{addCustomToken:d,customTokens:f}=rs(),p=Vx(),{data:m=[],isSuccess:h}=Or(Pc.supportedList(p)),g=bn(e.trim())?e.trim():null,_=J(()=>g?f.some(e=>{let t=Pe(e.contractAddress,g);return n===null?t:t&&e.chainId===n})?!0:n===null?t.some(e=>Pe(e.contractAddress,g)):t.some(e=>e.chainId===n&&Pe(e.contractAddress,g)):!1,[g,t,n,f]),v=J(()=>new Set(u.map(e=>e.id).filter(e=>!o||o.includes(e))),[o,u]),y=J(()=>o?new Set(o):null,[o]),{data:b=[],isLoading:x,error:S}=Or({queryKey:[`customTokenAllChains`,g?.toLowerCase(),r?.map(G)?.join(`|`),i?.join(`|`),a?.join(`|`),o?.join(`|`)],queryFn:async()=>{if(!g)return[];s.console.log(`[trails-sdk] Searching for token ${g} across all chains`);let e=(await Cc(g,{sequenceMetadataUrl:p.sequenceMetadataUrl,trailsApiKey:p.trailsApiKey})).filter(e=>e.chainId!=null&&v.has(e.chainId)&&(!r&&!i?!0:Xc(e,r,i,a)));return s.console.log(`[trails-sdk] Found ${e.length} tokens across all chains`),e},enabled:!!g&&!_&&u.length>0&&c,staleTime:5*ge,gcTime:Te,retry:1,refetchOnWindowFocus:!1});q(()=>{b.length>0&&!S&&h&&b.forEach(e=>{let t=m.some(t=>t.chainId===e.chainId&&Pe(t.contractAddress,e.contractAddress)),n=f.some(t=>t.chainId===e.chainId&&Pe(t.contractAddress,e.contractAddress));!t&&!n&&(d(e),s.console.log(`[trails-sdk] Added custom token to storage:`,e))})},[b,S,d,m,h,f]),q(()=>{S&&g&&!_&&s.console.error(`[trails-sdk] Failed to fetch custom token:`,S)},[S,g,_]);let C=J(()=>{let e=new Map;for(let n of t){let t=G(n);e.set(t,n)}return e},[t]),w=J(()=>{let t=g?.toLowerCase(),o=e.trim().toLowerCase();return Zc(f,r,i,a).filter(e=>{if(y&&(e.chainId==null||!y.has(e.chainId)))return!1;if(t){if(e.contractAddress.toLowerCase()!==t)return!1}else if(o){let t=(e.symbol||``).toLowerCase(),n=(e.name||``).toLowerCase();if(!t.includes(o)&&!n.includes(o))return!1}return n===null?!0:e.chainId===n}).map(e=>{let t=G(e),n=C.get(t),r=$(e.chainId||0)?.name||`Chain ${e.chainId||0}`;return n?{...n,chainName:r,isCustomToken:e.isCustomToken??!0}:{...e,chainName:r,isSufficientBalance:!0,isCustomToken:e.isCustomToken??!0}})},[f,n,C,g,e,r,i,a,y]),T=K(e=>Cs(e.balance||`0`),[]),E=J(()=>{let e=new Set;for(let t of m)e.add(G(t));return e},[m]);return{chainFilteredTokens:J(()=>{let e=t;n!==null&&(e=e.filter(e=>(e.chainId||0)===n)),l&&(e=e.filter(e=>W(e.chainId||0)||T(e)));let o=new Set(e.map(G)),s=[],c=[];return w.forEach(e=>{let t=G(e);o.has(t)||(T(e)?s.push(e):l||c.push(e),o.add(t))}),l||Zc(b,r,i,a).forEach(e=>{if((n===null||e.chainId===n)&&(!y||e.chainId!=null&&y.has(e.chainId))){let t=G(e);if(!o.has(t)){let n=$(e.chainId)?.name||`Chain ${e.chainId}`,r={...e,chainName:n,isCustomToken:!0,isSufficientBalance:!0};c.push(r),o.add(t)}}}),[...e,...s,...c].map(e=>{let t=G(e);return E.has(t)&&e.isCustomToken?{...e,isCustomToken:!1}:e})},[t,n,b,w,T,E,r,i,a,y,l]),foundTokensAllChains:b,isLoadingCustomToken:x,customTokenError:S,isCustomToken:K((e,t)=>f.some(n=>n.isCustomToken===!0&&(n.chainId||0)===e&&Pe(n.contractAddress,t)),[f])}}function fy(e,t=300){let[n,r]=X(e);return q(()=>{let n=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(n)}},[e,t]),n}function py(e){return String(e||``).trim().toUpperCase()}function my(e){return String(e||``).trim().toUpperCase().replaceAll(/\s+/g,` `)}function hy(e,t){if(py(e.symbol)!==py(t.asset))return!1;let n=t.networks??[];if(!n.length)return!1;let r=Number(e.chainId||0),i=my($(r)?.name);return n.some(e=>{if(e.chainId&&r>0&&e.chainId===r)return!0;let t=my(e.name),n=my(e.displayName);return!!i&&(t===i||n===i)})}function gy({selectedBluvoBalances:e,shouldFilterBluvoTokens:t}){let n=J(()=>t?new Map(e.map(e=>[py(e.asset),e])):new Map,[e,t]),r=J(()=>e=>{if(!t)return;let r=n.get(py(e.symbol));if(!r)return;let i=Number(r.amount||0);if(!(!Number.isFinite(i)||i<=0))return hy(e,r)?r:void 0},[n,t]);return{applyBluvoBalanceToToken:J(()=>e=>{if(!t)return e;let n=r(e);if(!n)return e;let i=Number(n.amount||0),a=Number(n.amountInFiat||0),o=Number.isFinite(i)?i:0,s=Number.isFinite(a)?a:0,c=Ks(s);return{...e,balanceFormatted:o.toString(),balanceDisplay:o.toString(),balanceLocaleDisplay:o.toString(),balanceUsd:s,balanceUsdFormatted:c,balanceUsdDisplay:c,balanceUsdLocaleDisplay:qs(s),isSufficientBalance:!0}},[r,t]),bluvoTotalBalanceUsd:J(()=>t?e.reduce((e,t)=>{let n=Number(t.amountInFiat||0);return e+(Number.isFinite(n)?n:0)},0):0,[e,t]),getBluvoBalance:r}}function _y({apiTokens:e,localTokens:t,filterByChainId:n,applyMeshBalanceToToken:r,applyBluvoBalanceToToken:i,shouldFilterMeshTokens:a,shouldFilterBluvoTokens:o,isSupportedMeshToken:s,getBluvoBalance:c,applyTerminalFilters:l=!1}){let u=new Map;for(let e of t){let t=e.contractAddress||Cn,n=Ke(e.chainId||0,t);u.set(n,e)}let d=e.map(e=>{let t=e.contractAddress||Cn,n=Ke(e.chainId||0,t),r=u.get(n);return r&&(r.balanceUsd||0)>0?r:e}),f=new Set(d.map(e=>Ke(e.chainId||0,e.contractAddress||Cn)));for(let e of t){let t=Ke(e.chainId||0,e.contractAddress||Cn);!f.has(t)&&(e.chainId||0)===n&&d.push(a?r(e):o?i(e):e)}let p=d.map(e=>a?r(e):o?i(e):e);return l?a?p.filter(e=>s(e.chainId,e.symbol)):o?p.filter(e=>!!c(e)):p:p}const vy=[`ETH`,`POL`,`USDC`,`USDT`,`DAI`,`BAT`,`WETH`],yy=new Map;function by(e,t){return t?e.filter(e=>e.chainId!=null&&t.has(e.chainId)):[...e]}function xy(e,t,n,r,i){let a=e.filter(e=>xs(e.decimals)?!0:(s.console.warn(`[trails-sdk] Skipping token with invalid decimals:`,{symbol:e.symbol,address:e.address,decimals:e.decimals}),!1)).map(e=>oc(e));return t?a.filter(e=>r(e.chainId,e.symbol)):n?a.filter(e=>!!i(e)):a}function Sy(e,t,n,r){let i=0;for(let a of r)e===a&&(i+=100),e.startsWith(a)&&(i+=50),e.includes(a)&&(i+=25),t===a&&(i+=20),t.startsWith(a)&&(i+=15),t.includes(a)&&(i+=10),n===a&&(i+=5),n.includes(a)&&(i+=2);return i}function Cy({onContinue:e,targetAmountUsd:t,onError:n,accountAddress:r,fundMethod:i,allSupportedTokens:a=!1,allowedTokens:o,allowedTokenKeys:c,allowedTokenRestrictedChainIds:l,allowedChainIds:u,solanaAccountAddress:d,chainFilterChainId:f,catalogSupplementTokens:p,includePrice:m=!1,balanceRefetchInterval:h=J_}){let[g,_]=X(null),[v,y]=X(``),b=gs(),x=!!i&&i!==`wallet`,S=(!i||i===`wallet`)&&!a,C=x?null:r??null,{sortedTokens:w,isLoadingSortedTokens:T,balanceError:E,refetch:D}=Q_(C,void 0,{disabled:x,refetchInterval:x?!1:h,includeAllChains:!0}),{tokens:O,isLoading:k}=q_(d,{disabled:x||!d}),A=J(()=>O.length===0?w:[...w,...O],[w,O]),j=i&&i!==`wallet`||a,{supportedTokens:M,isLoadingTokens:N,refetch:P}=Rc({disabled:!j}),F=Vx(),{onramp:I}=wo(),{selectedMeshExchange:ee,selectedMeshAccessTokens:te,selectedBluvoWalletId:ne,selectedBluvoBalances:re}=Vu(),ie=gv(),L=uy(I),R=yv(L),ae=!!L?.mesh,z=L?.mesh?.exchanges??null,B=ee?[ee.integrationId]:null,V=ee?null:z,{data:oe=[]}=Hx(),{selectedChainId:H}=mu(),se=f===void 0?H:f,ce=J(()=>u?new Set(u):null,[u]),U=i&&i!==`wallet`||a,le=i===`onramp-mesh`,ue=i===`onramp-bluvo`,de=le&&!a,fe=ue&&!a,pe=de&&ae&&!!F.trailsApiKey&&!!F.trailsApiUrl,me=J(()=>oe.map(e=>e.id).filter(e=>!ce||ce.has(e)),[ce,oe]),he=J(()=>v.trim(),[v]),ge=fy(he,300),_e=J(()=>ge?bn(ge):!1,[ge]),ve=he!==ge,{data:ye,isLoading:be,refetch:xe}=Or({...Pc.search(b,F.trailsApiKey,{searchQuery:ge,chainIds:se===null?me:[se],limit:30}),enabled:ge.length>0&&!!b&&!!F.trailsApiKey}),{data:Se,isLoading:Ce,refetch:we}=Or({...Pc.byChain(b,F.trailsApiKey,{chainId:se,limit:100}),enabled:U&&se!==null&&(!ce||ce.has(se))&&!!b&&!!F.trailsApiKey}),{data:Ee,isLoading:De,refetch:Oe}=Or({queryKey:[`mesh-supported-tokens`,R,ee?.integrationId,V,te,F.trailsApiUrl,F.trailsApiKey],queryFn:async()=>{let e=await ie.getMeshSupportedTokens({environment:R,integrationId:ee?.integrationId,accessTokens:te.length>0?te:void 0}),t=te.length>0;if(B?.length){let n=(e.tokens||[]).filter(e=>(e.integrationIds||[]).some(e=>B.includes(e)));return t?{...e,tokens:n.filter(e=>Number(e.balance||`0`)>0)}:{...e,tokens:n}}if(!V?.length)return t?{...e,tokens:(e.tokens||[]).filter(e=>Number(e.balance||`0`)>0)}:e;let n=(e.tokens||[]).filter(e=>(e.exchangeKeys||[]).some(e=>V.includes(e)));return t?{...e,tokens:n.filter(e=>Number(e.balance||`0`)>0)}:{...e,tokens:n}},enabled:pe,staleTime:Te,gcTime:Te,refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),ke=J(()=>de&&Ee?.tokens||[],[Ee,de]),Ae=J(()=>{if(!de)return 0;let e=Number(Ee?.totalBalanceUsd||`0`);return Number.isFinite(e)?e:0},[Ee,de]),je=J(()=>de?(e,t)=>vv(ke,e,t):(e,t)=>!1,[ke,de]),Me=J(()=>{if(!de)return yy;let e=new Map;for(let t of ke){let n=Number(t.chainId),r=String(t.symbol||``).toUpperCase();if(!r)continue;let i=t.balance||`0`,a=Number(t.balanceUsd||`0`),o=Number.isFinite(a)?a:0;Number.isFinite(n)&&n>0&&e.set(`${n}:${r}`,{balance:i,balanceUsd:o})}return e},[ke,de]),Ne=J(()=>(e,t)=>{let n=String(t||``).toUpperCase();if(n)return e&&Number.isFinite(Number(e))?Me.get(`${Number(e)}:${n}`):void 0},[Me]),Fe=J(()=>e=>{if(!de)return e;let t=Ne(e.chainId,e.symbol);if(!t)return e;let n=Ks(t.balanceUsd);return{...e,balanceFormatted:t.balance,balanceDisplay:t.balance,balanceLocaleDisplay:t.balance,balanceUsd:t.balanceUsd,balanceUsdFormatted:n,balanceUsdDisplay:n,balanceUsdLocaleDisplay:qs(t.balanceUsd)}},[Ne,de]),{applyBluvoBalanceToToken:Ie,bluvoTotalBalanceUsd:Le,getBluvoBalance:Re}=gy({selectedBluvoBalances:re,shouldFilterBluvoTokens:fe}),ze=J(()=>i===`direct-transfer`||i===`onramp-mesh`||i===`onramp-bluvo`||i===`onramp-meld`?M?.length?M.filter(e=>{let t=e.symbol.toUpperCase();return de?je(e.chainId,e.symbol):fe?!!Re(e):vy.includes(t)}).map(e=>({chainId:e.chainId,tokenAddress:e.contractAddress||Cn,tokenSymbol:e.symbol})):[]:!a||!M?.length?[]:M.map(e=>({chainId:e.chainId,tokenAddress:e.contractAddress||Cn,tokenSymbol:e.symbol})),[a,M,i,je,de,fe,Re]),{tokenPrices:Be,isLoadingTokenPrices:Ve,refetch:He}=ov(ze,!m),Ue=i&&i!==`wallet`?N||Ve||De||be||Ce:a?T||N||Ve||Ce:T||k,{data:We=0,isLoading:Ge}=rv(C),qe=i===`onramp-mesh`?Ae:i===`onramp-bluvo`?Le:We,Je=i===`onramp-mesh`?De:i===`onramp-bluvo`?!ne&&fe:Ge,Ye=Ks(qe),Xe=K(async()=>{let e=[];!x&&C&&e.push(D()),j&&e.push(P()),U&&ge.length>0&&b&&F.trailsApiKey&&e.push(xe()),U&&se!==null&&(!ce||ce.has(se))&&b&&F.trailsApiKey&&e.push(we()),pe&&e.push(Oe()),m&&ze.length>0&&e.push(He()),await Promise.allSettled(e)},[ce,C,ge.length,se,m,j,we,Oe,xe,He,P,D,pe,x,U,ze.length,b,F.trailsApiKey]),{data:Ze=!1,isLoading:Qe,error:$e}=nv({account:C,targetAmountUsd:x?null:t}),et=J(()=>{let e=Se?.tokens??[];return!U||e.length===0||se===null?[]:xy(e,de,fe,je,Re)},[Se,U,se,de,fe,Re,je]),tt=J(()=>{if(i&&i!==`wallet`){if(U&&se!==null&&et.length>0)return _y({apiTokens:et,localTokens:A,filterByChainId:se,applyMeshBalanceToToken:Fe,applyBluvoBalanceToToken:Ie,shouldFilterMeshTokens:de,shouldFilterBluvoTokens:fe,isSupportedMeshToken:je,getBluvoBalance:Re,applyTerminalFilters:!0});let e=M.filter(e=>{let t=e.symbol.toUpperCase();return de?je(e.chainId,e.symbol):fe?!!Re(e):vy.includes(t)}).map(e=>{let t=Be?.find(t=>t.token.tokenAddress?.toLowerCase()===(e.contractAddress||Cn).toLowerCase()&&Number(t.token.chainId)===Number(e.chainId))?.priceUsd,n=t?ec(t):void 0,r={...e,...n&&{priceUsd:n.priceUsd,priceUsdFormatted:n.priceUsdFormatted,priceUsdDisplay:n.priceUsdDisplay},isSufficientBalance:!0};return de?Fe(r):fe?Ie(r):r}).sort((e,t)=>(t.priceUsd||0)-(e.priceUsd||0));return de?e.filter(e=>je(e.chainId,e.symbol)):fe?e.filter(e=>!!Re(e)):e}return a&&U&&se!==null&&et.length>0?_y({apiTokens:et,localTokens:A,filterByChainId:se,applyMeshBalanceToToken:Fe,applyBluvoBalanceToToken:Ie,shouldFilterMeshTokens:de,shouldFilterBluvoTokens:fe,isSupportedMeshToken:je,getBluvoBalance:Re}):A.map(Fe)},[A,Fe,Ie,i,a,M,Be,je,de,fe,Re,U,se,et]);q(()=>{n&&E&&n(E)},[E,n]);let nt=r=>{let i=r.isNativeToken??!1;if(!r.decimals){s.console.warn(`[trails-sdk] [useTokenList] Missing decimals for token:`,{token:r,chainId:r.chainId,isNative:i}),n(`Decimals not found [useTokenList]`);return}S&&W(r.chainId||0)&&!ws(r)||(_(r),(!t||t&&Ze)&&(r.isSufficientBalance??!0)||s.console.warn(`[trails-sdk] Cannot continue with token selection`,{token:r,targetAmountUsd:t,hasSufficientBalanceUsd:Ze,isSufficientBalance:r.isSufficientBalance}),e(r))},rt=e=>{if(!g)return!1;let t=e.isNativeToken??!1,n=g.isNativeToken??!1;return(g.chainId||0)===(e.chainId||0)&&(t?n:Pe(g.contractAddress,e.contractAddress))},it=J(()=>{let e=ye?.tokens??[];return e.length===0?[]:xy(e,de,fe,je,Re)},[ye,de,fe,Re,je]),at=J(()=>{if(he&&it.length>0){let e=new Map;for(let t of tt){let n=t.contractAddress||Cn,r=Ke(t.chainId||0,n);e.set(r,t)}let t=it.map(t=>{let n=t.contractAddress||Cn,r=Ke(t.chainId||0,n);return e.get(r)??t}),n=new Set(t.map(e=>{let t=e.contractAddress||Cn;return Ke(e.chainId||0,t)})),r=he.toLowerCase();for(let e of tt){let i=e.contractAddress||Cn,a=Ke(e.chainId||0,i);if(!n.has(a)){let n=(e.symbol||``).toLowerCase(),a=(e.name||``).toLowerCase(),o=($(e.chainId||0)?.name||``).toLowerCase();(n.includes(r)||a.includes(r)||o.includes(r)||St(i).includes(r))&&t.push(e)}}return t}if(!he)return tt;let e=he.toLowerCase().split(/\s+/).filter(e=>e.length>0);return tt.filter(t=>{let n=($(t.chainId||0)?.name||``).toLowerCase(),r=(t.symbol||`???`).toLowerCase(),i=(t.name||`Unknown Token`).toLowerCase(),a=(t.contractAddress||Cn).toLowerCase();if(e.length>1){let t=e.some(e=>n.includes(e)),o=e.some(e=>r.includes(e)||i.includes(e)||a.includes(e));return t&&o}return e.some(e=>r.includes(e)||i.includes(e)||n.includes(e)||a.includes(e))}).sort((t,n)=>{let r=$(t.chainId||0),i=$(n.chainId||0),a=r?.name?.toLowerCase()||``,o=i?.name?.toLowerCase()||``,s=(t.symbol||`???`).toLowerCase(),c=(n.symbol||`???`).toLowerCase(),l=(t.name||`Unknown Token`).toLowerCase(),u=(n.name||`Unknown Token`).toLowerCase(),d=Sy(s,l,a,e);return Sy(c,u,o,e)-d})},[it,tt,he]),ot=J(()=>by(at,ce),[ce,at]),st=J(()=>Zc(ot,o,c,l),[ot,o,c,l]),ct=J(()=>{let e=st.map(e=>{let n=e.isNativeToken??!1,r=$(e.chainId||0);if(!e.decimals)return s.console.warn(`[trails-sdk] Missing decimals for token, skipping:`,{token:e,chainId:e.chainId,isNative:n}),null;let i=e.isSufficientBalance??!0;S&&W(e.chainId||0)&&!ws(e)&&(i=!1),t&&(i=(e.balanceUsd??0)>=t);let a=e.chainName||r?.name||``,o=e.priceUsdFormatted?void 0:e.priceUsd?ec(e.priceUsd):void 0;return{...e,balanceDisplay:e.balanceDisplay||e.balanceFormatted,priceUsdFormatted:e.priceUsdFormatted||o?.priceUsdFormatted,priceUsdDisplay:e.priceUsdDisplay||o?.priceUsdDisplay,balanceUsdDisplay:e.balanceUsdDisplay||e.balanceUsdFormatted,isSufficientBalance:i,chainName:a}}).filter(Boolean);if(a){let t=new Set(e.map(G)),n=Zc(by(M,ce),o,c,l).filter(e=>de&&!je(e.chainId,e.symbol)?!1:!t.has(G(e))).map(e=>{let t=$(e.chainId||0)?.name||`Chain ${e.chainId||0}`,n=Be?.find(t=>t.token.tokenAddress?.toLowerCase()===(e.contractAddress||Cn).toLowerCase()&&Number(t.token.chainId)===Number(e.chainId)),r=n?.priceUsd?ec(n.priceUsd):void 0;return{symbol:e.symbol,name:e.name,decimals:e.decimals,contractAddress:e.contractAddress,chainId:e.chainId,chainName:t,imageUrl:e.imageUrl||``,...r&&{priceUsd:r.priceUsd,priceUsdFormatted:r.priceUsdFormatted,priceUsdDisplay:r.priceUsdDisplay},isSufficientBalance:!0}}).sort((e,t)=>(t.priceUsd||0)-(e.priceUsd||0)),r=(p??[]).filter(e=>!t.has(G(e))).map(e=>{let t=$(e.chainId||0);return{...e,chainName:e.chainName||t?.name||`Chain ${e.chainId||0}`,isSufficientBalance:!0}});for(let e of r)t.add(G(e));let i=[...e,...n,...Zc(by(r,ce),o,c,l)];if(v.trim()){let e=v.toLowerCase().trim().split(/\s+/).filter(e=>e.length>0);return i.filter(t=>{let n=t.chainName?.toLowerCase()||``,r=t.symbol?.toLowerCase()||``,i=t.name?.toLowerCase()||``,a=t.contractAddress?.toLowerCase()||``;if(e.length>1){let t=e.some(e=>n.includes(e)),o=e.some(e=>r.includes(e)||i.includes(e)||a.includes(e));return t&&o}return e.some(e=>r.includes(e)||i.includes(e)||n.includes(e)||a.includes(e))}).sort((t,n)=>{let r=t.chainName?.toLowerCase()||``,i=t.symbol?.toLowerCase()||``,a=t.name?.toLowerCase()||``,o=n.chainName?.toLowerCase()||``,s=n.symbol?.toLowerCase()||``,c=n.name?.toLowerCase()||``,l=Sy(i,a,r,e),u=Sy(s,c,o,e);if(l===u){let e=t.balance&&t.balance!==``,r=n.balance&&n.balance!==``;if(e&&!r)return-1;if(!e&&r)return 1}return u-l})}return Zc(by(i,ce),o,c,l)}return fe?e.filter(e=>!!Re(e)):e},[st,t,S,a,M,Be,v,de,fe,Re,je,o,c,l,ce,p]),lt=J(()=>qe&&t&&!Ze&&!Qe&&!$e||ct?.length>0&&!ct.some(e=>e.isSufficientBalance),[t,Ze,Qe,$e,ct,qe]),ut=ve||be,{chainFilteredTokens:dt,foundTokensAllChains:ft,isLoadingCustomToken:pt,customTokenError:mt}=dy({searchQuery:v,filteredTokensFormatted:ct,filterByChainId:se,isApiAddressSearchComplete:_e&&!be&&!ve&&(ye?.tokens?.length??0)===0,allowedTokens:o,allowedTokenKeys:c,allowedTokenRestrictedChainIds:l,allowedChainIds:u,balanceOnly:S});return{selectedToken:g,searchQuery:v,handleTokenSelect:nt,filteredTokens:st,chainFilteredTokens:dt,foundTokensAllChains:ft,isLoadingSortedTokens:T||be,isLoadingSearchTokens:be,isLoadingCustomToken:pt,isSearching:ut,customTokenError:mt,balanceError:E,showContinueButton:!1,isTokenSelected:rt,setSearchQuery:y,filteredTokensFormatted:ct,totalBalanceUsd:qe,totalBalanceUsdFormatted:Ye,isLoadingTotalBalanceUsd:Je,showInsufficientBalance:lt,isLoadingTokens:Ue,refreshTokens:Xe}}function wy(){let{selectedFundMethod:e,setSelectedFundMethod:t,selectedMeshExchange:n,setSelectedMeshExchange:r,selectedMeshAccessTokens:i,setSelectedMeshAccessTokens:a}=Vu();return{selectedFundMethod:e,setSelectedFundMethod:t,selectedMeshExchange:n,setSelectedMeshExchange:r,selectedMeshAccessTokens:i,replaceSelectedMeshAccessTokens:K(e=>{a(e)},[a]),clearSelectedMeshAccessTokens:K(()=>{a([])},[a])}}const Ty=({chainId:e,size:t=24})=>{let n=e?$(e):null,r=n?.imageUrl||(e?Ba(e):``),i=n?.name||(e?`Chain ${e}`:``),a=e?`${i} (Chain ID: ${e})`:``;return e?Z(`div`,{className:`rounded-full flex items-center justify-center text-sm relative bg-black-100 bg-opacity-90 overflow-hidden`,style:{width:t,height:t},title:a,children:Z(`div`,{className:`flex items-center justify-center overflow-hidden shrink-0 rounded-full absolute w-full h-full text-white bg-white dark:bg-black-100`,children:Z(`img`,{className:`max-w-full max-h-full object-cover w-full`,src:r,alt:a})})}):null};function Ey(e,t){if(e<=1)return{iconSize:t,positions:[{left:0,top:0}]};if(e===2){let e=Math.max(t*.68,12),n=(t-e)/2;return{iconSize:e,positions:[{left:0,top:n},{left:t-e,top:n}]}}if(e===3){let e=Math.max(t*.56,10);return{iconSize:e,positions:[{left:(t-e)/2,top:0},{left:0,top:t-e},{left:t-e,top:t-e}]}}let n=Math.max(t/2-1,8);return{iconSize:n,positions:[{left:0,top:0},{left:t-n,top:0},{left:0,top:t-n},{left:t-n,top:t-n}]}}const Dy=({size:e=20,className:t=``,chainIds:n})=>{let r=(n&&n.length>0?n:[1,8453,42161,137]).slice(0,4),{iconSize:i,positions:a}=Ey(r.length,e);return Z(`div`,{className:`relative ${t}`,style:{width:e,height:e},children:r.map((e,t)=>Z(`div`,{className:`absolute flex items-center justify-center rounded-full bg-white dark:bg-gray-900`,style:{width:i,height:i,left:a[t]?.left??0,top:a[t]?.top??0,zIndex:t+1},children:Z(Ty,{chainId:e,size:i})},e))})},Oy=({chains:e,selectedChainId:t,onChainSelect:n,className:r=``,buttonClassName:i=``,dropdownClassName:a=``,compactMode:o=!1,nestedMode:s=!1,chainListScreen:c=!1,onNavigateToChainList:l})=>{let u=Y(null),d=Y(null),[f,p]=X(!1),[m,h]=X(``),g=J(()=>{if(!m.trim())return e;let t=m.trim().toLowerCase();return e.filter(e=>e.name.toLowerCase().includes(t)||e.chainId.toString().includes(t))},[e,m]);q(()=>{f&&d.current&&setTimeout(()=>{d.current?.focus()},100)},[f]),q(()=>{let e=e=>{u.current&&!u.current.contains(e.target)&&(p(!1),h(``))};return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[]);let _=e=>{n(e),p(!1),h(``)},v=()=>{c&&l?l():p(!f)},y=J(()=>{if(t===null)return null;let n=e.find(e=>e.chainId===t);if(n)return n;let r=$(t);return r?{chainId:r.id,name:r.name,imageUrl:r.imageUrl}:null},[e,t]),b=e.length===1,x=b?e[0]:null,S=y??x;return Q(`div`,{className:`relative ${r}`,ref:u,children:[Q(`button`,{type:`button`,disabled:b,onMouseDown:e=>{b||(e.preventDefault(),e.stopPropagation(),v())},className:`h-full px-3 flex items-center gap-2 transition-colors ${b?`cursor-default opacity-100`:`cursor-pointer`} ${i}`,title:b?`${S?.name??`Chain`} (only chain available)`:`Select a chain`,children:[S?Z(Ty,{chainId:S.chainId,size:20}):Z(Dy,{size:20,chainIds:e.map(e=>e.chainId)}),!b&&Z(Di,{className:`h-5 w-5 text-gray-400 transition-all duration-200 ${f?`rotate-180`:``}`})]}),!c&&f&&Q(`div`,{className:`absolute right-0 top-full mt-1 min-w-[280px] trails-bg-secondary trails-border trails-border-radius-list token-list-border shadow-lg z-50 ${s?`max-h-80`:o?`max-h-48`:`max-h-[400px]`} ${a}`,children:[Z(`div`,{className:`p-2 border-b border-gray-200 dark:border-gray-700`,children:Z(`input`,{ref:d,type:`text`,value:m,onChange:e=>h(e.target.value),placeholder:`Search chains`,className:`w-full px-3 py-2 text-sm border border-solid trails-border-radius-input focus:ring-2 focus:ring-blue-500 focus:border-blue-500 trails-input`,onMouseDown:e=>e.stopPropagation()})}),Q(`div`,{className:`p-2 ${s?`max-h-52`:o?`max-h-32`:`max-h-[320px]`} overflow-y-auto trails-scrollbar`,children:[Q(`button`,{type:`button`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),_(null)},className:`w-full flex items-center gap-3 px-3 py-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors rounded text-left ${t===null?`bg-blue-50 dark:bg-blue-900/20`:``}`,title:`Show tokens from all chains`,children:[Z(`div`,{className:`w-6 h-6 flex items-center justify-center`,children:Z(Dy,{size:24,chainIds:e.map(e=>e.chainId)})}),Z(`span`,{className:`text-sm font-medium`,children:`All Chains`})]}),g.map(e=>Q(`button`,{type:`button`,onMouseDown:t=>{t.preventDefault(),t.stopPropagation(),_(e.chainId)},className:`w-full flex items-center gap-3 px-3 py-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors rounded text-left ${t===e.chainId?`bg-blue-50 dark:bg-blue-900/20`:``}`,title:`${e.name} (Chain ID: ${e.chainId})`,children:[Z(Ty,{chainId:e.chainId,size:24}),Z(`span`,{className:`text-sm font-medium`,children:e.name})]},e.chainId)),g.length===0&&m.trim()&&Z(`div`,{className:`text-center py-4`,children:Q(`p`,{className:`text-sm text-gray-500 dark:text-gray-400`,children:[`No chains found matching "`,m,`"`]})})]})]})]})};function ky(e){switch(e){case`coinbase`:case`coinbaseRamp`:case`sandboxCoinbase`:return`bg-white`;case`binanceInternational`:case`binanceInternationalDirect`:case`binanceUs`:case`binanceUsDirect`:case`sandbox`:case`binanceConnect`:return`bg-black`;case`bitfinex`:case`bitfinexDirect`:return`bg-[#0e3452]`;case`kraken`:case`krakenDirect`:return`bg-[#5841d7]`;case`uphold`:case`upholdDirect`:return`bg-[#49cc68]`;case`paribu`:case`paribuOAuth`:return`bg-[#9cba3b]`;case`robinhood`:case`robinhoodDirect`:case`robinhoodConnect`:return`bg-[#ccff00]`;default:return`bg-gray-700`}}function Ay({exchangeKey:e,exchangeName:t,exchangeImageUrl:n,onError:r,className:i=`h-10 w-10 rounded-full border border-solid border-gray-200 dark:border-gray-700`,imageClassName:a=`h-7 w-7 object-contain`,fallbackClassName:o=`text-xs font-semibold text-white`}){let s=t||`Exchange`;return Z(`span`,{className:`flex items-center justify-center overflow-hidden ${ky(e||``)} ${i}`,children:n?Z(`img`,{src:n,alt:`${s} logo`,className:a,loading:`lazy`,referrerPolicy:`no-referrer`,onError:r}):Z(`span`,{className:o,children:s.slice(0,1).toUpperCase()})})}function jy({exchangeName:e,exchangeKey:t,exchangeImageUrl:n,connectedAccountName:r}){let i=e||`Exchange`;return Z(`div`,{className:`mb-3 rounded-xl border border-solid border-gray-200 p-3 dark:border-gray-700`,children:Q(`div`,{className:`flex items-center gap-3`,children:[Z(Ay,{exchangeKey:t,exchangeName:i,exchangeImageUrl:n,className:`h-10 w-10 rounded-full border border-solid border-gray-200 dark:border-gray-700`,imageClassName:`h-7 w-7 object-contain`}),Q(`div`,{className:`min-w-0`,children:[Z(`p`,{className:`truncate text-sm font-semibold text-gray-900 dark:text-white`,children:i}),r&&Z(`p`,{className:`truncate text-sm text-gray-500 dark:text-gray-400`,children:r})]})]})})}const My=Te;function Ny(e){try{return Pa(e)}catch{return}}function Py({textInput:e}){let t=Wx(Kn.id),n=J(()=>{if(e?.endsWith(`.eth`))return Ny(e)},[e]),{data:r,isLoading:i,isFetching:a}=Or({queryKey:[`ens`,`address`,n],enabled:!!t&&!!n,queryFn:async()=>t.getEnsAddress({name:n}),staleTime:My,gcTime:My,persister:ps.persisterFn});return{ensAddress:r,isLoading:i,isFetching:a}}function Fy({address:e}){let t=Wx(Kn.id),n=e?.startsWith(`0x`)?e:void 0,{data:r,isLoading:i}=Or({queryKey:[`ens`,`name`,n],enabled:!!t&&!!n,queryFn:async()=>t.getEnsName({address:n}),staleTime:My,gcTime:My,persister:ps.persisterFn});return{ensName:r,isLoading:i}}function Iy({address:e}){let t=Wx(Kn.id),n=e?.startsWith(`0x`)?e:void 0,{data:r,isLoading:i}=Or({queryKey:[`ens`,`name`,n],enabled:!!t&&!!n,queryFn:async()=>t.getEnsName({address:n}),staleTime:My,gcTime:My,persister:ps.persisterFn}),a=J(()=>{if(r)return Ny(r)},[r]),{data:o,isLoading:s}=Or({queryKey:[`ens`,`avatar`,a],enabled:!!t&&!!a,queryFn:async()=>t.getEnsAvatar({name:a}),staleTime:My,gcTime:My,persister:ps.persisterFn});return{ensName:r,ensAvatar:o,isLoading:i||s}}const Ly=1e3,Ry=(e,t=Ly)=>e%t/(Ly/64),zy=(e,t=0)=>{let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507)^Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)},By=(e,t)=>`gradient-avatar-${e}${t}`,Vy=(e,t,n)=>({hueA:e%360,hueB:(e+120)%360,hueC:n%360}),Hy=(e,t)=>{let n={a:zy(`${t}a`,0),b:zy(`${t}b`,1),c:zy(`${t}c`,2),x:zy(`${t}d`,3),y:zy(`${t}e`,4),r:zy(`${t}f`,5)},{hueA:r,hueB:i,hueC:a}=Vy(n.a,n.b,n.c),o=Ry(n.x),s=Ry(n.y),c=64/10+Ry(n.r,Ly*1.5);return{background:{id:By(`background`,e),stopColor0:`hsl(${a}deg 100% 50% / 1)`,stopColor1:`hsl(${r}deg 100% 50% / 1)`,cx:o,cy:s,r:c},primary:{id:By(`primary`,e),stopColor0:`hsl(${r}deg 100% 50% / 1)`,stopColor1:`hsl(${i}deg 100% 50% / 1)`,cx:o,cy:s,r:c},secondary:{id:By(`secondary`,e),stopColor0:`hsl(${a}deg 100% 50% / 1)`,stopColor1:`hsl(${i}deg 100% 50% / 1)`,cx:s,cy:o,r:c/2}}},Uy=({value:e=Cn,size:t=64,className:n=``})=>{let r=_r();if(!e||typeof e!=`string`)return Z(`div`,{className:`inline-block ${n}`,style:{width:t,height:t,backgroundColor:`#cccccc`,borderRadius:`50%`}});let i=Hy(r,e.toLowerCase()),a=e=>By(e,r);return Z(`div`,{className:`inline-block ${n}`,style:{width:t,height:t,borderRadius:`50%`,overflow:`hidden`,flexShrink:0},children:Q(`svg`,{width:t,height:t,viewBox:`0 0 64 64`,style:{display:`block`},xmlns:`http://www.w3.org/2000/svg`,"aria-label":`Identicon for ${e}`,children:[Q(`title`,{children:[`Identicon for `,e]}),Q(`defs`,{children:[Z(`clipPath`,{id:a(`circle-clip`),children:Z(`circle`,{cx:32,cy:32,r:32})}),Q(`filter`,{id:a(`blur-xs`),x:`-10%`,y:`-10%`,width:`120%`,height:`120%`,filterUnits:`userSpaceOnUse`,colorInterpolationFilters:`sRGB`,children:[Z(`feFlood`,{floodOpacity:`0`,result:`BackgroundImageFix`}),Z(`feBlend`,{mode:`normal`,in:`SourceGraphic`,in2:`BackgroundImageFix`,result:`shape`}),Z(`feGaussianBlur`,{stdDeviation:64/10,result:`effect1_foregroundBlur`})]}),Q(`linearGradient`,{id:i.background.id,x1:`0`,y1:`0`,x2:`1`,y2:`1`,children:[Z(`stop`,{offset:`0`,stopColor:i.background.stopColor0}),Z(`stop`,{offset:`1`,stopColor:i.background.stopColor1})]}),Q(`radialGradient`,{id:i.primary.id,children:[Z(`stop`,{offset:`0`,stopColor:i.primary.stopColor0}),Z(`stop`,{offset:`1`,stopColor:i.primary.stopColor1})]}),Q(`radialGradient`,{id:i.secondary.id,children:[Z(`stop`,{offset:`0`,stopColor:i.secondary.stopColor0}),Z(`stop`,{offset:`1`,stopColor:i.secondary.stopColor1})]})]}),Q(`g`,{clipPath:`url(#${a(`circle-clip`)})`,children:[Z(`rect`,{width:`100%`,height:`100%`,fill:`url(#${i.background.id})`}),Q(`g`,{filter:`url(#${a(`blur-xs`)})`,children:[Z(`circle`,{fill:`url(#${i.primary.id})`,cx:i.primary.cx,cy:i.primary.cy,r:i.primary.r}),Z(`circle`,{fill:`url(#${i.secondary.id})`,cx:i.secondary.cx,cy:i.secondary.cy,r:i.secondary.r})]})]})]})})},Wy=({walletAddress:e,size:t=16,className:n,showWalletConnectorIcon:r})=>{let{ensAvatar:i,ensName:a}=Iy({address:e}),o=Jr(),s=J(()=>o.find(t=>t.address===e),[o,e]),c=s?.icon?.trim();return i&&!r?Z(`img`,{src:i,alt:a||`Wallet`,className:`shrink-0 rounded-full object-cover ${n??``}`,style:{width:t,height:t}}):s||c?Z(Na,{walletId:s?.walletId,icon:c,label:`Wallet icon`,size:t,className:`shrink-0 ${n??``}`,decorative:!0,fallback:Z(Uy,{value:e,size:t,className:n})}):Z(Uy,{value:e,size:t,className:n})},Gy=`!bg-transparent !px-0 !py-0 text-sm text-gray-500 transition-colors hover:text-gray-700 !hover:bg-transparent dark:text-gray-400 dark:hover:text-gray-200 dark:!hover:bg-transparent`;function Ky({walletAddress:e,secondaryAddress:t,label:n=`Wallet`,walletIconUrl:r,walletId:i,onSwitchWallet:a}){let o=J(()=>wt(e),[e]),s=J(()=>wt(t),[t]);return e?Z(`div`,{className:`mb-3 rounded-xl border border-solid border-gray-200 p-3 dark:border-gray-700`,children:Q(`div`,{className:`flex items-center justify-between gap-3`,children:[Q(`div`,{className:`flex min-w-0 items-center gap-3`,children:[r||i?Z(Na,{walletId:i,icon:r,label:n,size:40,className:`shrink-0`,imageClassName:`shrink-0 rounded-full object-cover`,fallback:Z(Wy,{size:40,walletAddress:e})}):Z(Wy,{size:40,walletAddress:e}),Q(`div`,{className:`min-w-0`,children:[Z(`p`,{className:`truncate text-sm font-semibold text-gray-900 dark:text-white`,children:n}),Q(`div`,{className:`flex min-w-0 flex-col`,children:[Z(U,{text:e,size:`sm`,iconColor:`#6b7280`,className:Gy,buttonContent:Z(`span`,{className:`truncate`,children:o})}),t?Z(U,{text:t,size:`sm`,iconColor:`#6b7280`,className:Gy,buttonContent:Z(`span`,{className:`truncate`,children:s})}):null]})]})]}),a&&Q(`button`,{type:`button`,onClick:a,className:`inline-flex shrink-0 cursor-pointer items-center gap-1 rounded-full px-3 py-1.5 text-sm font-medium trails-bg-secondary trails-hover-bg transition-colors`,children:[Z(xi,{className:`h-3.5 w-3.5`}),Z(`span`,{children:`Switch`})]})]})}):null}function qy(e,t,n,r){return Ec({symbol:t,chainId:n,contractAddress:r})||(e?e.replace(`/small/`,`/large/`):null)}const Jy=({imageUrl:e,symbol:t,chainId:n,contractAddress:r,size:i=24})=>{let[a,o]=X(!1),[c,l]=X(null),u=Y(null),d=n?$(n):null,f=J(()=>qy(e,t,n,r),[e,t,n,r]);q(()=>{u.current!==f&&(l(null),o(!1),u.current=f)},[f]);let p=t?.[0]?.toUpperCase()||`?`,m=e=>{let i=e.currentTarget,a={width:i.naturalWidth,height:i.naturalHeight};l(a),s.console.log(`[TokenImage] Image loaded`,{effectiveImageUrl:f,naturalWidth:i.naturalWidth,naturalHeight:i.naturalHeight,symbol:t,chainId:n,contractAddress:r})},h=()=>{a||(s.console.error(`[TokenImage] Image load error`,{effectiveImageUrl:f,imageUrl:e,symbol:t,chainId:n,contractAddress:r}),o(!0))},g=c!==null&&c.width<=1&&c.height<=1,_=!f||a||g;return Q(`div`,{className:`rounded-full flex items-center justify-center text-sm relative m-0 ${t===`ETH`?``:`bg-gray-400 dark:bg-gray-900`}`,style:{minWidth:i,minHeight:i,maxWidth:i,maxHeight:i,width:i,height:i,backgroundColor:t===`ETH`?`#627eeb`:void 0},title:`${t}${n?` on ${d?.name||`chain`} (${n})`:``}`,children:[_?Z(`div`,{className:`absolute w-full h-full rounded-full flex items-center justify-center`,title:t?.length&&t.length>1?`Token: ${t}`:``,children:Z(`span`,{className:`text-white font-medium text-xs`,children:p})}):Z(`img`,{src:f,alt:t||`Token`,loading:`lazy`,className:`absolute w-full h-full rounded-full object-contain`,onLoad:m,onError:h,title:`Token: ${t}`,style:{width:i,height:i}}),n&&Z(`div`,{className:`absolute`,style:{right:`-2%`,bottom:`-2%`},children:Z(`div`,{className:`border-1 border-white dark:border-black rounded-full`,children:Z(Ty,{chainId:n,size:Math.round(i*.4)})})})]})},Yy=({recentTokens:e,onTokenSelect:t,selectedToken:n})=>{if(e.length===0)return null;let r=e=>n?(e.chainId||0)===(n.chainId||0)&&ft(e.contractAddress,n.contractAddress,e.chainId):!1;return Q(`div`,{className:`mb-0`,children:[Z(`h3`,{className:`text-[10px] font-medium text-gray-500 dark:text-gray-500 text-left mb-1`,children:`Recently Used`}),Z(`div`,{className:`flex gap-1 overflow-x-auto trails-scrollbar`,children:e.map(e=>{let n=r(e);return Z(`button`,{type:`button`,onClick:()=>t(e),title:`${e.symbol} - ${e.name}`,className:`flex-shrink-0 p-1 border-solid trails-border-radius-button transition-colors cursor-pointer ${n?`bg-blue-100 dark:bg-blue-900/30 border-2 border-blue-500`:`trails-bg-secondary border-2 border-transparent hover:trails-hover-bg`}`,children:Z(`div`,{className:`rounded-full flex items-center justify-center bg-white dark:bg-gray-600`,children:Z(Jy,{symbol:e.symbol,imageUrl:e.imageUrl,chainId:e.chainId||0,size:28})})},`${e.chainId||0}-${e.contractAddress}`)})})]})},Xy=({value:e,onChange:t,onDebouncedChange:n,debounceMs:r=300,placeholder:i=`Search`,autoFocus:a=!1,rightAlignedComponent:o,className:s=``})=>{let c=Y(null),l=Y(null),[u,d]=X(e??``),f=e!==void 0&&t!==void 0,p=f?e:u;q(()=>{f&&e!==u&&d(e)},[e,f,u]),q(()=>()=>{l.current&&clearTimeout(l.current)},[]);let m=K(e=>{let i=e.target.value;d(i),t&&t(i),n&&(l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{n(i)},r))},[t,n,r]);return q(()=>{a&&c.current&&c.current.focus()},[a]),Q(`div`,{className:`relative ${s}`,children:[Z(`div`,{className:`absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none`,children:Z(qi,{className:`h-5 w-5 text-gray-500 dark:text-gray-500`})}),Z(`input`,{ref:c,type:`text`,value:p,onChange:m,placeholder:i,className:`block w-full pl-10 ${o?`pr-16`:`pr-4`} py-2 border border-solid border-gray-200 dark:border-gray-700 trails-border-radius-input focus:ring-2 focus:ring-blue-500 focus:border-blue-500 trails-input`}),o&&Z(`div`,{className:`absolute inset-y-0 right-0 flex items-center`,children:o})]})},Zy=({className:e=``})=>Q(`div`,{className:`w-full py-2 px-4 flex items-center space-x-3 ${e}`,style:{height:56},children:[Z(`div`,{className:`relative shrink-0 mr-2`,children:Z(`div`,{className:`rounded-full bg-gray-200 dark:bg-gray-700 animate-pulse`,style:{width:32,height:32}})}),Q(`div`,{className:`flex-1 min-w-0 text-left space-y-2`,children:[Z(`div`,{className:`bg-gray-200 dark:bg-gray-700 rounded animate-pulse`,style:{width:`65%`,height:14}}),Z(`div`,{className:`bg-gray-200 dark:bg-gray-700 rounded animate-pulse`,style:{width:`45%`,height:12}})]})]}),Qy=({count:e=4,className:t=``})=>Z(`div`,{className:t,children:Array.from({length:e}).map((e,t)=>Z(Zy,{},t))});function $y({token:e,copyAs:t=`button`,className:n=``}){let{contractAddress:r}=e;return r?Q(`div`,{className:`absolute top-0 left-0 flex items-center gap-1.5 transition-all duration-300 ease-in-out opacity-0 transform translate-x-2 ${n}`,children:[Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap`,children:wt(r)}),Z(U,{text:r,stopPropagation:!0,className:`p-0.5`,size:`sm`,as:t}),Z(y,{content:Q(`div`,{className:`space-y-2 text-left`,children:[Q(`div`,{children:[Z(`span`,{className:`opacity-70`,children:`Symbol:`}),` `,Z(`span`,{className:`font-medium`,children:e.symbol})]}),Q(`div`,{children:[Z(`span`,{className:`opacity-70`,children:`Name:`}),` `,Z(`span`,{className:`font-medium`,children:e.name})]}),Q(`div`,{children:[Z(`span`,{className:`opacity-70`,children:`Chain:`}),` `,Z(`span`,{className:`font-medium`,children:e.chainName||$(e.chainId||0)?.name||`Chain ${e.chainId||0}`})]}),Q(`div`,{children:[Z(`span`,{className:`opacity-70`,children:`Decimals:`}),` `,Z(`span`,{className:`font-medium`,children:e.decimals})]}),Q(`div`,{children:[Z(`span`,{className:`opacity-70`,children:`Address:`}),` `,Z(`span`,{className:`font-mono text-[10px] break-all block mt-0.5`,children:r})]})]}),side:`top`,align:`center`,sideOffset:8,children:Z(Vi,{className:`w-3 h-3 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 cursor-pointer`})})]}):null}const eb=[];function tb(e,t){return(e.chainId||0)===(t.chainId||0)&&ft(e.contractAddress,t.contractAddress,e.chainId)}function nb(e,t){let n=t.trim();return n?W(e.chainId??0)?e.contractAddress.includes(n):St(e.contractAddress).includes(n.toLowerCase()):!0}const rb=mr(({token:e,isSelected:t,fundMethod:n,isBalanceVisible:r,onTokenSelect:i,virtualRow:a,measureElement:o,allowZeroBalance:s=!1})=>{let{symbol:c,imageUrl:l,chainId:u,contractAddress:d,balanceUsdFormatted:f,balanceUsdDisplay:p,balanceUsdLocaleDisplay:m,name:h,priceUsd:g,balanceFormatted:_,balanceLocaleDisplay:v,balance:y,balanceUsd:b,isSufficientBalance:x}=e,S=!N_(y)||!N_(_)||!N_(b),C=(g??0)>0||(b??0)>0,w=x??!0,T=!s&&(!n||n===`wallet`)&&W(u||0)&&!ws(e),E=!w&&n!==`direct-transfer`&&n!==`onramp-mesh`&&n!==`onramp-meld`,D=n!==`direct-transfer`&&n!==`onramp-meld`&&(S||T),O=K(()=>{T||E||i(e)},[E,T,i,e]);return Z(`div`,{"data-index":a.index,ref:o,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${a.start}px)`},children:Q(`button`,{type:`button`,onClick:O,disabled:T||E,title:T?`No balance for this token`:E?`Insufficient balance for this token`:`Select ${h} token`,className:`w-full py-2 px-4 flex items-center space-x-3 transition-all duration-200 trails-list-item trails-border-radius-list-button relative ${t?`trails-list-item-selected`:``} ${T?`opacity-50 cursor-not-allowed`:E?`opacity-75 cursor-not-allowed`:`cursor-pointer`}`,children:[Z(`div`,{className:`relative shrink-0 mr-2`,children:Z(`div`,{className:`rounded-full flex items-center justify-center bg-gray-100 dark:bg-gray-700 ${E?`opacity-80`:``}`,children:d?Z(Jy,{symbol:c,imageUrl:l,chainId:u,contractAddress:d,size:32}):Z(`span`,{className:`text-base font-medium text-gray-600 dark:text-gray-300 ${E?`opacity-70`:``}`,children:c})})}),Q(`div`,{className:`flex-1 min-w-0 text-left`,children:[Z(`h3`,{className:`text-sm font-medium truncate text-gray-900 dark:text-white ${E?`opacity-70`:``}`,style:{...E?{maxWidth:`100px`}:{}},children:h}),Q(`div`,{className:`group relative w-full`,children:[Q(`div`,{className:`flex items-center gap-1.5 transition-all duration-300 ease-in-out ${d&&!bt(d)?`group-hover:opacity-0 group-hover:transform group-hover:-translate-x-2`:``} ${E?`opacity-70`:``}`,children:[Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap truncate inline-block`,style:{...E?{maxWidth:`100px`}:{}},children:c}),e.isCustomToken&&Q(`div`,{className:`relative group/indicator`,children:[Z(_i,{className:`w-3 h-3 text-gray-500 dark:text-gray-400`}),Q(`div`,{className:`absolute bottom-full left-1/2 -translate-x-1/2 mb-1 px-2 py-1 text-xs text-white bg-gray-900 dark:bg-gray-700 rounded whitespace-nowrap opacity-0 group-hover/indicator:opacity-100 transition-opacity pointer-events-none z-50`,children:[`Custom token added by user`,Z(`div`,{className:`absolute top-full left-1/2 -translate-x-1/2 -mt-px border-4 border-transparent border-t-gray-900 dark:border-t-gray-700`})]})]})]}),d&&!bt(d)&&Z($y,{token:e,copyAs:`span`,className:`${E?`group-hover:opacity-70`:`group-hover:opacity-100`} group-hover:translate-x-0`}),d&&!bt(d)&&e.isCustomToken&&Q(`div`,{className:`relative group/indicator`,children:[Z(_i,{className:`w-3 h-3 text-gray-500 dark:text-gray-400`}),Q(`div`,{className:`absolute bottom-full left-1/2 -translate-x-1/2 mb-1 px-2 py-1 text-xs text-white bg-gray-900 dark:bg-gray-700 rounded whitespace-nowrap opacity-0 group-hover/indicator:opacity-100 transition-opacity pointer-events-none z-50`,children:[`Custom token added by user`,Z(`div`,{className:`absolute top-full left-1/2 -translate-x-1/2 -mt-px border-4 border-transparent border-t-gray-900 dark:border-t-gray-700`})]})]})]})]}),D&&Z(`div`,{className:`text-right shrink-0 flex flex-col items-end`,children:T?Q(hi,{children:[Z(`p`,{className:`text-sm font-medium text-gray-500 dark:text-gray-400 notranslate`,translate:`no`,children:r?`$0.00`:`••••••`}),Z(`p`,{className:`text-xs text-gray-400 dark:text-gray-500 notranslate`,translate:`no`,children:r?`0`:`••••••`})]}):C?Q(hi,{children:[Z(`p`,{className:`text-sm font-medium text-gray-900 dark:text-white notranslate ${w?``:`opacity-70`}`,translate:`no`,children:r?m||p||f||`$0.00`:`••••••`}),Z(`p`,{className:`text-xs text-gray-500 dark:text-gray-400 notranslate ${w?``:`opacity-70`}`,translate:`no`,children:r?v||_:`••••••`})]}):Z(`p`,{className:`text-sm font-medium text-gray-900 dark:text-white notranslate ${w?``:`opacity-70`}`,translate:`no`,children:r?v||_:`••••••`})})]})},a.key)});rb.displayName=`TokenRow`;const ib=({onTokenSelect:e,targetAmountUsd:t,onError:n,recentTokens:r=eb,onRecentTokenSelect:i,fundMethod:a,onNavigateToFundMethods:o,showContinueButton:s=!1,selectedToken:c,onContinue:l,showInsufficientBalance:u=!1,compactMode:d=!1,allSupportedTokens:f=!1,allowedTokens:p,allowedTokenKeys:m,allowedTokenRestrictedChainIds:h,allowedChainIds:g,chainListScreen:_,onNavigateToChainList:v,onNavigateToSwitchWallet:y,accountAddress:b,accountHeaderLabel:x,disabledChains:S,chainFilterChainId:C,onChainFilterChange:w,includeSolanaChainFilter:T=!1,catalogSupplementTokens:E})=>{let[D,O]=X(!1),{isBalanceVisible:k}=vu(),{address:A}=Kr(),j=Jr(),M=ni(),N=qu(),P=E_(b??A),F=Hu(),I=wd(F,J(()=>bd({connectedWallets:j,svmWallet:N,session:M,selectedFundingWallet:F,activeEvmAddress:A}),[A,j,F,N,M])),ee=b??P,te=J(()=>{if(I)return Zu(F)?N?.publicKey?.toBase58?.():Cd({evmAccountAddress:ee,connectedWallets:j,svmWallet:N,session:M})},[j,I,F,N,M,ee]),ne=J(()=>S?.length?new Set(S):null,[S]),re=!!ne?.size||w!=null&&C!==void 0,ie=mu({isolated:re,controlled:C,onChange:re?w:void 0}),L=T||!!N&&a===`wallet`&&I&&!ne?.has(101),R=ee??te??void 0,ae=J(()=>{if(!(!N||!te||R!==te))return pd(N)},[te,R,N]),z=N&&te&&R===te?N.walletId:void 0,{selectedMeshExchange:B,selectedMeshAccessTokens:V}=wy(),{selectedBluvoExchange:oe,selectedBluvoWalletId:H,selectedBluvoBalances:se}=Vu(),ce=Y(null),{handleChainSelect:U}=D_(a,f),{selectedChainId:le,setSelectedChainId:ue,clearChainFilter:de}=ie,fe=K(e=>{if(re){ue(e);return}U(e)},[U,ue,re]),{searchQuery:pe,setSearchQuery:me,handleTokenSelect:he,filteredTokens:ge,chainFilteredTokens:_e,foundTokensAllChains:ve,isLoadingTokens:ye,isLoadingCustomToken:be,isSearching:xe,customTokenError:Se,isTokenSelected:Ce,balanceError:we,showInsufficientBalance:Te}=Cy({onContinue:e,targetAmountUsd:t,onError:n,accountAddress:ee,fundMethod:a,allSupportedTokens:f,allowedTokens:p,allowedTokenKeys:m,allowedTokenRestrictedChainIds:h,allowedChainIds:g,solanaAccountAddress:L?te:null,chainFilterChainId:re?le:void 0,catalogSupplementTokens:E}),Ee=u||Te,{data:De=[]}=Hx(),Oe=J(()=>g?new Set(g):null,[g]);q(()=>{Oe&&le!==null&&!Oe.has(le)&&(re?ue(null):de())},[Oe,le,de,ue,re]),q(()=>{!ne?.size||le===null||ne.has(le)&&(re?ue(null):de())},[ne,le,de,ue,re]);let ke=gr(_e),Ae=J(()=>a!==`onramp-bluvo`||!oe||!H?ke:ke.filter(e=>{let t=Number(e.balanceFormatted||e.balanceDisplay||e.balance||0),n=Number(e.balanceUsd||0);return Number.isFinite(t)&&t>0||Number.isFinite(n)&&n>0}),[ke,a,oe,H]),je=J(()=>ne?.size?Ae.filter(e=>e.chainId==null||!ne.has(e.chainId)):Ae,[Ae,ne]),Me=J(()=>le===null||je.length>0||ve.length===0||!bn(pe.trim())?[]:ve.filter(e=>(e.chainId||0)!==le&&(e.chainId==null||!ne?.has(e.chainId))),[le,je,ve,pe,ne]);q(()=>{!ye&&!D&&O(!0)},[ye,D]);let Ne=!D&&(ye||je.length===0),Pe=J(()=>{let e;return e=g?.length?g.map(e=>({chainId:e,name:$(e)?.name||`Chain ${e}`,imageUrl:``})).sort((e,t)=>e.name.localeCompare(t.name)):De.map(e=>{let t=$(e.id);return{chainId:e.id,name:t?.name||e.name||`Chain ${e.id}`,imageUrl:``}}).sort((e,t)=>e.name.localeCompare(t.name)),L&&(!g?.length||g.includes(101))&&(e.some(e=>e.chainId===101)||(e=[...e,Ra].sort((e,t)=>e.name.localeCompare(t.name)))),ne?.size&&(e=e.filter(e=>!ne.has(e.chainId))),e},[g,ne,L,De]),Fe=r.filter(e=>{if(!je.some(t=>tb(t,e)))return!1;if(!pe.trim())return!0;let t=pe.trim().toLowerCase();return e.symbol.toLowerCase().includes(t)||e.name.toLowerCase().includes(t)||nb(e,pe)}),Ie=J(()=>Fe.map(e=>{let t=je.find(t=>tb(t,e));return t?{...e,balance:t.balance,balanceFormatted:t.balanceFormatted,balanceDisplay:t.balanceDisplay,balanceLocaleDisplay:t.balanceLocaleDisplay,balanceUsd:t.balanceUsd,balanceUsdFormatted:t.balanceUsdFormatted,balanceUsdDisplay:t.balanceUsdDisplay,balanceUsdLocaleDisplay:t.balanceUsdLocaleDisplay}:e}),[je,Fe]),Le=d?192:Ie.length>0?200:250,Re=ja({count:je.length,getScrollElement:()=>ce.current,estimateSize:()=>56,overscan:25}),ze=K(e=>{de(),he(e)},[he,de]),Be=e=>{let t=je.find(t=>tb(t,e));t?ze(t):i&&(de(),i(e))},Ve=J(()=>Se&&pe.trim().startsWith(`0x`)?`Token not found on any supported chain.`:pe.trim()?`No tokens found matching your search.`:a===`direct-transfer`||a===`onramp-mesh`?``:a===`onramp-bluvo`?!oe||!H?`Connect your exchange to load withdrawable assets.`:se.length===0?`Your connected exchange account has no withdrawable assets yet.`:`No route-compatible assets are available for this connected exchange account.`:ee&&!f?`No available tokens found`:f?`No tokens found`:``,[Se,a,pe,se.length,oe,H,ee,f]);return Q(`div`,{className:`space-y-2`,children:[a===`onramp-mesh`&&B&&Z(jy,{exchangeName:B.exchangeName,exchangeKey:B.exchangeKey,exchangeImageUrl:B.imageUrl,connectedAccountName:V[0]?.accountName}),a===`wallet`&&_&&(ee||te)&&Z(Ky,{walletAddress:R,walletIconUrl:ae,walletId:z,secondaryAddress:ee&&te&&ee!==te?te:void 0,label:x,onSwitchWallet:y}),Z(Xy,{onDebouncedChange:me,debounceMs:300,placeholder:`Search tokens, symbol, address`,autoFocus:!0,className:`mb-2`,rightAlignedComponent:Z(Oy,{chains:Pe,selectedChainId:le,onChainSelect:fe,compactMode:d,nestedMode:!0,chainListScreen:_,onNavigateToChainList:v})}),D&&Ie.length>0&&Z(`div`,{className:`overflow-hidden trails-fade-slide-in-fast`,children:Z(Yy,{recentTokens:Ie,onTokenSelect:Be})}),Ne&&Z(`div`,{style:{height:Le},children:Z(Qy,{count:Math.floor(Le/56)})}),D&&xe&&je.length===0&&Z(`div`,{style:{height:Le},children:Z(Qy,{count:Math.floor(Le/56)})}),D&&be&&je.length===0&&Z(`div`,{style:{height:Le},children:Z(Qy,{count:Math.floor(Le/56)})}),D&&!be&&!xe&&!we&&ge.length===0&&je.length===0&&Ve&&Q(`div`,{className:`space-y-3`,children:[Z(`div`,{className:`text-center py-4 rounded-lg trails-bg-secondary`,children:Z(`p`,{className:`text-gray-500 dark:text-gray-400`,children:Ve})}),Me.length>0&&Q(`div`,{className:`space-y-2`,children:[Z(`p`,{className:`text-xs font-medium text-gray-500 dark:text-gray-400 px-2`,children:Me.length===1?`Found on another chain`:`Found on ${Me.length} other chains`}),Z(`div`,{className:`max-h-48 overflow-y-auto trails-scrollbar`,children:Me.map(e=>{let t=$(e.chainId||0),n=e.chainName||t?.name||`Chain ${e.chainId||0}`;return Q(`div`,{onClick:()=>ze(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),ze(e))},className:`w-full py-2 px-4 flex items-center space-x-3 transition-all duration-200 trails-list-item trails-border-radius-list-button cursor-pointer`,children:[Z(`div`,{className:`relative shrink-0 mr-2`,children:Z(`div`,{className:`rounded-full flex items-center justify-center bg-gray-100 dark:bg-gray-700`,children:e.contractAddress?Z(Jy,{symbol:e.symbol,imageUrl:e.imageUrl,chainId:e.chainId,contractAddress:e.contractAddress,size:32}):Z(`span`,{className:`text-base font-medium text-gray-600 dark:text-gray-300`,children:e.symbol})})}),Q(`div`,{className:`flex-1 min-w-0 text-left`,children:[Z(`h3`,{className:`text-sm font-medium truncate text-gray-900 dark:text-white`,children:e.name}),Q(`span`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:[e.symbol,` on `,n]})]})]},`${e.chainId}-${e.contractAddress}`)})})]})]}),D&&je.length>0&&Z(`div`,{ref:ce,className:`overflow-y-auto trails-scrollbar`,style:{height:Le},children:Z(`div`,{style:{height:`${Re.getTotalSize()}px`,width:`100%`,position:`relative`},children:Re.getVirtualItems().map(e=>{let t=je[e.index];return t?Z(rb,{token:t,isSelected:Ce(t),fundMethod:a,isBalanceVisible:k,onTokenSelect:ze,virtualRow:e,measureElement:Re.measureElement,allowZeroBalance:f},e.key):null})})}),Ee&&a!==`direct-transfer`&&a!==`onramp-mesh`&&a!==`onramp-meld`&&Q(`div`,{className:`text-left py-3 px-4 rounded-lg bg-amber-500/10 border border-solid border-amber-500/30`,children:[Z(`p`,{className:`text-xs font-medium text-amber-400`,children:`Insufficient balance`}),Z(`p`,{className:`text-xs mt-1 text-amber-300`,children:`You do not have enough funds to reach the target amount`})]}),s&&l&&c&&Z(`div`,{className:`space-y-4`,children:Z(`button`,{type:`button`,onClick:()=>l(c),disabled:!c,className:`w-full font-semibold py-3 px-4 trails-border-radius-button transition-colors bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white disabled:text-gray-500 disabled:cursor-not-allowed cursor-pointer`,children:`Continue`})}),(a===`direct-transfer`||a===`onramp-mesh`||a===`onramp-meld`)&&Z(`div`,{className:`text-center pt-2 pb-1`,children:Z(`p`,{className:`text-sm font-medium text-gray-600 dark:text-gray-400`,children:a===`direct-transfer`?`Paying with Crypto Transfer`:`Paying with Exchange Deposit`})}),o&&D&&Z(`div`,{className:`text-center pt-1`,children:Q(`button`,{type:`button`,onClick:o,className:`inline-flex items-center justify-center space-x-1 px-2 py-1 text-xs font-medium trails-text-secondary trails-bg-secondary trails-hover-bg trails-border trails-border-radius-button transition-all duration-200 cursor-pointer`,children:[Z(Oi,{className:`h-3 w-3`}),Z(`span`,{children:`Pay with another method`})]})})]})},ab=`trails_recent_chains`;function ob(e){let[t,n]=X([]);return q(()=>{if(!e){n([]);return}try{let t=localStorage.getItem(ab);if(!t){n([]);return}let r=JSON.parse(t);n(r[St(e)]||[])}catch(e){n([]),s.console.warn(`[trails-sdk] Failed to load recent chains from localStorage:`,e)}},[e]),{recentChains:t,addRecentChain:K(t=>{if(e)try{let r=localStorage.getItem(ab),i=r?JSON.parse(r):{},a=St(e),o=i[a]||[];o=o.filter(e=>e.chainId!==t.chainId),o.unshift(t),o=o.slice(0,3),i[a]=o,localStorage.setItem(ab,an(i)),n(o)}catch(e){s.console.warn(`[trails-sdk] Failed to save recent chain to localStorage:`,e)}},[e]),clearRecentChains:K(()=>{if(e)try{let t=localStorage.getItem(ab);if(t){let n=JSON.parse(t);delete n[St(e)],localStorage.setItem(ab,an(n))}n([])}catch(e){s.console.warn(`[trails-sdk] Failed to clear recent chains from localStorage:`,e)}},[e])}}const sb=({recentChains:e,onChainSelect:t})=>e.length===0?null:Q(`div`,{className:`mb-1`,children:[Z(`h3`,{className:`text-[10px] font-medium text-gray-500 dark:text-gray-500 text-left mb-1`,children:`Recently Used`}),Z(`div`,{className:`flex gap-2 overflow-x-auto scrollbar-hide-always pb-1`,children:e.map(e=>Q(`button`,{type:`button`,onClick:()=>t(e.chainId),title:`Select ${e.name}`,className:`flex-shrink-0 flex items-center gap-1.5 px-2.5 py-1.5 border-solid trails-border-radius-button transition-colors cursor-pointer trails-bg-secondary border border-transparent hover:trails-hover-bg`,children:[Z(Ty,{chainId:e.chainId,size:16}),Z(`span`,{className:`text-xs font-medium text-gray-900 dark:text-white whitespace-nowrap`,children:Ga(e.chainId,e.name)})]},e.chainId))})]}),cb=({onBack:e,chains:t,extraChains:n,onChainSelect:r,disabledChains:i})=>{let[a,o]=X(``),{address:s}=Kr(),{selectedChainId:c,setSelectedChainId:l}=mu(),{recentChains:u,addRecentChain:d}=ob(s),{data:f=[]}=Hx(),p=J(()=>i?.length?new Set(i):null,[i]),m=J(()=>{let e=t||f.map(e=>({chainId:e.id,name:e.name,imageUrl:``})),r=p?e.filter(e=>!p.has(e.chainId)):e;if(!n?.length)return r;let i=new Set(n.map(e=>e.chainId));return[...p?n.filter(e=>!p.has(e.chainId)):n,...r.filter(e=>!i.has(e.chainId))]},[t,p,n,f]),h=J(()=>{if(!a.trim())return m;let e=a.trim().toLowerCase();return m.filter(t=>t.name.toLowerCase().includes(e)||t.chainId.toString().includes(e))},[m,a]),g=J(()=>{let e=new Set(m.map(e=>e.chainId));return u.filter(t=>e.has(t.chainId))},[m,u]),_=t=>{if(t!==null){let e=m.find(e=>e.chainId===t);e&&d(e)}r?r(t):l(t),e()};return Q(`div`,{className:`flex flex-col h-full max-h-[600px]`,children:[Z(M_,{onBack:e,headerContent:`Select Chain`}),Q(`div`,{className:`flex-1 overflow-hidden flex flex-col space-y-2`,children:[Z(Xy,{value:a,onChange:o,placeholder:`Search chains`,autoFocus:!0,className:`mb-2 p-1`}),g.length>0&&Z(`div`,{className:`overflow-hidden trails-fade-slide-in-fast`,children:Z(sb,{recentChains:g,onChainSelect:_})}),Q(`div`,{className:`max-h-[250px] overflow-y-auto trails-scrollbar space-y-1`,children:[Q(`button`,{type:`button`,onClick:()=>_(null),className:`w-full py-2 px-4 flex items-center space-x-3 transition-all duration-200 trails-list-item trails-border-radius-list-button cursor-pointer`,title:`Show tokens from all chains`,children:[Z(`div`,{className:`relative flex-shrink-0 mr-2`,children:Z(`div`,{className:`rounded-full flex items-center justify-center bg-gray-100 dark:bg-gray-700`,children:Z(Dy,{size:32,chainIds:m.map(e=>e.chainId)})})}),Z(`div`,{className:`flex-1 min-w-0 text-left`,children:Z(`h3`,{className:`text-sm font-medium truncate text-gray-900 dark:text-white`,children:`All Chains`})})]}),h.map(e=>Q(`button`,{type:`button`,onClick:()=>_(e.chainId),className:`w-full py-2 px-4 flex items-center space-x-3 transition-all duration-200 trails-list-item trails-border-radius-list-button cursor-pointer ${c===e.chainId?`trails-list-item-selected`:``}`,title:`Select ${e.name} (${e.chainId})`,children:[Z(`div`,{className:`relative flex-shrink-0 mr-2`,children:Z(`div`,{className:`rounded-full flex items-center justify-center bg-gray-100 dark:bg-gray-700`,children:Z(Ty,{chainId:e.chainId,size:32})})}),Z(`div`,{className:`flex-1 min-w-0 text-left`,children:Z(`h3`,{className:`text-sm font-medium truncate text-gray-900 dark:text-white`,children:Ga(e.chainId,e.name)})}),c===e.chainId&&Z(`div`,{className:`w-5 h-5 rounded-full bg-blue-500 flex items-center justify-center flex-shrink-0`,children:Q(`svg`,{className:`w-3 h-3 text-white`,fill:`currentColor`,viewBox:`0 0 20 20`,"aria-label":`Selected`,children:[Z(`title`,{children:`Selected`}),Z(`path`,{fillRule:`evenodd`,d:`M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z`,clipRule:`evenodd`})]})})]},e.chainId)),h.length===0&&a.trim()&&Z(`div`,{className:`text-center py-4 rounded-lg trails-bg-secondary`,children:Z(`p`,{className:`text-gray-500 dark:text-gray-400`,children:`No chains found matching your search.`})})]})]})]})},lb=({onError:e,fundMethod:t,accountAddress:n,allSupportedTokens:r=!1})=>{let[i,a]=X(!1),{refreshTokens:o}=Cy({onContinue:K(e=>{},[]),onError:e,fundMethod:t,accountAddress:n,allSupportedTokens:r});return Z(`button`,{type:`button`,onClick:K(async()=>{if(!i){a(!0);try{await o()}finally{a(!1)}}},[i,o]),disabled:i,className:`inline-flex h-8 w-8 cursor-pointer items-center justify-center rounded-full bg-transparent text-gray-500 transition-colors hover:text-gray-900 disabled:cursor-wait dark:text-gray-400 dark:hover:text-white`,title:`Refresh tokens`,"aria-label":`Refresh tokens`,children:Z(Gi,{className:`h-4 w-4 ${i?`animate-spin`:``}`,"aria-hidden":`true`})})},ub=[],db=({onContinue:e,onBack:t,accountAddress:n,targetAmountUsd:r,targetAmountUsdFormatted:i,onError:a,recentTokens:o=ub,onRecentTokenSelect:s,fundMethod:c,onNavigateToFundMethods:l,onShowChainList:u,onNavigateToSwitchWallet:d})=>{let{mode:f}=y_(),{setSelectedToken:p}=ul(),[m,h]=X(!1),g=qu(),{address:_}=Kr(),v=Jr(),y=ni(),b=Hu(),x=wd(b,J(()=>bd({connectedWallets:v,svmWallet:g,session:y,selectedFundingWallet:b,activeEvmAddress:_}),[_,v,b,g,y])),S=J(()=>g&&c===`wallet`&&x?[Ra]:void 0,[c,x,g]),{handleChainSelect:C}=D_(c);return m?Z(cb,{extraChains:S,onChainSelect:C,onBack:()=>h(!1)}):Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:t,headerContent:f===`fund`?`Fund with any token`:r?f===`earn`?`Deposit ${i} with:`:`Pay ${i} with:`:`Select payment token`,customActions:Z(lb,{onError:a,fundMethod:c,accountAddress:n??void 0})}),Z(ib,{accountAddress:n??void 0,onTokenSelect:t=>{p(t),e(t)},targetAmountUsd:r,targetAmountUsdFormatted:i,onError:a,recentTokens:o,onRecentTokenSelect:s,fundMethod:c,onNavigateToFundMethods:l,showContinueButton:!0,onContinue:e,chainListScreen:!0,onNavigateToChainList:()=>{u?u():h(!0)},onNavigateToSwitchWallet:d})]})},fb=({inputValue:e,variant:t=`default`,size:n=`standard`,textAlign:r=`left`})=>J(()=>{let i=e.length,a;a=t===`smaller`||t===`inline`?i>24?`0.75rem`:i>22?`0.8125rem`:i>20?`0.875rem`:i>15?`1rem`:i>12?`1.125rem`:i>9?`1.25rem`:i>6?`1.375rem`:`1.5rem`:n===`large`?i>24?`0.875rem`:i>22?`1rem`:i>20?`1.125rem`:i>18?`1.25rem`:i>15?`1.5rem`:i>12?`1.875rem`:i>9?`2.25rem`:i>6?`3rem`:`3.75rem`:i>24?`0.75rem`:i>22?`0.875rem`:i>20?`1rem`:i>15?`1.125rem`:i>12?`1.5rem`:i>9?`1.75rem`:i>6?`2rem`:`2.25rem`;let o={fontSize:a,transition:`all 0.1s ease-in-out`,textAlign:r};return t===`inline`?{...o,width:`${Math.max((e||`0`).length,1)}ch`,minWidth:`1ch`,maxWidth:`270px`,padding:`0`,margin:`0`}:o},[e,t,n,r]),pb=fr(({id:e=`amount`,value:t,onChange:n,placeholder:r=`0`,isLoading:i=!1,className:a,variant:o=`default`,inputSize:s=`standard`,textAlign:c=`left`,maxDecimals:l=18,maxDigits:u=30,showPlaceholderStyle:d=!1,currencySymbol:f,onFocus:m,onBlur:h,disabled:g,isFiatInput:_=!1,...v},y)=>{let b=fb({inputValue:t,variant:o,size:s,textAlign:c}),x=t||r,S=(x.match(/\./g)||[]).length,C=x.length-S,w=Math.max(C+S*.3+.1,1),T=K(e=>{if(!n)return;let r=e.target.value;if(r===``){n(e);return}if(r.startsWith(`.`)){r=`0${r}`,n({...e,target:{...e.target,value:r}});return}if(t===`0`&&r.length===2&&/^0\d$/.test(r)){r=`0.${r[1]}`,n({...e,target:{...e.target,value:r}});return}if(r.length>1&&r.startsWith(`0`)&&r[1]!==`.`){let e=r.replace(/^0+/,``);r=e===``?`0`:e}if(!(r.length>u)&&RegExp(`^\\d*\\.?\\d{0,${l}}$`).test(r)){if(r!==e.target.value){n({...e,target:{...e.target,value:r}});return}n(e)}},[n,l,u,t]),E=d?`text-gray-400 dark:text-gray-500`:`trails-text-primary`;return f?Q(`div`,{className:`inline-flex items-end ${c===`center`?`justify-center`:c===`right`?`justify-end`:`justify-start`}`,children:[_&&Z(`span`,{className:`font-bold ${i?`animate-pulse`:``} select-none`,style:{fontSize:b.fontSize,fontWeight:`bold`,color:`#a3a3a8`,marginRight:`0.1ch`},children:p[f]||f}),Z(`input`,{ref:y,id:e,type:`text`,value:t,onChange:T,onFocus:m,onBlur:h,disabled:g,placeholder:r,autoComplete:`off`,className:`bg-transparent font-bold ${E} placeholder:trails-text-muted border-none outline-none ${i?`animate-pulse`:``}`,style:{...b,width:`${w}ch`},inputMode:`decimal`,...v}),!_&&Z(`span`,{className:`font-bold ${i?`animate-pulse`:``} select-none self-end`,style:{fontSize:`1.2rem`,fontWeight:`bold`,color:`#a3a3a8`,marginLeft:`2px`,marginBottom:`17px`},children:f})]}):Z(`input`,{ref:y,id:e,type:`text`,value:t,onChange:T,onFocus:m,onBlur:h,disabled:g,placeholder:r,autoComplete:`off`,className:a||`w-full bg-transparent font-bold ${E} placeholder:trails-text-muted border-none outline-none ${i?`animate-pulse`:``}`,style:b,inputMode:`decimal`,...v})});pb.displayName=`DynamicSizeInputField`;const mb=({token:e,onBack:t,onCancel:n,onSubmit:r,initialAmount:i})=>{let[a,o]=X(i??``);q(()=>{i!==void 0&&o(i)},[i]);let s=J(()=>e?$(e.chainId||0):void 0,[e]),c=J(()=>{if(!(!e?.balance||!e.decimals))try{return Xs(e.balance,e.decimals)}catch{return}},[e]);return Q(`div`,{className:`flex flex-col space-y-4`,children:[Z(M_,{headerContent:`Enter amount`,onBack:()=>t(a),rightSideContent:Z(`button`,{type:`button`,onClick:()=>n(a),className:`text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200`,children:`Cancel`})}),Z(`div`,{className:`flex items-center justify-between rounded-2xl border border-gray-200 dark:border-gray-700 p-4 bg-white dark:bg-gray-900/40`,children:e?Q(hi,{children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(Jy,{symbol:e.symbol,imageUrl:e.imageUrl,chainId:e.chainId,contractAddress:e.contractAddress,size:32}),Q(`div`,{children:[Z(`div`,{className:`text-base font-semibold text-gray-900 dark:text-gray-100`,children:e.symbol}),Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:s?.name??`Chain ${e.chainId}`})]})]}),c?Q(`button`,{type:`button`,onClick:()=>{c&&o(c)},className:`text-sm font-semibold text-blue-600 hover:text-blue-500`,children:[`Use max (`,c,`)`]}):null]}):Z(`div`,{className:`text-sm text-gray-500`,children:`Select a token first`})}),Q(`div`,{className:`space-y-2`,children:[Z(`label`,{htmlFor:`origin-amount-input`,className:`text-xs font-semibold uppercase text-gray-500 dark:text-gray-400`,children:`Amount to use`}),Z(`div`,{className:`rounded-2xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900/40 px-4 py-3`,children:Z(pb,{id:`origin-amount-input`,value:a,onChange:e=>o(e.target.value),placeholder:`0.0`})}),Z(`p`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`Enter the amount you want to spend from this token.`})]}),Z(`button`,{type:`button`,onClick:()=>{!a||Number(a)<=0||r(a.trim())},disabled:!a||Number(a)<=0,className:`w-full py-3 font-semibold trails-border-radius-button bg-blue-500 text-white disabled:bg-gray-200 disabled:text-gray-500 dark:disabled:bg-gray-800 dark:disabled:text-gray-500 hover:bg-blue-600 disabled:cursor-not-allowed transition-colors`,children:`Continue`})]})};function hb(){let[e,t]=X(!1);q(()=>{let e=setTimeout(()=>{t(!0)},100);return()=>clearTimeout(e)},[]);let n={container:{width:`80px`,height:`80px`,position:`relative`},circleContainer:{position:`relative`,width:`100%`,height:`100%`},circleFill:{position:`absolute`,top:0,left:0,width:`100%`,height:`100%`,borderRadius:`50%`,backgroundColor:`#ef4444`,transform:e?`scale(1)`:`scale(0)`,opacity:+!!e,transition:`transform 0.15s ease-out 0.3s, opacity 0.15s ease-out 0.3s`},progressRing:{position:`absolute`,top:0,left:0,width:`100%`,height:`100%`,transform:`rotate(-90deg)`},circle:{fill:`none`,stroke:`url(#redGradient)`,strokeWidth:4,strokeLinecap:`round`,strokeDasharray:226,strokeDashoffset:e?0:226,transition:`stroke-dashoffset 0.3s ease-out`},xContainer:{position:`absolute`,top:`50%`,left:`50%`,transform:e?`translate(-50%, -50%) scale(1)`:`translate(-50%, -50%) scale(0)`,opacity:+!!e,zIndex:10,transition:`transform 0.1s ease-out 0.4s, opacity 0.1s ease-out 0.4s`},xPath:{fill:`none`,stroke:`white`,strokeWidth:3,strokeLinecap:`round`,strokeLinejoin:`round`,strokeDasharray:15,strokeDashoffset:e?0:15,transition:`stroke-dashoffset 0.15s ease-out 0.45s`},xPathSecond:{fill:`none`,stroke:`white`,strokeWidth:3,strokeLinecap:`round`,strokeLinejoin:`round`,strokeDasharray:15,strokeDashoffset:e?0:15,transition:`stroke-dashoffset 0.15s ease-out 0.5s`}};return Z(`div`,{style:n.container,children:Q(`div`,{style:n.circleContainer,children:[Z(`div`,{style:n.circleFill}),Q(`svg`,{"aria-hidden":`true`,style:n.progressRing,children:[Z(`defs`,{children:Q(`radialGradient`,{id:`redGradient`,cx:`50%`,cy:`50%`,r:`50%`,gradientUnits:`objectBoundingBox`,children:[Z(`stop`,{offset:`0%`,style:{stopColor:`#ef4444`,stopOpacity:0}}),Z(`stop`,{offset:`70%`,style:{stopColor:`#ef4444`,stopOpacity:.3}}),Z(`stop`,{offset:`100%`,style:{stopColor:`#ef4444`,stopOpacity:1}})]})}),Z(`circle`,{cx:`40`,cy:`40`,r:`36`,style:n.circle})]}),Z(`div`,{style:n.xContainer,children:Q(`svg`,{"aria-hidden":`true`,width:`48`,height:`48`,viewBox:`0 0 24 24`,children:[Z(`path`,{d:`M6 6L18 18`,style:n.xPath}),Z(`path`,{d:`M18 6L6 18`,style:n.xPathSecond})]})})]})})}const gb=({option:e,chainId:t,isDisabled:n,isLoading:r,isSelected:i,variant:a=`compact`})=>{let o=n?`text-gray-400 dark:text-gray-500`:`trails-text-primary`;return a===`compact`?Q(hi,{children:[Q(`div`,{className:`flex items-center space-x-2`,children:[Z(Jy,{imageUrl:e.tokenImageUrl,symbol:e.tokenSymbol,chainId:e.chainId||t,size:24}),Z(`div`,{className:`ml-2 text-left`,children:r?Z(`div`,{className:`animate-pulse bg-gray-200 dark:bg-gray-700 h-4 w-20 rounded`}):Q(`div`,{className:`flex items-center gap-2`,children:[Z(`div`,{className:`text-xs font-medium ${o}`,children:e.amountFormatted}),e.isPassthroughEligible&&Z(`span`,{className:`text-[10px] px-2 py-0.5 rounded-full bg-gray-200 text-gray-900`,children:`passthrough`})]})})]}),Z(`div`,{className:`text-right`,children:r?Z(`div`,{className:`animate-pulse bg-gray-200 dark:bg-gray-700 h-4 w-12 rounded`}):Q(`div`,{className:`text-xs font-medium ${o}`,title:e.amountUsdDisplay,children:[`≈ `,e.amountUsdLocaleDisplay||e.amountUsdDisplay]})})]}):Q(hi,{children:[Q(`div`,{className:`flex min-w-0 items-center gap-3`,children:[Z(Jy,{imageUrl:e.tokenImageUrl,symbol:e.tokenSymbol,chainId:e.chainId||t,size:30}),Q(`div`,{className:`flex min-w-0 flex-col items-start`,children:[Q(`div`,{className:`flex items-center gap-1.5`,children:[Z(`span`,{className:`truncate text-sm font-semibold ${o}`,children:e.tokenSymbol}),a===`confirmation`&&bt(e.tokenAddress)&&Z(`span`,{className:`rounded-full bg-gray-100 px-1.5 py-0.5 text-[10px] font-medium text-gray-600 dark:bg-gray-800 dark:text-gray-300`,children:`Native gas`})]}),Z(`span`,{className:`truncate text-xs text-gray-500 dark:text-gray-400`,children:e.amountFormatted})]})]}),a===`insufficient`?Z(`span`,{className:`shrink-0 text-xs font-medium text-amber-600 dark:text-amber-400`,children:`Not enough`}):Q(`div`,{className:`flex shrink-0 items-center gap-3`,children:[Q(`span`,{className:`text-sm font-semibold trails-text-primary`,title:e.amountUsdDisplay,children:[`≈ `,e.amountUsdLocaleDisplay||e.amountUsdDisplay]}),Z(`span`,{className:`flex h-5 w-5 items-center justify-center rounded-full border transition-colors ${i?`border-blue-500 bg-blue-500 text-white`:`border-gray-300 dark:border-gray-600`}`,children:i&&Z(Ti,{className:`h-3 w-3`,strokeWidth:3})})]})]})},_b=({option:e,isSelected:t,onClick:n,chainId:r,originTokenInfo:i,variant:a=`compact`})=>{let o=a===`compact`&&!!i?.isLoadingBalance,s=a===`insufficient`||!o&&Bl(e,i),c=!!n&&!s&&!o,l=Z(gb,{option:e,isSelected:t,chainId:r,isDisabled:s,isLoading:o,variant:a});if(a===`insufficient`)return Z(`div`,{className:`flex w-full items-center justify-between gap-3 p-3 trails-border-radius-list-button border trails-bg-card trails-border-primary opacity-60`,children:l});let u=Z(`button`,{type:`button`,"aria-pressed":a===`confirmation`?t:void 0,className:`${a===`confirmation`?`group flex w-full items-center justify-between gap-3 p-3 trails-border-radius-list-button border transition-all duration-150`:`w-full flex items-center justify-between p-2 trails-border-radius-list-button transition-colors`} ${a===`confirmation`?s?`cursor-not-allowed opacity-50 trails-bg-card trails-border-primary`:t?`cursor-pointer border-blue-500 bg-blue-50 ring-1 ring-blue-500/30 shadow-sm dark:bg-blue-900/20`:`cursor-pointer trails-bg-card trails-border-primary hover:border-blue-300 hover:trails-hover-bg`:o?`border cursor-wait opacity-70 bg-gray-50 dark:bg-gray-800 border-gray-200 dark:border-gray-700`:s?`border cursor-not-allowed opacity-50 bg-gray-100 dark:bg-gray-800 border-gray-300 dark:border-gray-600`:c?t?`border cursor-pointer trails-bg-primary/10 border-blue-500 bg-blue-50 dark:bg-blue-900/20`:`border cursor-pointer trails-bg-card trails-border-primary hover:trails-hover-bg`:`cursor-default trails-bg-card`}`,onClick:c?n:void 0,disabled:s||!c,children:l});return o?Z(y,{message:`Loading balance...`,children:u}):s?Z(y,{message:`Not enough balance to use this fee option`,children:u}):u},vb=ur(null),yb=vb.Provider;function bb(){return hr(vb)||{}}const xb=({quote:e,thresholdBps:t,warningMessage:n,fallbackBridgeUrl:r})=>{if(!t||t<=0||!e?.priceImpact||!(Math.abs(Number(e.priceImpact))*100>t))return null;let i=`Price impact exceeds ${t/100}%. You may get a worse rate.`;return Z(`div`,{className:`mb-1 p-2 rounded-lg bg-amber-50 border border-amber-200 dark:bg-amber-900/20 dark:border-amber-800`,children:Q(`div`,{className:`flex items-start gap-2`,children:[Z(`svg`,{className:`w-4 h-4 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})}),Q(`div`,{className:`flex-1 min-w-0`,children:[Z(`p`,{className:`text-xs text-amber-700 dark:text-amber-300`,children:n||i}),r?.startsWith(`https`)&&Z(`div`,{className:`mt-1`,children:Z(y,{message:r,children:Q(`a`,{href:r,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-xs font-medium text-amber-800 dark:text-amber-200 hover:text-amber-900 dark:hover:text-amber-100 hover:underline cursor-pointer transition-colors`,children:[`Use alternative bridge`,Z(`svg`,{className:`w-3 h-3`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14`})})]})})})]})]})})};function Sb(e){if(!e)return!1;let t=e.state===`failed`||e.state===`aborted`,n=e.decodedGuestModuleEvents?.some(e=>e.type===`CallFailed`||e.type===`CallAborted`);return t||!!n}function Cb(e){return!!e?.some(e=>Sb(e))}const wb=({quote:e,onRampQuote:t,fiatToUsdExchangeRate:n,showContent:r=!0,children:i,onExpand:a,swapMode:o,compact:c=!1,isRefetching:l=!1,initialExpanded:u=!1,showInsufficientFunds:d=!0,isPassthrough:f=!1,liveTransactionStates:p,hasMetaTxError:m})=>{let[h,g]=X(!1),[_,v]=X(!0),[b,x]=X(u),[S,C]=X(u),w=Y(null),{trailsAppUrl:T}=Vx(),E=Y(null),D=bb(),O=Mg(e),k=t?.totalFee?t?.totalFee/(n??1):0;t&&s.console.log(`[trails-sdk] OnRamp Quote`,{onRampQuote:t}),q(()=>{a?.(b)},[b,a]),q(()=>{u!==S&&(C(u),x(u))},[u,S]);let A=K(()=>{if(!t||!e?.originTokenRate)return null;let n=t.exchangeRate;if(!n||e.originTokenRate===`0`)return null;let r=e.originTokenRate.match(/=\s*([\d.]+)/),i=r?parseFloat(r[1]):null;return i?{fiatToDestinationToken:i/n,fiatSymbol:t.sourceCurrencyCode,destSymbol:e.destinationToken?.symbol||`TOKEN`,fiatToUsdcRate:n}:null},[t,e]),{totalFeeUsd:j,totalFeeUsdDisplay:M,totalFeeUsdLocaleDisplay:N}=J(()=>{if(t){let t=k+parseFloat(e?.fees.totalFeeAmountUsd||`0`);return{totalFeeUsd:t,totalFeeUsdDisplay:Ks(t),totalFeeUsdLocaleDisplay:qs(t)}}if(e?.fees?.totalFeeAmountUsd){let t=parseFloat(e.fees.totalFeeAmountUsd);return{totalFeeUsd:t,totalFeeUsdDisplay:e.fees.totalFeeAmountUsdDisplay??Ks(t),totalFeeUsdLocaleDisplay:e.fees.totalFeeAmountUsdLocaleDisplay??qs(t)}}return{totalFeeUsd:0,totalFeeUsdDisplay:`$0.00`,totalFeeUsdLocaleDisplay:qs(0)}},[t,e?.fees,k]),P=K(()=>e?.slippageTolerance?parseFloat(e.slippageTolerance)*100:null,[e?.slippageTolerance]),F=J(()=>{let t=(e?.intentProtocol||le).replace(`_`,`.`).toUpperCase();return t.startsWith(`V`)?t:`V${t}`},[e?.intentProtocol]),I=K((t,n)=>{let r=e?.routeProviders?.length??e?.trailsFeeBreakdown?.providerFees?.length??0;return r>1?n===0?`Swap`:`Bridge`:r===1?e?.originChain?.id===e?.destinationChain?.id?`Swap`:`Bridge`:t.isBridge?`Bridge`:`Swap`},[e?.destinationChain?.id,e?.originChain?.id,e?.routeProviders?.length,e?.trailsFeeBreakdown?.providerFees?.length]);return r?Q(`div`,{className:`relative transition-opacity duration-300 ${l?`opacity-50`:``}`,children:[Z(xb,{quote:e,thresholdBps:D.thresholdBps,warningMessage:D.warningMessage,fallbackBridgeUrl:D.fallbackBridgeUrl}),d&&e?.noSufficientBalance&&Q(`div`,{className:`flex justify-between items-center mb-2 p-2 bg-amber-50 dark:bg-amber-900/20 rounded-lg`,children:[Q(`span`,{className:`text-xs text-amber-600 dark:text-amber-400 flex items-center gap-1`,children:[`Balance Status:`,Z(y,{message:`Your wallet does not have sufficient balance to complete this transaction`,children:Z(Vi,{className:`size-3 text-amber-500 dark:text-amber-400 cursor-pointer`})})]}),Q(`span`,{className:`font-medium text-xs text-amber-600 dark:text-amber-400 flex items-center gap-1`,children:[Z(ea,{className:`size-3`}),`Insufficient Balance`]})]}),Z(`div`,{className:`flex justify-center`,children:o?Q(`button`,{type:`button`,onClick:()=>x(!b),className:`w-full flex items-center justify-between px-2 py-2 trails-border-radius-button transition-colors cursor-pointer text-sm`,"aria-label":`Show more details`,children:[Z(`div`,{className:`font-semibold text-gray-900 dark:text-white flex items-center gap-2 whitespace-nowrap max-w-48 truncate`,children:(()=>{let n=A();if(n){let{fiatToDestinationToken:e,fiatSymbol:t,destSymbol:r}=n;return Q(`span`,{children:[`1 `,t,` = `,e.toFixed(6),` `,r]})}if(t?.exchangeRate){let e=t.sourceCurrencyCode,n=t.destinationCurrencyCode.split(`_`)[0];return Q(`span`,{children:[`1 `,e,` =`,` `,(1/t.exchangeRate).toFixed(6),` `,n]})}return e?.originTokenRate&&e.originTokenRate!==`0`?Z(`span`,{children:e.originTokenRate}):null})()}),Q(`div`,{className:`flex items-center gap-2 text-gray-600 dark:text-gray-400`,children:[e?.completionEstimateDisplay&&Q(`div`,{className:`flex items-center gap-1`,children:[Z(Mi,{className:`size-3`}),Q(`span`,{className:`font-medium`,children:[`~`,t?`3 min`:e.completionEstimateDisplay]})]}),j>0&&Q(`div`,{className:`flex items-center gap-1`,children:[Z(`svg`,{"aria-hidden":`true`,focusable:`false`,"data-prefix":`fas`,"data-icon":`gas-pump`,className:`svg-inline--fa fa-gas-pump`,role:`img`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 512 512`,width:`12`,children:Z(`path`,{fill:`currentColor`,d:`M32 64C32 28.7 60.7 0 96 0H256c35.3 0 64 28.7 64 64V256h8c48.6 0 88 39.4 88 88v32c0 13.3 10.7 24 24 24s24-10.7 24-24V222c-27.6-7.1-48-32.2-48-62V96L384 64c-8.8-8.8-8.8-23.2 0-32s23.2-8.8 32 0l77.3 77.3c12 12 18.7 28.3 18.7 45.3V168v24 32V376c0 39.8-32.2 72-72 72s-72-32.2-72-72V344c0-22.1-17.9-40-40-40h-8V448c17.7 0 32 14.3 32 32s-14.3 32-32 32H32c-17.7 0-32-14.3-32-32s14.3-32 32-32V64zM96 80v96c0 8.8 7.2 16 16 16H240c8.8 0 16-7.2 16-16V80c0-8.8-7.2-16-16-16H112c-8.8 0-16 7.2-16 16z`})}),Z(`span`,{className:`font-medium`,title:M,children:N})]}),Z(Di,{className:`size-3 transition-transform duration-300 ease-out text-gray-600 dark:text-gray-400 ${b?`rotate-180`:``}`})]})]}):Q(`button`,{type:`button`,onClick:()=>x(!b),className:`w-full max-w-md flex items-center ${c?`justify-center`:`justify-between`} gap-2 py-1 px-1 trails-border-radius-button transition-colors cursor-pointer text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300`,"aria-label":`Show transaction details`,children:[Z(`span`,{children:`Transaction details`}),Z(Di,{className:`size-3 transition-transform duration-300 ease-out ${b?`rotate-180`:``}`})]})}),Z(`div`,{ref:w,className:`overflow-auto transition-all duration-300 ease-out ${b?`max-h-[250px] opacity-100`:`max-h-0 opacity-0`}`,children:Z(`div`,{className:`text-sm p-2 space-y-2`,children:Q(`div`,{className:`space-y-2`,children:[e?.trailsFeeBreakdown&&(e?.trailsFeeBreakdown.originRelayFee||e?.trailsFeeBreakdown.destinationRelayFee)&&j>0&&Q(hi,{children:[Q(Db,{variant:`bold`,children:[Z(Ob,{tooltip:`The total fees for this transaction, including gas costs and all provider fees`,children:`Fees total`}),Z(kb,{children:Q(`span`,{className:`notranslate`,translate:`no`,title:`${j}`,children:[`≈`,` `,N||e?.fees?.totalFeeAmountUsdLocaleDisplay]})})]}),Z(`div`,{className:`h-0`}),(e.trailsFeeBreakdown.originRelayFee||e.trailsFeeBreakdown.destinationRelayFee)&&Q(Tb,{children:[Q(Db,{children:[Z(Ob,{tooltip:`Total gas costs for executing transactions on both origin and destination chains`,children:`All gas costs`}),Z(kb,{children:Z(`span`,{title:`$${e.totalGasUsd??0}`,children:e.totalGasUsdLocaleDisplay||e.totalGasUsdDisplay||`$0.00`})})]}),e.trailsFeeBreakdown.originRelayFee&&Q(Db,{variant:`light`,children:[Q(Ob,{tooltip:`Gas fee for executing the transaction on the origin chain`,children:[`Origin Gas`,Z(Ty,{chainId:e.originChain.id,size:16})]}),Z(kb,{children:Z(`span`,{title:`$${e.originGasUsd??0}`,children:e.originGasUsdLocaleDisplay||e.trailsFeeBreakdown.originRelayFee.usdValueLocale||e.trailsFeeBreakdown.originRelayFee.usdValue})})]}),e.trailsFeeBreakdown.destinationRelayFee&&Q(Db,{variant:`light`,children:[Q(Ob,{tooltip:`Gas fee for executing the transaction on the destination chain`,children:[`Destination Gas`,Z(Ty,{chainId:e.trailsFeeBreakdown.destinationRelayFee.chainId||e.destinationChain.id,size:16})]}),Z(kb,{children:Z(`span`,{title:`$${e.destinationGasUsd??0}`,children:e.destinationGasUsdLocaleDisplay||e.trailsFeeBreakdown.destinationRelayFee.usdValueLocale||e.trailsFeeBreakdown.destinationRelayFee.usdValue})})]})]}),Z(`div`,{className:`h-1`})]}),(()=>{let n=e?.trailsFeeBreakdown&&(e.providerFeeUsd??0)>0,r=e?.trailsFeeBreakdown&&(e.trailsFeeUsd??0)>0,i=t&&(t.totalFee??0)>0;return!n&&!r&&!i?null:Q(Tb,{children:[((e?.totalProviderFeesUsd??0)>0||i)&&Q(Db,{children:[Z(Ob,{tooltip:`Total provider fees for bridge, routing, and onramp services`,children:`All provider fees`}),Z(kb,{children:Z(`span`,{title:`$${e?(e?.totalProviderFeesUsd??0)+(k??0):k??0}`,children:qs(e?(e?.totalProviderFeesUsd??0)+(k??0):k)})})]}),n&&e?.trailsFeeBreakdown?.providerFees&&e.trailsFeeBreakdown.providerFees.length>0&&e.trailsFeeBreakdown.providerFees.map((e,t)=>Q(Db,{variant:`light`,children:[Q(Ob,{tooltip:`Fee charged by ${e.name||e.id}`,children:[I(e,t),e.name&&Q(`span`,{children:[` `,`(`,Q(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:`hover:underline inline-flex items-center gap-0.5 text-blue-500`,children:[e.name,Z(Li,{className:`size-3`})]}),`)`]})]}),Z(kb,{children:Z(`span`,{title:`$${e.feeUsd}`,children:e.usdValueLocale||e.usdValue})})]},`provider-fee-${e.id??e.name??t}`)),i&&Q(Db,{variant:`light`,children:[Q(Ob,{tooltip:`Fee charged by the onramp service provider, including network and transaction fees`,children:[`Onramp`,t.serviceProvider&&Q(`span`,{children:[`(`,t.serviceProvider,`)`]})]}),Z(kb,{children:Z(`span`,{title:`$${k??0}`,children:qs(k)})})]}),r&&e?.trailsFeeBreakdown?.trailsFee&&(()=>{let t=e.trailsFeeBreakdown.trailsFee;return Q(Db,{variant:`light`,children:[Z(Ob,{tooltip:`Platform fee for using the Trails service`,children:`Trails`}),Z(kb,{children:Z(`span`,{title:t.usdValue,children:t.usdValueLocale||t.usdValue})})]})})()]})})(),Z(`div`,{className:`h-px bg-gray-200 dark:bg-gray-800 my-4`}),(()=>{let t=e?.slippageTolerance!=null&&Number(e.slippageTolerance)!==0,n=e?.priceImpact!=null&&Number(e.priceImpact)!==0,r=e?.intentId!=null&&e.intentId!==``;return t||n||r?Q(Tb,{children:[Z(Db,{variant:`bold`,children:Z(Ob,{children:`Transaction details`})}),r&&Q(Db,{children:[Z(Ob,{children:`Intent ID`}),Z(kb,{children:Q(`a`,{href:`${T}/intent/${e.intentId}`,target:`_blank`,rel:`noopener noreferrer`,className:`font-mono text-xs hover:underline flex items-center gap-1 text-blue-500`,children:[wt(e?.intentId??``,9,3),Z(Li,{className:`size-3`})]})})]}),t&&Q(Db,{children:[Z(Ob,{tooltip:`The maximum percentage by which the exchange rate can change before the transaction fails. Higher slippage means more tolerance for price changes but potentially worse rates.`,children:`Max slippage`}),Q(kb,{children:[P(),`%`]})]}),n&&Q(`div`,{className:`space-y-1`,children:[Q(Db,{children:[Z(Ob,{tooltip:`The percentage change in the token price caused by your trade. Higher impact means your trade affects the market price more, potentially resulting in worse rates.`,children:`Price impact`}),Q(kb,{className:`flex items-center gap-1 ${Math.abs(Number(e.priceImpact))>5?`text-red-600 dark:text-red-400`:Math.abs(Number(e.priceImpact))>.5?`text-orange-600 dark:text-orange-400`:`text-gray-600 dark:text-gray-400`}`,children:[Math.abs(Number(e.priceImpact))>.5&&Z(`span`,{title:`High price impact`,children:Z(ea,{className:`size-3`})}),Number(e.priceImpact).toFixed(2),`%`]})]}),e.priceImpactUsdDisplay&&Z(`div`,{className:`text-right`,children:Q(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 notranslate`,translate:`no`,title:e.priceImpactUsdDisplay,children:[`≈`,` `,e.priceImpactUsdLocaleDisplay||e.priceImpactUsdDisplay]})})]})]}):null})(),Q(`div`,{className:`space-y-3 pt-2`,children:[!O&&(()=>{let n=A();if(n){let{fiatToDestinationToken:e,fiatSymbol:t,destSymbol:r}=n;return Q(Db,{children:[Z(Ob,{tooltip:`Combined exchange rate from ${t} to ${r} (via USDC on Base)`,children:`Exchange Rate`}),Z(kb,{children:Q(`button`,{type:`button`,onClick:()=>v(!_),className:`hover:underline cursor-pointer`,children:[`1 `,t,` = $`,e.toFixed(6),` $`,r,"`"]})})]})}if(t?.exchangeRate){let e=t.sourceCurrencyCode,n=t.destinationCurrencyCode.split(`_`)[0],r=t.exchangeRate;return Q(Db,{children:[Z(Ob,{tooltip:`Exchange rate from ${e} to ${n}`,children:`Exchange Rate`}),Q(kb,{children:[`1 `,e,` = $`,(1/r).toFixed(6),` $`,n]})]})}return e?.originTokenRate&&e?.destinationTokenRate&&e.originTokenRate!==`0`&&e.destinationTokenRate!==`0`?Q(Db,{children:[Z(Ob,{tooltip:`The current exchange rate between the origin and destination tokens`,children:`Exchange Rate`}),Z(kb,{children:Z(`button`,{type:`button`,onClick:()=>v(!_),className:`hover:underline cursor-pointer`,children:_?e.originTokenRate:e.destinationTokenRate})})]}):null})(),(e?.originAmount&&e?.originToken.symbol&&e?.originChain.id||e?.destinationToken.symbol&&e?.destinationAmount&&e?.destinationAmountUsdDisplay&&e?.destinationChain.id)&&Q(Tb,{children:[!O&&e?.originAmount&&e?.originToken.symbol&&e?.originChain.id&&Q(Db,{className:`items-start`,children:[Z(Ob,{tooltip:f?`The amount of tokens you will transfer`:`The amount of tokens you will send from the origin chain`,children:f?`Transfer Amount`:`Origin Transfer Amount`}),Z(`div`,{className:`text-right`,children:e.originToken.isNativeToken?Q(hi,{children:[Q(`div`,{className:`font-medium text-xs text-gray-600 dark:text-gray-400 flex items-center gap-1 justify-end`,children:[Z(Jy,{imageUrl:e.originToken.imageUrl,symbol:e.originToken.symbol,chainId:e.originChain.id,contractAddress:e.originToken.contractAddress,size:16}),Q(`span`,{className:`notranslate`,translate:`no`,children:[e.originAmountFormattedLocale||e.originAmountDisplay,` `,e.originToken.symbol]})]}),e.originAmountUsdDisplay&&Q(`div`,{className:`text-xs text-gray-500 dark:text-gray-400 mt-0.5 notranslate`,translate:`no`,title:e.originAmountUsdDisplay,children:[`≈`,` `,e.originAmountUsdLocaleDisplay||e.originAmountUsdDisplay]})]}):Q(hi,{children:[Z(`a`,{href:Za({address:e.originToken.contractAddress,chainId:e.originChain.id}),target:`_blank`,rel:`noopener noreferrer`,className:`hover:underline cursor-pointer`,children:Q(`div`,{className:`font-medium text-xs text-gray-600 dark:text-gray-400 flex items-center gap-1 justify-end`,children:[Z(Jy,{imageUrl:e.originToken.imageUrl,symbol:e.originToken.symbol,chainId:e.originChain.id,contractAddress:e.originToken.contractAddress,size:16}),e.originAmountFormattedLocale||e.originAmountDisplay,` `,e.originToken.symbol]})}),e.originAmountUsdDisplay&&Q(`div`,{className:`text-xs text-gray-500 dark:text-gray-400 mt-0.5 notranslate`,translate:`no`,title:e.originAmountUsdDisplay,children:[`≈`,` `,e.originAmountUsdLocaleDisplay||e.originAmountUsdDisplay]})]})})]}),e?.destinationToken.symbol&&e?.destinationAmount&&e?.destinationAmountUsdDisplay&&e?.destinationChain.id&&Q(Db,{className:`items-start`,children:[Z(Ob,{tooltip:f?`The amount of tokens the recipient will receive`:`The amount of tokens you will receive on the destination chain after the swap and/or bridge`,children:f?`Target Amount`:`Destination Target Amount`}),Z(`div`,{className:`text-right`,children:e.destinationToken.isNativeToken?Q(hi,{children:[Q(`div`,{className:`font-medium text-xs text-gray-600 dark:text-gray-400 flex items-center gap-1 justify-end`,children:[Z(Jy,{imageUrl:e.destinationToken.imageUrl,symbol:e.destinationToken.symbol,chainId:e.destinationChain.id,contractAddress:e.destinationToken.contractAddress,size:16}),Q(`span`,{className:`notranslate`,translate:`no`,children:[e.destinationAmountFormattedLocale||e.destinationAmountDisplay,` `,e.destinationToken.symbol]})]}),e.destinationAmountUsdDisplay&&Q(`div`,{className:`text-xs text-gray-500 dark:text-gray-400 mt-0.5 notranslate`,translate:`no`,title:e.destinationAmountUsdDisplay,children:[`≈`,` `,e.destinationAmountUsdLocaleDisplay||e.destinationAmountUsdDisplay]})]}):Q(hi,{children:[Z(`a`,{href:Za({address:e.destinationToken.contractAddress,chainId:e.destinationChain.id}),target:`_blank`,rel:`noopener noreferrer`,className:`hover:underline cursor-pointer`,children:Q(`div`,{className:`font-medium text-xs text-gray-600 dark:text-gray-400 flex items-center gap-1 justify-end`,children:[Z(Jy,{imageUrl:e.destinationToken.imageUrl,symbol:e.destinationToken.symbol,chainId:e.destinationChain.id,contractAddress:e.destinationToken.contractAddress,size:16}),e.destinationAmountFormattedLocale||e.destinationAmountDisplay,` `,e.destinationToken.symbol]})}),e.destinationAmountUsdDisplay&&Q(`div`,{className:`text-xs text-gray-500 dark:text-gray-400 mt-0.5 notranslate`,translate:`no`,title:e.destinationAmountUsdDisplay,children:[`≈`,` `,e.destinationAmountUsdLocaleDisplay||e.destinationAmountUsdDisplay]})]})})]})]}),(e?.originDepositAddress||e?.destinationDepositAddress||e?.destinationAddress)&&Z(Tb,{children:f?e?.destinationAddress&&Q(Db,{children:[Z(Ob,{tooltip:`The address that will receive the tokens`,children:`Target Address`}),Z(kb,{children:Q(`a`,{href:Za({address:e.destinationAddress,chainId:e.destinationChain.id}),target:`_blank`,rel:`noopener noreferrer`,className:`font-mono text-xs hover:underline flex items-center gap-1 text-blue-500`,children:[wt(e.destinationAddress),Z(Li,{className:`size-3`})]})})]}):Q(hi,{children:[e?.originDepositAddress&&Q(Db,{children:[Z(Ob,{tooltip:`This is the intent address to deposit to that will then execute the swap and/or bridge`,children:`Origin Deposit Address`}),Z(kb,{children:Q(`a`,{href:Za({address:e.originDepositAddress,chainId:e.originChain.id}),target:`_blank`,rel:`noopener noreferrer`,className:`font-mono text-xs hover:underline flex items-center gap-1 text-blue-500`,children:[wt(e.originDepositAddress),Z(Li,{className:`size-3`})]})})]}),e?.destinationDepositAddress&&e?.destinationDepositAddress!==e?.originDepositAddress&&Q(Db,{children:[Z(Ob,{tooltip:`This is the address that will receive the tokens after any swap and/or bridge from the origin chain`,children:`Destination Deposit Address`}),Z(kb,{children:Q(`a`,{href:Za({address:e.destinationDepositAddress,chainId:e.destinationChain.id}),target:`_blank`,rel:`noopener noreferrer`,className:`font-mono text-xs hover:underline flex items-center gap-1 text-blue-500`,children:[wt(e.destinationDepositAddress),Z(Li,{className:`size-3`})]})})]}),e?.destinationAddress&&Q(Db,{children:[Z(Ob,{tooltip:`This is the final execution address or recipient address`,children:`Destination Target Address`}),Z(kb,{children:Q(`a`,{href:Za({address:e.destinationAddress,chainId:e.destinationChain.id}),target:`_blank`,rel:`noopener noreferrer`,className:`font-mono text-xs hover:underline flex items-center gap-1 text-blue-500`,children:[wt(e.destinationAddress),Z(Li,{className:`size-3`})]})})]})]})}),e?.destinationCalldata&&Q(`div`,{className:`space-y-2`,children:[Z(`div`,{className:`space-y-0.5`,children:Q(`button`,{type:`button`,onClick:()=>{g(!h),h||setTimeout(()=>{E.current&&E.current.scrollIntoView({behavior:`smooth`,block:`nearest`})},150)},className:`flex items-center gap-1 text-xs hover:underline cursor-pointer transition-colors duration-200 text-gray-600 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300`,"aria-label":h?`Hide custom calldata`:`Show custom calldata`,children:[Z(`span`,{className:`text-[10px]`,children:`Includes custom destination calldata`}),Z(Di,{className:`size-3 transition-transform duration-300 ease-out ${h?`rotate-180`:``}`})]})}),Z(`div`,{ref:E,className:`overflow-hidden transition-all duration-300 ease-out ${h?`max-h-32 opacity-100`:`max-h-0 opacity-0`}`,children:Z(`div`,{className:`mt-2`,children:Z(`textarea`,{value:e.destinationCalldata,readOnly:!0,className:`w-full p-2 text-xs font-mono rounded border border-solid resize-none transition-all duration-200 bg-gray-100 dark:bg-gray-700 border-gray-300 dark:border-gray-600 text-gray-800 dark:text-gray-200`,rows:4,placeholder:`No custom calldata`})})})]}),(()=>{let t=p&&p.length>0,n=t?p:f&&e?.passthroughTransactionStates?.length?e.passthroughTransactionStates:e?.transactionStates;return!n||n.length===0?null:Q(`div`,{className:`mt-4`,children:[Z(`div`,{className:`h-px bg-gray-200 dark:bg-gray-800 mb-3`}),Q(Tb,{children:[Z(Db,{variant:`bold`,children:Z(Ob,{children:Q(`span`,{className:`flex items-center gap-2`,children:[t?`Transactions`:`Transaction Steps`,f&&Z(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded-full bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 font-medium`,children:`Direct`})]})})}),n.map((e,n)=>{let r=e,i=t&&tg(r.transactionHash),a=r.explorerUrl||(tg(r.transactionHash)&&r.chainId?Xa({txHash:r.transactionHash,chainId:r.chainId}):null),o=m&&t?m(r):!1;return Q(`div`,{className:`p-2 rounded ${t?`bg-gray-100 dark:bg-gray-700/50`:``}`,children:[Q(`div`,{className:`flex justify-between items-center`,children:[Q(`span`,{className:`flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400`,children:[!t&&Z(`span`,{className:`w-4 h-4 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center text-[10px] font-medium`,children:n+1}),e.label]}),Q(`span`,{className:`flex items-center gap-2`,children:[Z(Ty,{chainId:e.chainId,size:14}),t&&r.state&&Z(`span`,{className:`px-2 py-0.5 rounded-full text-xs ${Sb(r)?`bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-400`:r.state===`confirmed`?`bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-400`:`bg-yellow-100 text-yellow-700 dark:bg-yellow-900/50 dark:text-yellow-400`}`,children:r.state.charAt(0).toUpperCase()+r.state.slice(1)})]})]}),t&&i&&a&&Q(`div`,{className:`mt-1 flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Hash`}),Q(`a`,{href:a,target:`_blank`,rel:`noopener noreferrer`,className:`text-xs flex items-center gap-1 hover:underline text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300`,children:[o&&Q(`svg`,{className:`w-4 h-4 text-orange-500`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`An internal meta transaction failure occurred`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})]}),Z(`span`,{children:wt(r.transactionHash)}),Z(Li,{className:`w-3 h-3`})]})]})]},e.label||n)})]})]})})(),F.length>0&&Q(`div`,{className:`pt-1 text-[10px] opacity-50 text-gray-600 dark:text-gray-400`,children:[`Protocol version: `,F]}),i&&Z(`div`,{className:`mb-0`,children:i})]})]})})})]}):null},Tb=({children:e,className:t=``})=>Z(`div`,{className:`space-y-2 ${t}`,children:e}),Eb={default:`text-xs text-gray-600 dark:text-gray-400`,light:`text-xs text-gray-400 dark:text-gray-600`,bold:`text-sm font-semibold text-gray-900 dark:text-white`},Db=({children:e,className:t=``,variant:n=`default`})=>Z(`div`,{className:`flex justify-between items-center ${Eb[n]} ${t}`,children:e}),Ob=({children:e,tooltip:t,className:n=``})=>Q(`div`,{className:`flex items-center gap-1 ${n}`,children:[e,t&&Z(y,{message:t,children:Z(Vi,{className:`size-3 text-gray-500 dark:text-gray-400 cursor-pointer`})})]}),kb=({children:e,className:t})=>Z(`div`,{className:t,children:e}),Ab=[],jb=e=>`hasEnoughBalanceForFee`in e&&`balance`in e,Mb=e=>e?.contractAddress?wt(e.contractAddress):`Native Token`,Nb=({option:e,chainId:t,feeDisplay:n,isSelected:r=!1,isDisabled:i=!1,showRadio:a=!1,radioName:o=`feeOption`,onSelect:s})=>{let c=e=>{e?.stopPropagation(),!i&&s?.()};return Z(`div`,{className:`px-4 py-3 flex flex-col space-y-3 border border-gray-200 dark:border-gray-800 rounded-lg transition-all duration-200 ${i?`opacity-50 cursor-not-allowed bg-gray-50 dark:bg-gray-900/30`:`bg-white dark:bg-gray-900 hover:shadow-sm`}`,role:a?`radio`:void 0,tabIndex:a&&!i?0:void 0,"aria-disabled":i,onClick:a?c:void 0,onKeyDown:a?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),c())}:void 0,children:Q(`div`,{className:`flex items-start justify-between gap-3`,children:[Q(`div`,{className:`flex items-center space-x-3`,children:[Z(Jy,{symbol:e.token.symbol,imageUrl:e.token.logoURL,chainId:t,size:32}),Q(`div`,{className:`ml-2 text-left`,children:[Z(`div`,{className:`text-sm font-semibold`,children:e.token.symbol}),Z(`div`,{className:`text-xs trails-text-muted`,children:Mb(e.token)})]})]}),Q(`div`,{className:`flex items-center space-x-3`,children:[Q(`div`,{className:`text-right`,children:[Z(`div`,{className:`text-[10px] uppercase tracking-wide trails-text-muted`,children:`Fee to pay`}),Q(`div`,{className:`text-base font-semibold`,children:[n.feeAmountFormatted,` `,e.token.symbol]})]}),a&&Z(`input`,{type:`radio`,name:o,checked:r,disabled:i,onChange:c,className:`w-4 h-4 text-trails-primary focus:ring-trails-primary`})]})]})})},Pb=()=>Z(`div`,{className:`flex items-center justify-center py-8`,children:Z(`p`,{className:`text-sm trails-text-muted`,children:`Loading fee options...`})}),Fb=({chainId:e,originToken:t,originTokenAmount:n,setIsFeeOptionConfirmed:r,onFeeOptionsLoaded:i,setIsError:a,pendingFeeOptionConfirmation:o,confirmPendingFeeOption:c,rejectPendingFeeOption:l})=>{let[u,d]=X(),f=Y(void 0),p=Y(void 0),[m,h]=X(!1),[g,_]=X(!1),[v,b]=X(!1),x=o?.id,S=!!o&&(!o.options||o.options.length===0),C=o?.options??Ab,w=C.some(e=>jb(e)&&e.hasEnoughBalanceForFee),T=J(()=>t?.contractAddress?.toLowerCase()||null,[t?.contractAddress]),E=J(()=>{if(!n)return null;try{return BigInt(n)}catch(e){return s.console.error(`[trails-sdk] Failed to parse origin token amount for fee comparison`,{originTokenAmount:n,error:e}),null}},[n]),D=K(e=>{if(!t||!e?.token)return!1;let n=e.token.contractAddress?St(e.token.contractAddress):null;return T&&n?T===n:!1},[t,T]),O=K(e=>{if(!E||E<=0n||!D(e)||!e?.balance||!e?.value)return!1;try{return BigInt(e.balance)<BigInt(e.value)+E}catch(t){return s.console.error(`[trails-sdk] Failed to compare origin amount plus fee with balance`,{balance:e?.balance,value:e?.value,originAmount:n,error:t}),!1}},[D,E,n]),k=K(e=>{let t=e.token.decimals??18,n=e.value||`0`,r=`0`;try{r=Ws(vn(BigInt(n),t),{maxFractionDigits:Math.min(t,6),minFractionDigits:0})}catch(r){s.console.warn(`[trails-sdk] Failed to format fee option amount`,{error:r,value:n,decimals:t,token:e?.token?.symbol})}return{feeAmountFormatted:r}},[]),A=J(()=>{let e=C.filter(jb).filter(e=>e.hasEnoughBalanceForFee);return e.find(e=>!O(e))??e[0]},[C,O]),j=A?.token?.symbol;q(()=>{if(!x){f.current=void 0,p.current=void 0;return}f.current!==x&&(f.current=x,p.current=void 0,b(!1),r(!1),d(void 0))},[x,r]),q(()=>{x&&(s.console.log(`[trails-sdk] Pending fee options: `,C),A&&p.current!==x&&(p.current=x,i?.()),!u&&j&&d(j))},[x,C,A,j,i,u]),q(()=>{!x||S||w||a?.(!0)},[w,S,x,a]);let M=async e=>{if(o&&!g){_(!0);try{b(!0),r(!0),c(o.id,e)}finally{_(!1)}}},N=async()=>{if(o&&!g){_(!0);try{l(o.id)}finally{_(!1)}}};if(!o)return v?null:Z(Pb,{});if(S)return Z(Pb,{});let P=C.filter(jb).filter(e=>e.hasEnoughBalanceForFee).find(e=>e.token.symbol===u),F=P?k(P):null,I=P?O(P):!1;return w?Q(`div`,{className:`space-y-2`,children:[Q(`div`,{className:`flex items-center justify-between`,children:[Z(`div`,{className:`text-sm font-medium trails-text-primary`,children:`Select Fee Payment Token`}),Q(`button`,{type:`button`,onClick:()=>h(!m),className:`flex items-center space-x-1 text-xs trails-text-muted hover:trails-text-primary transition-colors cursor-pointer`,children:[Q(`span`,{children:[m?`Hide`:`Show`,` options`]}),Z(m?Ai:Di,{className:`w-3 h-3`})]})]}),P?.hasEnoughBalanceForFee&&F&&Z(Nb,{option:P,chainId:e,feeDisplay:F,isSelected:!0,isDisabled:I,showRadio:!1}),m&&Z(`div`,{className:`space-y-2`,children:C.filter(jb).filter(e=>e.hasEnoughBalanceForFee).map(t=>{let n=O(t),r=k(t);return n?Z(y,{message:`Not enough balance to cover sell amount and fee`,children:Z(Nb,{option:t,chainId:e,feeDisplay:r,isSelected:u===t.token.symbol,isDisabled:n,showRadio:!0,onSelect:()=>d(t.token.symbol)},t.token.symbol||t.token.contractAddress)},t.token.symbol):Z(Nb,{option:t,chainId:e,feeDisplay:r,isSelected:u===t.token.symbol,isDisabled:n,showRadio:!0,onSelect:()=>d(t.token.symbol)},t.token.symbol||t.token.contractAddress)})}),Q(`div`,{className:`flex flex-col space-y-3 sm:flex-row sm:space-y-0 sm:space-x-3`,children:[!I&&Z(`div`,{className:`flex-1`,children:Z(`button`,{type:`button`,onClick:()=>M(P?.token.contractAddress||null),disabled:!P||g,className:`w-full py-3 px-6 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-300 disabled:text-gray-500 text-white font-semibold rounded-lg transition-all duration-200 cursor-pointer disabled:cursor-not-allowed shadow-sm hover:shadow-md disabled:shadow-none flex items-center justify-center`,children:g?Q(hi,{children:[Z(`div`,{className:`animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2`}),`Processing...`]}):`Confirm Fee`})}),Z(`button`,{type:`button`,onClick:N,disabled:g,className:`px-6 py-3 bg-gray-100 hover:bg-gray-200 disabled:bg-gray-50 text-gray-700 font-semibold rounded-lg transition-all duration-200 cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 flex items-center justify-center border border-gray-300 ${I?`w-full sm:flex-1`:``}`,children:g?Q(hi,{children:[Z(`div`,{className:`animate-spin rounded-full h-4 w-4 border-b-2 border-gray-500 mr-2`}),`Processing...`]}):`Cancel`})]})]}):Q(`div`,{className:`space-y-4 py-6`,children:[Z(`div`,{className:`p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg`,children:Q(`div`,{className:`flex items-start space-x-2`,children:[Z(`svg`,{"aria-hidden":`true`,className:`w-5 h-5 text-red-600 dark:text-red-400 shrink-0 mt-0.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z`})}),Z(`p`,{className:`text-sm text-red-800 dark:text-red-200 font-medium`,children:`No available tokens for fees, please transfer any of these tokens to your wallet.`})]})}),Z(`div`,{className:`flex flex-col space-y-2`,children:C.map(t=>{let n=t.token.contractAddress;return Q(`div`,{className:`flex items-center space-x-3 p-3 trails-bg-secondary trails-border-radius-container border border-transparent`,children:[Z(`div`,{className:`flex items-center shrink-0`,children:Z(Jy,{symbol:t.token.symbol,imageUrl:t.token.logoURL,chainId:e,size:32})}),Q(`div`,{className:`flex-1 min-w-0 flex flex-col items-start`,children:[Z(`span`,{className:`text-sm font-bold trails-text-primary leading-tight`,children:t.token.symbol}),n?Q(`div`,{className:`flex items-center space-x-1.5 mt-0.5`,children:[Q(`span`,{className:`text-xs trails-text-muted leading-tight`,children:[n.slice(0,4),`...`,n.slice(-4)]}),Z(U,{text:n,stopPropagation:!0,className:`shrink-0 p-0.5`,size:`sm`})]}):Z(`span`,{className:`text-xs trails-text-muted mt-0.5 leading-tight`,children:`Native Token`})]})]},t.token.symbol||n)})})]})},Ib=()=>Z(`div`,{className:`space-y-4 py-6`,children:Z(`div`,{className:`p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg`,children:Q(`div`,{className:`flex items-start space-x-2`,children:[Z(`svg`,{"aria-hidden":`true`,className:`w-5 h-5 text-red-600 dark:text-red-400 shrink-0 mt-0.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z`})}),Q(`p`,{className:`text-sm text-red-800 dark:text-red-200 font-medium`,children:[`Sequence fee options require adapter-owned Sequence support. Pass the matching wagmi adapter through `,Z(`code`,{children:`config.adapters`}),` on`,Z(`code`,{children:`TrailsProvider`}),` or the `,Z(`code`,{children:`adapters`}),` prop on`,Z(`code`,{children:`TrailsWidget`}),`.`]})]})})}),Lb=e=>{let{sequenceSupport:t}=Vx(),n=t?.WaasFeeOptionsController,{chainId:r,setIsError:i}=e;return q(()=>{n||i?.(!0)},[n,i]),n?Z(n,{chainId:r,children:t=>Z(Fb,{...e,...t})}):Z(Ib,{})},Rb=({retryEnabled:e=!1,expiredQuoteEnabled:t=!1,onRetry:n,onBack:r,quote:i,onRampQuote:a,originToken:o,isQuoting:s=!1,awaitingFeeConfirmation:c=!1,feeOptions:l,selectedFeeOption:u,setSelectedFeeOption:d,onConfirmFeeOption:f,originTokenInfo:p})=>{let[m,h]=X(!1),[g,_]=X(!1),[v,y]=X(!1),[b,x]=X(!1),[S,C]=X(!1),{activeConnection:w}=Yr();q(()=>{x(!1),h(!0)},[]),q(()=>{if(_(!1),e||t)return;let n=setTimeout(()=>{_(!0)},2*ge);return()=>clearTimeout(n)},[t,e]);let T=w?.walletBehavior.isEmbeddedWallet??!1,E=Ll(w),D=i?.originToken??o??null,O=i?.originChain.id??D?.chainId,k=!!D?.symbol||!!D?.imageUrl,A=e||t,j=S||t,M=Hl({originChainId:O,feeOptions:l,walletRequiresFeeOptions:E}),N=M===`waas-fee-options`,P=!A&&!s,F=K(()=>{x(!0)},[]);if(c&&M===`sdk-selectable`&&P){let e=l??[],{selectedOptionDisabled:t,allOptionsDisabled:n}=Vl({feeOptions:e,selectedFeeOption:u,originTokenInfo:p}),o=r?Z(`button`,{type:`button`,onClick:r,className:`absolute left-0 p-2 rounded-full transition-colors cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800 hover:trails-hover-bg text-gray-600 dark:text-gray-400`,children:Z(Oi,{className:`h-5 w-5`})}):null;if(n)return Q(`div`,{className:`space-y-6`,children:[Z(`div`,{className:`relative flex items-center justify-center`,children:o}),Q(`div`,{className:`flex flex-col items-center text-center`,children:[Z(`div`,{className:`mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/20`,children:Z(ea,{className:`h-8 w-8 text-amber-500`})}),Z(`h2`,{className:`text-xl font-bold text-gray-900 dark:text-white`,children:`Insufficient balance for fees`}),Z(`p`,{className:`mt-2 text-sm text-gray-600 dark:text-gray-300`,children:`You don't have enough of any available token to cover the network fee for this transaction. Pick a different token or top up your wallet to continue.`})]}),e.length>0&&Q(`div`,{className:`space-y-2`,children:[Z(`div`,{className:`px-1 text-[11px] font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400`,children:`Fee options`}),Z(`div`,{className:`space-y-2`,children:e.map(e=>Z(_b,{option:e,isSelected:!1,chainId:e.chainId||O,variant:`insufficient`},e.tokenAddress))})]}),r&&Z(`button`,{type:`button`,onClick:r,className:`flex w-full items-center justify-center gap-2 px-4 py-3 trails-border-radius-button font-semibold text-white shadow-sm shadow-blue-500/20 transition-all duration-150 cursor-pointer bg-blue-500 hover:bg-blue-600 active:scale-[0.99] dark:bg-blue-600 dark:hover:bg-blue-700`,children:Z(`span`,{children:`Choose another token`})})]});let s=e=>{d?.(jl(e))};return Q(`div`,{className:`space-y-5`,children:[Z(`div`,{className:`relative flex items-center justify-center`,children:o}),Q(`div`,{className:`flex flex-col items-center text-center`,children:[k&&Z(`div`,{className:`mb-3 flex items-center justify-center`,children:Z(Jy,{imageUrl:D?.imageUrl,symbol:D?.symbol,chainId:O,contractAddress:D?.contractAddress,size:56})}),Z(`h2`,{className:`text-xl font-bold text-gray-900 dark:text-white`,children:`Review & confirm`}),Z(`p`,{className:`mt-1 text-sm text-gray-600 dark:text-gray-300`,children:`Choose which token to pay the gas fee with`})]}),Q(`div`,{className:`space-y-2`,children:[Z(`div`,{className:`px-1 text-[11px] font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400`,children:`Pay gas with`}),Z(`div`,{className:`space-y-2`,children:e.map(e=>Z(_b,{option:e,isSelected:Ml(e,u),onClick:()=>s(e),chainId:e.chainId||O,originTokenInfo:p,variant:`confirmation`},e.tokenAddress))})]}),Z(wb,{quote:i,onRampQuote:a,showContent:!0,compact:!0}),Z(`button`,{type:`button`,onClick:f,disabled:t,className:`flex w-full items-center justify-center gap-2 px-4 py-3 trails-border-radius-button font-semibold text-white shadow-sm transition-all duration-150 ${t?`cursor-not-allowed bg-gray-300 text-gray-500 shadow-none dark:bg-gray-700 dark:text-gray-400`:`cursor-pointer bg-blue-500 shadow-blue-500/20 hover:bg-blue-600 active:scale-[0.99] dark:bg-blue-600 dark:hover:bg-blue-700`}`,children:Z(`span`,{children:t?`Insufficient balance`:`Confirm`})})]})}return Q(`div`,{className:`space-y-6`,children:[Z(`div`,{className:`flex items-center relative`,children:Z(`button`,{type:`button`,onClick:r,className:`absolute left-0 top-0 p-2 rounded-full transition-colors cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800 hover:trails-hover-bg text-gray-600 dark:text-gray-400`,children:Z(Oi,{className:`h-6 w-6`})})}),Q(`div`,{className:`flex flex-col justify-center min-h-full space-y-6 pt-8`,children:[Q(`div`,{className:`text-center`,children:[Q(`div`,{className:`mx-auto flex items-center justify-center transition-all duration-500 ease-out relative mb-4 ${m?`transform -translate-y-8`:``}`,children:[t?Z(`div`,{className:`flex items-center justify-center h-24 w-24`,children:Z(ea,{className:`h-16 w-16 text-amber-500`})}):S?Z(hb,{}):e?Z(`div`,{className:`h-24 w-24`}):Z(`div`,{className:`animate-spin rounded-full h-24 w-24 border-solid border-b-2 border-blue-500 dark:border-blue-400`}),!j&&k&&Z(`div`,{className:`absolute`,children:Z(Jy,{imageUrl:D?.imageUrl,symbol:D?.symbol,chainId:O,contractAddress:D?.contractAddress,size:64})})]}),Q(`div`,{className:`mb-2 transition-all duration-500 ease-out ${m?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:[Z(`h2`,{className:`text-xl font-bold text-gray-900 dark:text-white`,children:t?`Quote expired`:e?`Try again`:s?`Quoting intent…`:N?v?`Waiting for wallet…`:b?`Waiting for fee selection…`:S?`No fee token found`:`Waiting for fee options…`:`Waiting for wallet…`}),Z(`p`,{className:`mt-2 text-sm text-gray-600 dark:text-gray-300`,children:t?`This quote took too long and is no longer valid. Go back to fetch a fresh quote.`:s?`Preparing the best route...`:(!N||v)&&!T?`Please approve the request in your wallet`:``})]}),N&&P&&Z(`div`,{className:`mb-2 mt-4 transition-all duration-500 ease-out ${m?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:Z(Lb,{chainId:i?.originChain.id,originTokenAmount:i?.originAmount,originToken:i?.originToken,setIsFeeOptionConfirmed:y,setIsError:C,onFeeOptionsLoaded:F})})]}),g&&Z(`div`,{className:`transition-all duration-500 ease-out delay-150 ${m?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:Z(`div`,{className:`p-4 trails-border-radius-container text-sm bg-yellow-50 border border-solid border-yellow-200 dark:bg-yellow-900/20 dark:border-yellow-700/50`,children:Q(`div`,{className:`flex items-start space-x-3`,children:[Q(`svg`,{className:`w-5 h-5 mt-0.5 shrink-0 text-yellow-600 dark:text-yellow-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`Warning`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})]}),Q(`div`,{children:[Z(`p`,{className:`font-medium text-yellow-800 dark:text-yellow-300`,children:`Request is taking longer than expected`}),Z(`p`,{className:`mt-1 text-xs text-yellow-700 dark:text-yellow-400`,children:`This transaction request is taking longer than expected. Please reach out to support for help if the issue persists.`})]})]})})}),t&&r&&Z(`div`,{className:`mb-2 transition-all duration-500 ease-out delay-300 ${m?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:Z(`button`,{type:`button`,onClick:r,className:`w-full px-4 py-2 trails-border-radius-button font-medium transition-colors cursor-pointer bg-blue-500 hover:bg-blue-600 text-white dark:bg-blue-600 dark:hover:bg-blue-700`,children:`Go back`})}),e&&n&&Z(`div`,{className:`mb-2 transition-all duration-500 ease-out delay-300 ${m?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:Z(`button`,{type:`button`,onClick:n,className:`w-full px-4 py-2 trails-border-radius-button font-medium transition-colors cursor-pointer bg-blue-500 hover:bg-blue-600 text-white dark:bg-blue-600 dark:hover:bg-blue-700`,children:`Try Again`})}),!s&&Z(wb,{quote:i,onRampQuote:a,showContent:!0,compact:!0})]})]})},zb=({depositConfirmedAt:e,estimatedDurationSeconds:t,showContent:n=!0})=>{let r=Number.isFinite(t)&&t>0,i=r?t:0,a=i*1e3,[o,s]=X(0),[c,l]=X(Math.ceil(i/60));return q(()=>{if(!r){s(0),l(0);return}let t=()=>{let t=Date.now()-e,n=Math.min(t/a*100,100),r=Math.max(0,Math.ceil((a-t)/6e4));s(n),l(r)};t();let n=setInterval(t,1e3);return()=>clearInterval(n)},[e,r,a]),r?Q(`div`,{className:`w-full max-w-sm transition-all duration-500 ease-out mt-4 ${n?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:[Q(`div`,{className:`flex justify-between text-sm text-gray-600 dark:text-gray-400 mb-2`,children:[Z(`span`,{children:`Bridging via LayerZero`}),Z(`span`,{children:c>0?`${c} min remaining`:`completing soon`})]}),Z(`div`,{className:`w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden`,children:Z(`div`,{className:`h-full bg-blue-500 dark:bg-blue-400 transition-all duration-1000`,style:{width:`${o}%`}})}),Q(`p`,{className:`text-xs text-gray-500 dark:text-gray-400 mt-2 text-center`,children:[`LayerZero OFT transfers typically complete in about`,` `,Ce(i)]})]}):null},Bb=({quote:e,timestamp:t})=>Z(`div`,{className:`w-full max-w-sm p-3 trails-border-radius-container trails-bg-secondary trails-text-secondary`,children:Q(`div`,{className:`flex items-start justify-between`,children:[Z(`div`,{className:`flex items-start space-x-2`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Z(`div`,{style:{width:`24px`,height:`24px`},children:Z(Jy,{imageUrl:e.originToken.imageUrl,symbol:e.originToken.symbol,chainId:e.originChain.id,size:24})}),Q(`div`,{className:`flex flex-col`,children:[Z(`span`,{className:`text-xs font-medium text-left text-gray-900 dark:text-white`,children:e.originToken.name}),Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 flex items-center`,children:we(t)})]})]})}),Q(`div`,{className:`text-right`,children:[Z(`div`,{className:`text-xs font-medium text-right text-gray-900 dark:text-white`,children:e.originAmountUsdDisplay}),Q(`div`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:[e.originAmountFormatted,` `,e.originToken.symbol]})]})]})}),Vb=({quote:e,elapsedSeconds:t})=>Z(`div`,{className:`w-full max-w-sm p-3 flex justify-center`,children:Q(`div`,{className:`flex items-center space-x-4`,children:[Q(`div`,{className:`flex flex-col items-start space-y-1`,children:[Z(`div`,{style:{width:`28px`,height:`28px`},children:Z(Jy,{imageUrl:e.originToken.imageUrl,symbol:e.originToken.symbol,chainId:e.originChain.id,size:28})}),Q(`div`,{className:`text-left`,children:[Z(`div`,{className:`text-base font-bold text-gray-900 dark:text-white`,children:e.originToken.symbol}),Z(`div`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:e.originAmountFormatted})]})]}),Q(`div`,{className:`flex flex-col items-center space-y-1`,children:[Z(`div`,{className:`text-xl text-gray-400 dark:text-gray-500`,children:`→`}),Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:Ce(t)})]}),Q(`div`,{className:`flex flex-col items-start space-y-1`,children:[Z(`div`,{style:{width:`28px`,height:`28px`},children:Z(Jy,{imageUrl:e.destinationToken.imageUrl,symbol:e.destinationToken.symbol,chainId:e.destinationChain.id,size:28})}),Q(`div`,{className:`text-left`,children:[Z(`div`,{className:`text-base font-bold text-gray-900 dark:text-white`,children:e.destinationToken.symbol}),Z(`div`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:e.destinationAmountFormatted})]})]})]})}),Hb=e=>e?.length?e.some(e=>e.id===`LZ_OFT`):!1,Ub=e=>e?.length?e.some(e=>e.id===`HYPERLANE`):!1,Wb=60*ge,Gb=ge,Kb=3*ge,qb=2*ge,Jb=3*ge,Yb=()=>Q(`svg`,{width:`12`,height:`12`,viewBox:`0 0 12 12`,fill:`none`,children:[Z(`title`,{children:`Completed`}),Z(`path`,{d:`M2.5 6L5 8.5L9.5 4`,stroke:`white`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`animate-draw`})]}),Xb=()=>Q(`svg`,{width:`12`,height:`12`,viewBox:`0 0 12 12`,fill:`none`,children:[Z(`title`,{children:`Failed`}),Z(`path`,{d:`M3 3L9 9M9 3L3 9`,stroke:`white`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`animate-draw`})]}),Zb=()=>Q(`svg`,{className:`w-4 h-4 text-white`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`An internal meta tx failure occurred`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})]}),Qb=()=>Q(`svg`,{width:`12`,height:`12`,viewBox:`0 0 12 12`,fill:`none`,className:`animate-spin`,children:[Z(`title`,{children:`Processing`}),Z(`circle`,{cx:`6`,cy:`6`,r:`4`,stroke:`white`,strokeWidth:`2`,strokeLinecap:`round`,strokeDasharray:`6 6`,strokeDashoffset:`0`})]}),$b=({onElapsedTime:e,transactionStates:t,quote:n,onRampQuote:r,timestamp:i,onContinue:a,fundMethod:o})=>{let{mode:s}=y_(),[c,l]=X(!1),[u,d]=X(!1),[f,p]=X(!1),[m,h]=X(!1),[g,_]=X(0),[v,y]=X(null),b=Hb(n?.routeProviders),x=Ub(n?.routeProviders),S=n?.originChain?.id===Kn.id,C=Cb(t)&&a;q(()=>{let e=setTimeout(()=>{h(!0)},o===`onramp-mesh`?Jb:b?Wb:x?Kb:S?qb:Gb);return()=>clearTimeout(e)},[o,x,S,b]),q(()=>{let e=t?.[0]?.state===`confirmed`;b&&e&&!v&&y(Date.now())},[t,b,v]),q(()=>{let e=setTimeout(()=>{l(!0)},200);return()=>clearTimeout(e)},[]),q(()=>{let e=setTimeout(()=>{d(!0)},400),t=setTimeout(()=>{p(!0)},800);return()=>{clearTimeout(e),clearTimeout(t)}},[]);let[w,T]=X(-1);q(()=>{let e=t.findIndex(e=>e.state===`pending`);e!==w&&(T(e),_(0))},[t,w]),q(()=>{let e=document.createElement(`style`);return e.textContent=`
2
+ @keyframes draw {
3
+ from {
4
+ stroke-dasharray: 0 100;
5
+ }
6
+ to {
7
+ stroke-dasharray: 100 0;
8
+ }
9
+ }
10
+
11
+ .animate-draw {
12
+ animation: draw 0.6s ease-out forwards;
13
+ }
14
+
15
+ @keyframes slideInFromTop {
16
+ from {
17
+ transform: translateY(-20px);
18
+ }
19
+ to {
20
+ transform: translateY(0);
21
+ }
22
+ }
23
+
24
+ @keyframes lineGrow {
25
+ from {
26
+ height: 0;
27
+ }
28
+ to {
29
+ height: 100%;
30
+ }
31
+ }
32
+
33
+ .animate-slide-in {
34
+ animation: slideInFromTop 0.3s ease-out forwards;
35
+ }
36
+
37
+ .animate-line-grow {
38
+ animation: lineGrow 0.6s ease-out forwards;
39
+ }
40
+ `,document.head.appendChild(e),()=>{document.head.removeChild(e)}},[]);let[E,D]=X(0);q(()=>{let e=setInterval(()=>{D(e=>e+1)},1e3);return()=>clearInterval(e)},[]),q(()=>{if(w>=0){let e=setInterval(()=>{_(e=>e+1)},1e3);return()=>clearInterval(e)}},[w]),q(()=>{e(E)},[e,E]);let O=[],k=!1;for(let e of t)k||e.state!==`confirmed`?(k=!0,O.push({...e,state:e.state===`confirmed`?`pending`:e.state})):O.push(e);let A=(e,n)=>{let r=n===w,i=e.state===`confirmed`,a=Sb(e),o=Ng(e),s=t.slice(0,n).some(e=>Sb(e)),c;c=a?`failed`:i?`completed`:r&&!s?`active`:`pending`;let l=Q(`div`,{className:`flex items-start space-x-4`,children:[Z(`div`,{className:`flex-shrink-0`,children:Q(`div`,{className:(()=>{let e=`w-5 h-5 rounded-full flex items-center justify-center transition-all duration-500 ease-out`;switch(c){case`completed`:return o?`${e} bg-orange-500 scale-100`:`${e} bg-green-600 dark:bg-green-500 scale-100`;case`active`:return`${e} bg-blue-600 dark:bg-blue-500 scale-110`;case`failed`:return`${e} bg-red-600 dark:bg-red-500 scale-100`;case`pending`:return`${e} bg-gray-300 dark:bg-gray-600 scale-100`}})(),children:[c===`completed`&&!o&&Z(Yb,{}),c===`completed`&&o&&Z(Zb,{}),c===`failed`&&Z(Xb,{}),c===`active`&&Z(Qb,{})]})}),Z(`div`,{className:`flex-1 min-w-0`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Z(`span`,{className:`text-sm font-medium transition-all duration-500 ease-out text-gray-900 dark:text-white`,children:e.label}),c===`completed`?Z(Li,{className:`w-4 h-4 text-gray-400 transition-opacity duration-300`}):c===`active`?Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 font-mono animate-pulse mt-1`,title:`Elapsed time`,children:Ce(g)}):Z(`div`,{className:`w-4 h-4`})]})})]});return c===`completed`||c===`failed`?Z(`a`,{href:e.explorerUrl,target:`_blank`,rel:`noopener noreferrer`,className:`block hover:opacity-80 transition-all duration-300 ease-out`,children:l}):Z(`div`,{className:`block`,children:l})};return Q(`div`,{className:`space-y-2 flex flex-col items-center justify-center py-8`,children:[Z(`div`,{className:`w-full max-w-sm transition-all duration-500 ease-out ${c?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:Z(M_,{headerContent:s===`swap`?`Swap in progress`:`Transaction Status`,headerContentAlign:`center`})}),n&&Z(`div`,{className:`w-full max-w-sm transition-all duration-500 ease-out delay-100 ${c?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:s===`swap`?Z(Vb,{quote:n,elapsedSeconds:E}):Z(Bb,{quote:n,timestamp:i})}),Z(`div`,{className:`mb-2 w-full mx-auto`,style:{width:`auto`},children:Q(`div`,{className:`relative`,children:[Z(`div`,{className:`absolute left-2.5 top-5 bottom-5 w-0.5 transition-all duration-500 ease-out bg-gray-300 dark:bg-gray-700 ${f?`animate-line-grow`:`h-0`}`}),w>0&&f&&Z(`div`,{className:`absolute left-2.5 top-5 w-0.5 bg-green-500 transition-all duration-1000 ease-out`,style:{height:`${(()=>{let e=-1;for(let n=0;n<t.length;n++){let r=t[n];if(r&&r.state===`confirmed`&&!Sb(r))e=n;else if(Sb(r))break}return e>=0?e/(t.length-1)*80:0})()}%`,maxHeight:`calc(100% - 20px)`}}),Z(`div`,{className:`space-y-6 mt-4`,children:O.map((e,t)=>Z(`div`,{className:`relative transition-all duration-300 ease-out`,style:{transitionDelay:u?`${t*100}ms`:`0ms`,transform:u?`translateY(0)`:`translateY(-20px)`,visibility:u?`visible`:`hidden`},children:A(e,t)},e.id))})]})}),b&&v&&n?.completionEstimateSeconds!=null&&Z(zb,{depositConfirmedAt:v,estimatedDurationSeconds:n.completionEstimateSeconds,showContent:c}),C&&Z(`div`,{className:`w-full max-w-sm transition-all duration-500 ease-out delay-150 mt-4 flex justify-center ${c?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:Q(`button`,{type:`button`,onClick:a,className:`inline-flex items-center gap-1 px-4 py-2 trails-border-radius-button font-medium transition-colors cursor-pointer bg-blue-500 hover:bg-blue-600 text-white dark:bg-blue-600 dark:hover:bg-blue-700`,children:[`Continue`,Z(ki,{className:`w-4 h-4`})]})}),n&&Z(`div`,{className:`w-full max-w-sm transition-all duration-500 ease-out delay-200 ${c?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:Z(`div`,{className:`mt-4`,children:Z(wb,{quote:n,onRampQuote:r,showContent:!0,compact:!0,liveTransactionStates:t,hasMetaTxError:Ng})})}),m&&!C&&Z(`div`,{className:`w-full max-w-sm transition-all duration-500 ease-out delay-250 ${c?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:Z(`div`,{className:`p-4 trails-border-radius-container text-sm bg-yellow-50 border border-solid border-yellow-200 dark:bg-yellow-900/20 dark:border-yellow-700/50`,children:Q(`div`,{className:`flex items-start space-x-3`,children:[Q(`svg`,{className:`w-5 h-5 mt-0.5 flex-shrink-0 text-yellow-600 dark:text-yellow-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`Warning`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})]}),Q(`div`,{children:[Z(`p`,{className:`font-medium text-yellow-800 dark:text-yellow-300`,children:`Transaction taking longer than expected`}),Q(`p`,{className:`mt-1 text-xs text-yellow-700 dark:text-yellow-400`,children:[`This transaction is taking longer than expected.`,` `,Z(`a`,{href:`https://support.trails.build/`,target:`_blank`,rel:`noopener noreferrer`,className:`text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline`,children:`Visit support`}),` `,`for help if the issue persists.`]})]})]})})})]})};function ex(e){return e.filter(e=>{try{return BigInt(e.balance||`0`)>0n}catch{return!1}}).map(e=>({chainId:e.chainId,contractAddress:e.contractAddress,symbol:e.symbol,decimals:e.decimals,rawBalance:e.balance,formattedBalance:Xs(e.balance,e.decimals)}))}function tx({intentId:e,ownerAddress:t,enabled:n=!0}){let r=Vx(),i=gs(),{data:a,isLoading:o,error:c,refetch:l}=Or({queryKey:[`receiptIntentBalances`,e,t],enabled:n&&!!e&&!!t&&!!r.trailsApiKey&&!!r.trailsApiUrl,queryFn:async()=>{let n=await i.getIntentHistory({byOwnerAddress:t,includeBalances:!0,page:{pageSize:5}}),r=e?.toLowerCase(),a=(n.intents||[]).find(e=>e.intentId?.toLowerCase()===r);return a?(s.console.log(`[trails-sdk] receipt balance intent match`,{intentId:e,hasBalance:a.hasBalance,balanceGroupCount:(a.balances||[]).length}),{hasBalance:!!a.hasBalance,balances:a.balances||[]}):{hasBalance:!1,balances:[]}},staleTime:0,gcTime:600*1e3,refetchInterval:e=>e.state.dataUpdateCount>=5?!1:3e4,refetchIntervalInBackground:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,refetchOnMount:!1}),u=J(()=>{let e=a?.balances||[];return e.length===0?[]:e.map(e=>({intentAddress:e.intentAddress,chainId:e.chainId,tokens:ex(e.tokens||[])})).filter(e=>e.tokens.length>0)},[a?.balances]);return{chainGroups:u,hasRecoverableFunds:(a?.hasBalance??!1)&&u.length>0,isLoading:o,error:c||null,refetch:async()=>{await l()}}}function nx(){let[e,t]=X(!1);q(()=>{let e=setTimeout(()=>{t(!0)},100);return()=>clearTimeout(e)},[]);let n={container:{width:`80px`,height:`80px`,position:`relative`},circleContainer:{position:`relative`,width:`100%`,height:`100%`},circleFill:{position:`absolute`,top:0,left:0,width:`100%`,height:`100%`,borderRadius:`50%`,backgroundColor:`#22c55e`,transform:e?`scale(1)`:`scale(0)`,opacity:+!!e,transition:`transform 0.15s ease-out 0.3s, opacity 0.15s ease-out 0.3s`},progressRing:{position:`absolute`,top:0,left:0,width:`100%`,height:`100%`,transform:`rotate(-90deg)`},circle:{fill:`none`,stroke:`url(#gradient)`,strokeWidth:4,strokeLinecap:`round`,strokeDasharray:226,strokeDashoffset:e?0:226,transition:`stroke-dashoffset 0.3s ease-out`},checkmarkContainer:{position:`absolute`,top:`50%`,left:`50%`,transform:e?`translate(-50%, -50%) scale(1)`:`translate(-50%, -50%) scale(0)`,opacity:+!!e,zIndex:10,transition:`transform 0.1s ease-out 0.4s, opacity 0.1s ease-out 0.4s`},checkmarkPath:{fill:`none`,stroke:`white`,strokeWidth:4,strokeLinecap:`round`,strokeLinejoin:`round`,strokeDasharray:18,strokeDashoffset:e?0:18,transition:`stroke-dashoffset 0.15s ease-out 0.45s`}};return Z(`div`,{style:n.container,children:Q(`div`,{style:n.circleContainer,children:[Z(`div`,{style:n.circleFill}),Q(`svg`,{"aria-hidden":`true`,style:n.progressRing,children:[Z(`defs`,{children:Q(`radialGradient`,{id:`gradient`,cx:`50%`,cy:`50%`,r:`50%`,gradientUnits:`objectBoundingBox`,children:[Z(`stop`,{offset:`0%`,style:{stopColor:`#22c55e`,stopOpacity:0}}),Z(`stop`,{offset:`70%`,style:{stopColor:`#22c55e`,stopOpacity:.3}}),Z(`stop`,{offset:`100%`,style:{stopColor:`#22c55e`,stopOpacity:1}})]})}),Z(`circle`,{cx:`40`,cy:`40`,r:`36`,style:n.circle})]}),Z(`div`,{style:n.checkmarkContainer,children:Z(`svg`,{"aria-hidden":`true`,width:`48`,height:`48`,viewBox:`0 0 24 24`,children:Z(`path`,{d:`M6 14l4 4L18 8`,style:n.checkmarkPath})})})]})})}const rx=({hasRecoverableFunds:e,chainGroups:t,isLoading:n=!1,error:r=null,trailsIntentUrl:i,onRefresh:a})=>n?null:r?Q(`div`,{className:`rounded-xl bg-gray-100 dark:bg-gray-800 p-3`,children:[Z(`p`,{className:`text-sm text-gray-600 dark:text-gray-400`,children:`Could not verify remaining funds right now.`}),a&&Z(`button`,{type:`button`,onClick:a,className:`mt-2 text-sm font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 cursor-pointer`,children:`Retry`})]}):!e||t.length===0?null:Z(`div`,{className:`rounded-xl bg-warning p-[1px]`,children:Q(`div`,{className:`rounded-xl bg-background-overlay p-4`,children:[Q(`div`,{className:`flex items-center justify-between gap-3`,children:[Z(`h3`,{className:`text-sm font-semibold text-gray-900 dark:text-white`,children:`Funds available to recover`}),i&&Q(`a`,{href:i,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-xs font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300`,children:[`Recover`,Q(`svg`,{className:`w-3 h-3 text-blue-600 dark:text-blue-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,children:[Z(`title`,{children:`External Link`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14`})]})]})]}),Z(`div`,{className:`mt-3 space-y-3`,children:t.map(e=>{let t=$(e.chainId)?.name||`Unknown`;return Q(`div`,{children:[Q(`div`,{className:`mb-2 flex items-center gap-2`,children:[Z(Ty,{chainId:e.chainId,size:14}),Z(`span`,{className:`text-xs font-medium text-gray-700 dark:text-gray-300`,children:t})]}),Z(`div`,{className:`space-y-1`,children:e.tokens.map(e=>Q(`div`,{className:`flex items-center justify-between rounded-lg bg-gray-100 dark:bg-gray-800 px-2 py-1.5`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400 truncate`,children:e.symbol}),Z(`span`,{className:`text-xs font-medium text-gray-900 dark:text-white`,children:e.formattedBalance})]},`${e.chainId}-${e.contractAddress}`))})]},`${e.intentAddress}-${e.chainId}`)})})]})});function ix(){let[e,t]=X(!1);q(()=>{let e=setTimeout(()=>{t(!0)},100);return()=>clearTimeout(e)},[]);let n={container:{width:`80px`,height:`80px`,position:`relative`},circleContainer:{position:`relative`,width:`100%`,height:`100%`},circleFill:{position:`absolute`,top:0,left:0,width:`100%`,height:`100%`,borderRadius:`50%`,backgroundColor:`#f59e0b`,transform:e?`scale(1)`:`scale(0)`,opacity:+!!e,transition:`transform 0.15s ease-out 0.3s, opacity 0.15s ease-out 0.3s`},progressRing:{position:`absolute`,top:0,left:0,width:`100%`,height:`100%`,transform:`rotate(-90deg)`},circle:{fill:`none`,stroke:`url(#yellowGradient)`,strokeWidth:4,strokeLinecap:`round`,strokeDasharray:226,strokeDashoffset:e?0:226,transition:`stroke-dashoffset 0.3s ease-out`},iconContainer:{position:`absolute`,top:`50%`,left:`50%`,transform:e?`translate(-50%, -50%) scale(1)`:`translate(-50%, -50%) scale(0)`,opacity:+!!e,zIndex:10,transition:`transform 0.1s ease-out 0.4s, opacity 0.1s ease-out 0.4s`},trianglePath:{fill:`none`,stroke:`white`,strokeWidth:2.5,strokeLinecap:`round`,strokeLinejoin:`round`,strokeDasharray:120,strokeDashoffset:e?0:120,transition:`stroke-dashoffset 0.2s ease-out 0.45s`},exclamationPath:{fill:`none`,stroke:`white`,strokeWidth:2.5,strokeLinecap:`round`,strokeLinejoin:`round`,strokeDasharray:20,strokeDashoffset:e?0:20,transition:`stroke-dashoffset 0.15s ease-out 0.55s`},dot:{fill:`white`,opacity:+!!e,transition:`opacity 0.1s ease-out 0.65s`}};return Z(`div`,{style:n.container,children:Q(`div`,{style:n.circleContainer,children:[Z(`div`,{style:n.circleFill}),Q(`svg`,{"aria-hidden":`true`,style:n.progressRing,children:[Z(`defs`,{children:Q(`radialGradient`,{id:`yellowGradient`,cx:`50%`,cy:`50%`,r:`50%`,gradientUnits:`objectBoundingBox`,children:[Z(`stop`,{offset:`0%`,style:{stopColor:`#f59e0b`,stopOpacity:0}}),Z(`stop`,{offset:`70%`,style:{stopColor:`#f59e0b`,stopOpacity:.3}}),Z(`stop`,{offset:`100%`,style:{stopColor:`#f59e0b`,stopOpacity:1}})]})}),Z(`circle`,{cx:`40`,cy:`40`,r:`36`,style:n.circle})]}),Z(`div`,{style:n.iconContainer,children:Q(`svg`,{width:`48`,height:`48`,viewBox:`0 0 24 24`,role:`img`,"aria-labelledby":`warning-icon-title`,children:[Z(`title`,{id:`warning-icon-title`,children:`Warning icon`}),Z(`path`,{d:`M12 3 L22 20 H2 Z`,style:n.trianglePath}),Z(`path`,{d:`M12 9 L12 14`,style:n.exclamationPath}),Z(`circle`,{cx:`12`,cy:`17`,r:`1.5`,style:n.dot})]})})]})})}const ax=[];function ox(e,t){let n=!!(e?.chainId&&t?.chainId&&e&&t&&(e.blockNumber||e.transactionHash)&&(t.blockNumber||t.transactionHash)&&(e.blockNumber!==t.blockNumber||e.transactionHash!==t.transactionHash)),{data:r=0}=Or({queryKey:[`completionTimeSeconds`,e?.blockNumber,t?.blockNumber,e?.transactionHash,t?.transactionHash,e?.chainId,t?.chainId],enabled:n,queryFn:async()=>rg(e,t),staleTime:1/0,gcTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:!1});return r}function sx(e){let t=(e||[]).slice().reverse().find(e=>tg(e.transactionHash)&&e.chainId),n=t?.explorerUrl||(tg(t?.transactionHash)&&t?.chainId?Xa({txHash:t.transactionHash,chainId:t.chainId}):null),r=t?.chainId,i=(e||[]).filter(e=>e.state===`confirmed`),a=i[0],o=i[i.length-1];return{finalExplorerUrl:n,completionTimeSeconds:ox(a,o),finalChainId:r}}const cx=({onSendAnother:e,onClose:t,renderInline:n=!1,transactionStates:r=ax,totalCompletionSeconds:i,quote:a,showCloseButton:o,actionButtonText:s,onRampQuote:c,errorMessage:l})=>{let{address:u}=Kr(),{trailsAppUrl:d}=Vx(),[f,p]=X(!1),[m,h]=X(!1),[g,_]=X(null);q(()=>{let e=setTimeout(()=>{p(!0)},400);return()=>clearTimeout(e)},[]);let v=J(()=>r.some(e=>Ng(e)),[r]),y=J(()=>{let e=[...r],t=r.find(e=>e.refundTransactionHash);if(!t?.refundTransactionHash)return e;let n=t.refundTransactionChainId??t.chainId,i=e.findIndex(e=>e.transactionHash===t.refundTransactionHash),a=(i>=0?e.splice(i,1)[0]:void 0)??{id:`refund-${t.refundTransactionHash}`,transactionHash:t.refundTransactionHash,explorerUrl:Xa({txHash:t.refundTransactionHash,chainId:n}),chainId:n,state:t.refunded?`confirmed`:`pending`,label:`Refund`,txnMinedAt:t.txnMinedAt},o=Math.max(e.length-1,0);return e.splice(o,0,a),e},[r]),b=J(()=>r.some(e=>e.refunded),[r]),x=J(()=>r.some(e=>e.state===`aborted`),[r]),S=J(()=>Cb(r),[r]),C=m||b,w=s||`Start new transaction`,{finalExplorerUrl:T,finalChainId:E,completionTimeSeconds:D}=sx(r),O=J(()=>{if(!C)return null;let e=r.find(e=>e.refundTransactionHash);if(!e?.refundTransactionHash)return null;let t=e.refundTransactionChainId??e.chainId;return{url:Xa({txHash:e.refundTransactionHash,chainId:t}),chainId:t}},[C,r]),k=O?.url??T??void 0,A=O?.chainId??E,j=()=>!d||!a?.intentId?null:`${d}/intent/${a.intentId}`,M=j(),[N,P]=X(!1);q(()=>{if(!a?.intentId){P(!1);return}P(!1);let e=setTimeout(()=>{P(!0)},2*Ee);return()=>{clearTimeout(e)}},[a?.intentId]);let{chainGroups:F,hasRecoverableFunds:I,isLoading:ee,error:te,refetch:ne}=tx({intentId:a?.intentId??void 0,ownerAddress:u,enabled:N&&!!a?.intentId}),re=i??D;q(()=>{let e=r?.find(e=>e.refunded);if(e){let t=$(e?.chainId)?.name||`the origin chain`;_(Q(hi,{children:[`The transaction call failed, but your funds were successfully refunded on`,` `,Q(`span`,{className:`inline-flex ml-1 items-center`,children:[Z(`span`,{className:`mr-1 inline-flex items-center`,children:Z(Ty,{chainId:e?.chainId,size:16})}),Z(`strong`,{children:t})]}),`.`]})),h(!0);return}h(!1),_(null)},[r]);let ie=a&&Z(`div`,{className:`mt-2`,children:Z(wb,{quote:a,onRampQuote:c,showContent:!0,compact:!0,liveTransactionStates:y,hasMetaTxError:Ng})}),L=r.some(e=>tg(e.transactionHash)),R=!!l&&r.length===0;return!T&&!C&&!L||S&&!b?Q(`div`,{className:`flex flex-col justify-center min-h-full space-y-6`,children:[Z(M_,{}),Q(`div`,{className:`text-center`,children:[Z(`div`,{className:`mx-auto flex items-center justify-center mb-4`,children:R?Z(ix,{}):Z(`div`,{className:`w-16 h-16 rounded-full flex items-center justify-center bg-red-100 dark:bg-red-900/20`,children:Q(`svg`,{className:`w-8 h-8 text-red-500 dark:text-red-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`Error`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})]})})}),Z(`h2`,{className:`text-xl font-semibold text-gray-900 dark:text-white`,children:R?`Unable to Continue`:`Transaction Failed`}),R?Z(`div`,{className:`mt-3 p-3 trails-border-radius-container text-sm text-left bg-amber-50 border border-solid border-amber-200 text-amber-800 dark:bg-amber-900/20 dark:border-amber-700/50 dark:text-amber-200`,children:l}):Z(`p`,{className:`mt-2 text-sm text-gray-600 dark:text-gray-400`,children:x?Q(hi,{children:[`The transaction likely timed out and was aborted. Please`,` `,Z(`a`,{href:`https://support.trails.build/en/`,target:`_blank`,rel:`noopener noreferrer`,className:`text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 underline`,children:`contact support`}),` `,`with the intent ID below to request a refund.`]}):Q(hi,{children:[`No final transaction hash found. This is likely due to a failed transaction or failed relay. Please`,` `,Z(`a`,{href:`https://support.trails.build/en/`,target:`_blank`,rel:`noopener noreferrer`,className:`text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 underline`,children:`reach out to support`}),`.`]})})]}),!R&&a?.intentId&&Z(`div`,{className:`text-center`,children:Q(`div`,{className:`inline-flex flex-col items-center gap-2 p-3 rounded-lg bg-gray-100 dark:bg-gray-800`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Intent ID`}),Z(`code`,{className:`text-sm font-mono text-gray-900 dark:text-white break-all`,children:a.intentId})]})}),e&&Z(`div`,{className:`flex justify-center`,children:Z(`button`,{type:`button`,onClick:e,className:`inline-flex items-center gap-1 px-4 py-2 text-sm bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 trails-border-radius-button transition-colors duration-200 text-gray-600 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 cursor-pointer font-medium`,children:`Try Again`})}),Z(rx,{hasRecoverableFunds:I,chainGroups:F,isLoading:ee,error:te?.message||null,trailsIntentUrl:M,onRefresh:ne}),ie,!n&&t&&o&&Z(`div`,{className:`text-center`,children:Z(`button`,{type:`button`,onClick:t,className:`w-full cursor-pointer font-semibold py-3 px-4 trails-border-radius-button transition-colors bg-gray-100 hover:bg-gray-200 text-gray-600 hover:text-gray-900 dark:bg-gray-800 dark:hover:bg-gray-700 dark:text-gray-300 dark:hover:text-white`,children:`Close`})})]}):Q(`div`,{className:`flex flex-col justify-center min-h-full space-y-6`,children:[Z(M_,{}),Q(`div`,{className:`text-center mb-2`,children:[Z(`div`,{className:`mx-auto flex items-center justify-center`,children:Z(C||v?ix:nx,{})}),Q(`div`,{className:`transition-all duration-500 ease-out ${f?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:[Z(`h2`,{className:`mt-4 text-2xl font-bold text-gray-900 dark:text-white`,children:C?`Unable to process.`:`Completed`}),C&&Z(`div`,{className:`mt-1 text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-1 justify-center animate-fade-in-up`,children:`You were Refunded.`}),re>0&&Q(`div`,{className:`mt-1 text-sm text-gray-600 dark:text-gray-400 flex items-center gap-1 justify-center animate-fade-in-up`,style:{animation:`fadeInUp 0.7s cubic-bezier(0.23, 1, 0.32, 1)`,animationFillMode:`both`},children:[Z(`div`,{className:`inline-block animate-fade-in-up`,children:C?Z(`span`,{children:`Transaction confirmed`}):Q(`span`,{children:[`Completed in`,` `,Z(`strong`,{children:Ce(re)})]})}),i&&i<15&&!v&&!C&&Q(`svg`,{className:`w-4 h-4 ml-1 text-yellow-400 inline`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,children:[Z(`title`,{children:`Lightning Fast`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M13 10V3L4 14h7v7l9-11h-7z`,fill:`currentColor`})]}),Z(`style`,{children:`
41
+ @keyframes fadeInUp {
42
+ 0% { opacity: 0; transform: translateY(16px); }
43
+ 100% { opacity: 1; transform: translateY(0); }
44
+ }
45
+ `})]}),(v||C)&&Q(`div`,{className:`mt-2 text-sm text-orange-600 dark:text-orange-400 flex items-center gap-2 justify-center animate-fade-in-up`,style:{animation:`fadeInUp 0.7s cubic-bezier(0.23, 1, 0.32, 1)`,animationFillMode:`both`},children:[Q(`svg`,{className:`w-4 h-4 text-orange-500`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,children:[Z(`title`,{children:`Internal Meta Transaction Error`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})]}),Z(`span`,{children:`Although one or more errors occurred`})]})]})]}),(k||j()||O?.url)&&Z(`div`,{className:`text-center transition-all duration-500 ease-out delay-100 ${f?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:Q(`div`,{className:`flex flex-col items-center gap-2`,children:[k&&Q(`a`,{href:k,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-sm font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 transition-colors`,children:[A&&Z(Ty,{chainId:A,size:16}),`View on Explorer`,Q(`svg`,{className:`w-4 h-4 ml-1 text-blue-600 dark:text-blue-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`External Link`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14`})]})]}),j&&Q(`a`,{href:j()||``,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-sm font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 transition-colors`,children:[`View Transaction Receipt`,Q(`svg`,{className:`w-4 h-4 ml-1 text-blue-600 dark:text-blue-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`External Link`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14`})]})]})]})}),C&&g&&Z(`div`,{className:`mt-2 text-sm text-yellow-700 dark:text-yellow-400 flex items-center gap-2 justify-center animate-fade-in-up`,style:{animation:`fadeInUp 0.7s cubic-bezier(0.23, 1, 0.32, 1)`,animationFillMode:`both`},children:Z(`div`,{className:`rounded-xl bg-warning`,children:Z(`div`,{className:`flex bg-background-overlay rounded-xl p-4 w-full flex-col gap-3`,children:Q(`div`,{className:`flex w-full gap-2 justify-between`,children:[Q(`div`,{className:`flex flex-col gap-1`,children:[Z(`div`,{className:`text-sm font-medium text-gray-900 dark:text-white text-left`,children:`Refund Information`}),Z(`div`,{className:`text-sm text-gray-700 dark:text-gray-300 text-left`,children:g})]}),Z(`div`,{className:`flex items-center`,children:Q(`svg`,{className:`w-5 h-5 text-yellow-600 dark:text-yellow-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,children:[Z(`title`,{children:`Information`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})]})})]})})})}),Q(`div`,{className:`space-y-3 transition-all duration-500 ease-out delay-200 ${f?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:[e&&Z(`div`,{className:`flex justify-center`,children:Z(`button`,{type:`button`,onClick:e,className:`inline-flex items-center gap-1 px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 dark:bg-blue-600 dark:hover:bg-blue-700 trails-border-radius-button transition-colors duration-200 text-white cursor-pointer font-medium`,children:w})}),Z(rx,{hasRecoverableFunds:I,chainGroups:F,isLoading:ee,error:te?.message||null,trailsIntentUrl:M,onRefresh:ne}),ie,!n&&o&&Z(`button`,{type:`button`,onClick:t,className:`w-full cursor-pointer font-semibold py-3 px-4 trails-border-radius-button transition-colors bg-gray-100 hover:bg-gray-200 text-gray-600 hover:text-gray-900 dark:bg-gray-800 dark:hover:bg-gray-700 dark:text-gray-300 dark:hover:text-white`,children:`Close`})]})]})};function lx(){return qu()!=null}function ux(){let{navigate:e}=y_();return K(t=>{e(`wallet-list`,{backTarget:t?.backTarget})},[e])}const dx=[`eip155`],fx=({onConnect:e,onContinue:t,onError:n,lastClickedWallet:r,showDisconnect:i=!0})=>{let a=Yr(),o=a.address,c=a.activeConnection,l=a.walletName,u=a.isConnected,d=Jr(),f=li(),p=J(()=>f.filter(e=>e.namespace===`eip155`),[f]),{switchAccount:m}=ai(),h=Ao(),g=Oo(),_=Ia(),v=g===`builtin-evm`?Fa(_):void 0,{availableBrowserWallets:y,orderedWalletOptions:b}=La({activeRememberedWalletId:g===`builtin-evm`?_.activeWalletId??null:null,supportsWidgetWalletSelection:h,lastClickedWallet:g===`builtin-evm`?void 0:r,rememberedWalletIds:v,namespaces:dx}),{navigate:x}=y_(),S=ux(),C=lx(),[w,T]=X(null),{hideAddWallet:E}=wo(),D=J(()=>new Set([...y.map(e=>e.walletId),...b.map(e=>e.id)]),[y,b]),O=p.some(Rr),k=D.size>0,A=p.some(e=>Rr(e)&&!D.has(e.id)),j=(c?.showDisconnect??c?.ui?.showDisconnect)===!0,M=!E&&h&&O,N=!E&&h&&(!k||A);q(()=>{w&&n(Error(w))},[w,n]);let{trackClick:P}=k_(),F=t=>{let n=b.find(e=>e.id===t),r=y.find(e=>e.walletId===t),i=n?.flow,a=n?.isDetected??!0,o=n?.name??r?.name??t,c=(typeof n?.icon==`string`?n.icon:void 0)??(typeof r?.icon==`string`?r.icon:void 0);if(s.console.log(`[trails-sdk] handleWalletConnect called:`,{walletId:t,flow:i,isDetected:a}),P({component:`ConnectWallet`,action:`connect_wallet`,label:t,metadata:{flow:i,isDetected:a}}),C){S({backTarget:`connect`,walletId:t,walletName:o,walletIcon:c});return}e(t)},I=()=>{try{T(null),P({component:`ConnectWallet`,action:`disconnect_wallet`,metadata:{currentAddress:o,currentConnector:l}}),x(`disconnect`)}catch(e){s.console.error(`[trails-sdk] Failed to disconnect wallet:`,e),T(e instanceof Error?e.message:`Failed to disconnect wallet`)}},ee=e=>{try{T(null),m(e.connectionId,e.address),s.console.log(`[trails-sdk] Switched to wallet: ${e.address}`)}catch(e){s.console.error(`[trails-sdk] Failed to switch wallet:`,e),T(e instanceof Error?e.message:`Failed to switch wallet`)}};return Q(`div`,{className:`space-y-6`,children:[Z(M_,{headerContent:`Connect Wallet`,headerContentAlign:`left`}),u?Z(`div`,{className:`space-y-4`,children:Q(`div`,{className:`flex flex-col gap-3`,children:[d.map(e=>Z(`div`,{className:`space-y-2`,children:Q(`button`,{type:`button`,onClick:e.isActive?t:()=>ee(e),className:`w-full flex items-center justify-between cursor-pointer font-semibold py-4 px-6 trails-border-radius-large-button transition-all duration-200 ${e.isActive?`trails-bg-secondary trails-hover-bg trails-text-primary`:`bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300`}`,children:[Q(`div`,{className:`flex items-center space-x-3`,children:[Z(Na,{walletId:e.walletId,icon:e.icon,label:e.name,size:24,className:`h-6 w-6 shrink-0`,fallback:Z(na,{className:`h-6 w-6 text-gray-600 dark:text-gray-400`})}),Q(`div`,{className:`flex flex-col items-start space-y-1`,children:[Q(`div`,{className:`flex items-center space-x-2`,children:[Z(`span`,{children:e.name||`Wallet`}),Z(`span`,{className:`text-xs px-2 py-1 trails-border-radius-container font-normal ${e.isActive?`bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200`:`bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200`}`,children:e.isActive?`Active`:`Connected`})]}),Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 font-mono`,children:wt(e.address)})]})]}),Q(`div`,{className:`flex items-center`,children:[e.isActive&&Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 font-medium`,children:`Continue`}),Z(ki,{className:`h-5 w-5 text-gray-400`})]})]})},e.address)),y.length>0&&Z(`div`,{className:`pt-2 space-y-2`,children:y.map(e=>Q(`button`,{type:`button`,onClick:()=>F(e.walletId),className:`w-full flex items-center justify-between cursor-pointer font-semibold py-4 px-6 trails-border-radius-large-button transition-all duration-200 trails-bg-secondary trails-hover-bg trails-text-primary`,children:[Q(`div`,{className:`flex items-center space-x-3`,children:[Z(Na,{walletId:e.walletId,icon:e.icon,label:e.name,size:24,className:`h-6 w-6 shrink-0`,fallback:Z(na,{className:`h-6 w-6 text-gray-600 dark:text-gray-400`})}),Q(`div`,{className:`flex items-center space-x-2`,children:[Z(`span`,{children:e.name}),Z(`span`,{className:`text-xs bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300 px-2 py-1 trails-border-radius-container font-normal`,children:`Detected`})]})]}),Z(ki,{className:`h-5 w-5 text-gray-400`})]},e.key))}),M&&Q(`button`,{type:`button`,onClick:()=>S({backTarget:`connect`}),className:`w-full flex items-center justify-between cursor-pointer font-semibold py-4 px-6 trails-border-radius-large-button transition-all duration-200 trails-bg-secondary trails-hover-bg trails-text-primary`,children:[Q(`div`,{className:`flex items-center space-x-3`,children:[Z(vi,{className:`h-6 w-6 text-gray-600 dark:text-gray-400`}),Z(`span`,{children:`Connect Another Wallet`})]}),Z(ki,{className:`h-5 w-5 text-gray-400`})]}),i&&j&&Q(`button`,{type:`button`,onClick:I,className:`w-full flex items-center justify-between cursor-pointer font-semibold py-4 px-6 trails-border-radius-large-button transition-all duration-200 trails-bg-secondary trails-hover-bg trails-text-primary`,children:[Q(`div`,{className:`flex items-center space-x-3`,children:[Z(Ui,{className:`h-6 w-6 text-gray-600 dark:text-gray-400`}),Z(`span`,{children:`Disconnect`})]}),Z(ki,{className:`h-5 w-5 text-gray-400`})]})]})}):Q(`div`,{className:`flex flex-col gap-3`,children:[y.map(e=>Q(`button`,{type:`button`,onClick:()=>F(e.walletId),className:`w-full flex items-center justify-between cursor-pointer font-semibold py-4 px-6 trails-border-radius-large-button transition-all duration-200 trails-bg-secondary trails-hover-bg trails-text-primary`,children:[Q(`div`,{className:`flex items-center space-x-3`,children:[Z(Na,{walletId:e.walletId,icon:e.icon,label:e.name,size:24,className:`h-6 w-6 shrink-0`,fallback:Z(na,{className:`h-6 w-6 text-gray-600 dark:text-gray-400`})}),Q(`div`,{className:`flex items-center space-x-2`,children:[Z(`span`,{children:e.name}),Z(`span`,{className:`text-xs bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300 px-2 py-1 trails-border-radius-container font-normal`,children:`Detected`})]})]}),Z(ki,{className:`h-5 w-5 text-gray-400`})]},e.key)),b.length>0?Q(hi,{children:[b.map(e=>Q(`button`,{type:`button`,"data-wallet-id":e.id,onClick:()=>F(e.id),className:`w-full flex items-center justify-between cursor-pointer font-semibold py-4 px-6 trails-border-radius-large-button transition-all duration-200 trails-bg-secondary trails-hover-bg trails-text-primary`,children:[Q(`div`,{className:`flex items-center space-x-3`,children:[Z(Na,{walletId:e.id,icon:e.icon,label:e.name,size:24,className:`h-6 w-6 shrink-0`,fallback:Z(na,{className:`h-6 w-6 text-gray-600 dark:text-gray-400`})}),Q(`div`,{className:`flex items-center space-x-2`,children:[Z(`span`,{children:e.name}),e.isRecent?Z(`span`,{className:`text-xs bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300 px-2 py-1 trails-border-radius-container font-normal`,children:`Recent`}):e.isDetected?Z(`span`,{className:`text-xs bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300 px-2 py-1 trails-border-radius-container font-normal`,children:`Detected`}):null]})]}),Z(ki,{className:`h-5 w-5 text-gray-400`})]},e.id)),b.length>0&&N&&Q(`button`,{type:`button`,onClick:()=>S({backTarget:`connect`}),className:`w-full flex items-center justify-between cursor-pointer font-semibold py-4 px-6 trails-border-radius-large-button transition-all duration-200 trails-bg-secondary trails-hover-bg trails-text-primary`,children:[Q(`div`,{className:`flex items-center space-x-3`,children:[Z(vi,{className:`h-6 w-6 text-gray-600 dark:text-gray-400`}),Z(`span`,{children:`More Wallets`})]}),Z(ki,{className:`h-5 w-5 text-gray-400`})]})]}):N||C&&!E?Q(`button`,{type:`button`,onClick:()=>S({backTarget:`connect`}),className:`w-full flex items-center justify-between cursor-pointer font-semibold py-4 px-6 trails-border-radius-large-button transition-all duration-200 trails-bg-secondary trails-hover-bg trails-text-primary`,children:[Q(`div`,{className:`flex items-center space-x-3`,children:[Z(vi,{className:`h-6 w-6 text-gray-600 dark:text-gray-400`}),Z(`span`,{children:`Choose Wallet`})]}),Z(ki,{className:`h-5 w-5 text-gray-400`})]}):Z(`div`,{className:`space-y-6`,children:Z(`div`,{className:`text-center p-4 trails-border-radius-container trails-text-tertiary trails-bg-secondary`,children:`No injected wallet was detected in this browser`})})]})]})},px=`trails_recent_tokens`;function mx(e){let[t,n]=X([]);return q(()=>{if(!e){n([]);return}try{let t=localStorage.getItem(px);if(t){let r=JSON.parse(t)[St(e)]||[],i=r.map(e=>({symbol:e.symbol,name:e.name,decimals:e.decimals,contractAddress:e.contractAddress,tokenId:e.tokenId,chainId:e.chainId,chainName:e.chainName,imageUrl:e.imageUrl,isCustomToken:e.isCustomToken,isNativeToken:e.isNativeToken}));s.console.log(`[trails-sdk] Loaded and sanitized recent tokens`,{accountAddress:St(e),tokenCount:i.length,tokens:i.map((e,t)=>({symbol:e.symbol,chainId:e.chainId,hasBalance:r[t]&&`balance`in r[t]}))}),n(i)}}catch(e){s.console.warn(`[trails-sdk] Failed to load recent tokens from localStorage:`,e)}},[e]),{recentTokens:t,addRecentToken:K(t=>{if(e)try{let r=localStorage.getItem(px),i=r?JSON.parse(r):{},a=St(e),o=i[a]||[],s={symbol:t.symbol,name:t.name,decimals:t.decimals,contractAddress:t.contractAddress,tokenId:t.tokenId,chainId:t.chainId,chainName:t.chainName,imageUrl:t.imageUrl,isCustomToken:t.isCustomToken,isNativeToken:t.isNativeToken};o=o.filter(e=>!(e.contractAddress===s.contractAddress&&(e.chainId||0)===(s.chainId||0))),o.unshift(s),o=o.slice(0,10),i[a]=o,localStorage.setItem(px,an(i)),n(o)}catch(e){s.console.warn(`[trails-sdk] Failed to save recent token to localStorage:`,e)}},[e]),clearRecentTokens:K(()=>{if(e)try{let t=localStorage.getItem(px);if(t){let n=JSON.parse(t),r=St(e);delete n[r],localStorage.setItem(px,JSON.stringify(n))}n([])}catch(e){console.warn(`Failed to clear recent tokens from localStorage:`,e)}},[e])}}function hx(e){return!e.isWalletReady&&(e.status===`awaiting-origin`||e.status===`quoting`||e.status===`confirmation`)}function gx(e){switch(e){case`awaiting-origin`:return`select-origin-token`;case`awaiting-amount`:return`select-origin-amount`;case`quoting`:case`confirmation`:return`wallet-confirmation`;case`pending`:return`pending`;case`success`:case`error`:return`receipt`;default:return`select-origin-token`}}function _x(){let{address:e}=Kr(),{data:t}=si(),{connect:n}=ai(),r=li().filter(e=>e.namespace===`eip155`),{renderInline:i}=wo(),{isModalOpen:a,closeModal:o,pendingSelection:c,setPendingSelection:l,hostTransactionState:u,setHostTransactionState:d,hostTransactionQuote:f,hostTransactionStates:p,hostTransactionTimestamp:m,feeOptions:h,pendingFeeConfirmation:g,setPendingFeeConfirmation:_,resetHostTransactionState:v,resetForNewTransaction:y,receiptActionButtonText:b,onReceiptAction:x,retryTransactionRef:S,repeatTransactionRef:C,restartOriginSelectionRef:w,lastOriginSelection:T,setLastOriginSelection:E,setHandleCloseModal:D}=wx(),k=kr(),{selectedToken:A,setSelectedToken:j}=ul(),{recentTokens:M,addRecentToken:N}=mx(e),{sortedTokens:P,isLoadingSortedTokens:F}=Q_(h?e??null:null,void 0,{refetchInterval:!1}),I=f?.originChain.id,ee=J(()=>Ol(h?.feeOptions??[],I,P),[h,I,P]),{selectedFeeOption:te,setSelectedFeeOption:ne}=Yl(ee),re=K(()=>{g?.resolve(te),_(void 0)},[g,te,_]),ie=J(()=>{let e=f?.originToken,t=f?.originChain.id??e?.chainId;return Rl({originToken:e,originTokenBalance:P.find(n=>n.chainId===t&&St(n.contractAddress)===St(e?.contractAddress))?.balance,originTokenAmount:f?.originAmountFormatted,isLoadingBalance:F})},[f,P,F]),[L,R]=X(null),[ae,z]=X(null),[B,V]=X(!1),[oe,H]=X(null),[se,ce]=X(null),U=!!(e&&t?.account),le=hx({isWalletReady:U,status:u.status}),ue=!!(e&&!t?.account),de=Y(T?.amount);q(()=>{T?.amount&&(de.current=T.amount)},[T?.amount]);let fe=gx(u.status),pe=le?se??(ue?`wallet-connection-pending`:`connect-wallet`):fe;q(()=>{le||(ce(null),H(null),V(!1))},[le]),q(()=>{U&&se&&(ce(null),H(null),V(!1))},[se,U]),q(()=>{u.status===`success`&&m&&R(Math.max(0,xe(ke(m))))},[u.status,m]),q(()=>()=>{$a.abortAll()},[]);let me=K(()=>{c&&(c.reject(Error(`Modal closed by user`)),l(void 0)),$a.abortAll(),o(),v(),j(null),ce(null),H(null),V(!1),z(null)},[o,v,c,l,j]);q(()=>(D(me),()=>{D(null)}),[me,D]);let he=e=>{if(!U){s.console.warn(`[trails-sdk] [HookModalContent] Ignoring token selection until wallet client is ready`);return}if(j(e),N(e),c){if(c.requireAmountInput){d(e=>({...e,status:`awaiting-amount`}));return}let t=e.contractAddress||Cn;try{c.resolve({fromTokenAddress:t,fromChainId:e.chainId??0,originToken:e})}catch(e){s.console.error(`[trails-sdk] [HookModalContent] Error resolving pending selection:`,e),c.reject(e)}finally{l(void 0)}}},ge=e=>{he(e)},_e=e=>{if(de.current=e,A&&E({tokenAddress:A.contractAddress||Cn,chainId:A.chainId??0,amount:e}),c&&A)try{c.resolve({fromTokenAddress:A.contractAddress||Cn,fromChainId:A.chainId??0,fromAmount:e,originToken:A}),l(void 0)}catch(e){s.console.error(`[trails-sdk] [HookModalContent] Error resolving pending selection amount:`,e),c.reject(e),l(void 0)}},ve=()=>{S.current&&(d(e=>({...e,retryEnabled:!1})),S.current())},ye=async e=>{try{if(H(null),V(!0),z(e),ce(`wallet-connection-pending`),!r.find(t=>t.id===e))throw Error(`No wallet option available for wallet: ${e}`);await n(e)}catch(e){s.console.error(`[trails-sdk] [HookModalContent] Failed to connect wallet:`,e),H(e instanceof Error?e.message:`Failed to connect wallet`),V(!1)}},be=K(()=>{$a.abortAll(),k.invalidateQueries({queryKey:[`prepareSend`]}),Lh(),x&&x(),C.current?C.current():y()},[k,x,C,y]);return!a||u.status===`idle`?null:Z(w_,{isOpen:a,onClose:me,children:Z(`div`,{className:`flex flex-col min-h-[400px] shadow-xl p-4 sm:p-6 relative w-full max-w-[400px] min-w-0 sm:w-[400px] mx-auto custom-scrollbar trails-bg-primary trails-text-primary trails-font trails-border-radius-widget trails-widget-border trails-fade-slide-in`,children:Z(`div`,{className:`flex-1 flex flex-col w-full min-w-0 trails-fade-slide-in-fast`,children:(()=>{switch(pe){case`connect-wallet`:return Z(fx,{onConnect:e=>{ye(e)},onDisconnect:()=>{ce(`connect-wallet`)},onContinue:()=>{U&&ce(null)},onError:e=>{H(e instanceof Error?e.message:String(e))},lastClickedWallet:ae,showDisconnect:!1});case`wallet-connection-pending`:return Z(O,{onBack:()=>{ce(`connect-wallet`),H(null),V(!1)},onRetry:()=>{ae&&ye(ae)},selectedWalletId:ae??``,isConnecting:B||ue,error:oe,showRetry:!!oe});case`select-origin-token`:return Z(db,{onContinue:he,onBack:me,accountAddress:e??void 0,targetAmountUsd:u.details?.targetAmountUsd??null,targetAmountUsdFormatted:u.details?.targetAmountUsdFormatted??null,onError:e=>{s.console.error(`[trails-sdk] [HookModalContent] Token list error:`,e)},recentTokens:M,onRecentTokenSelect:ge,fundMethod:null,renderInline:i});case`select-origin-amount`:return Z(mb,{token:A,onBack:e=>{de.current=e,d(e=>({...e,status:`awaiting-origin`}))},onCancel:e=>{de.current=e,me()},onSubmit:_e,initialAmount:de.current});case`wallet-confirmation`:return Z(Rb,{onBack:()=>{w.current?w.current():d(e=>({...e,status:`awaiting-origin`}))},retryEnabled:u.retryEnabled??!1,onRetry:ve,quote:f,originToken:u.details?.originToken??A,isQuoting:u.status===`quoting`,awaitingFeeConfirmation:!!g,feeOptions:ee,selectedFeeOption:te,setSelectedFeeOption:ne,onConfirmFeeOption:re,originTokenInfo:ie});case`pending`:return Z($b,{onElapsedTime:e=>R(e??0),transactionStates:p,quote:f,timestamp:m??void 0,onContinue:()=>{}});case`receipt`:return Z(cx,{onSendAnother:be,onClose:me,renderInline:i,transactionStates:p,totalCompletionSeconds:L??void 0,quote:f,showCloseButton:!1,actionButtonText:b??void 0,errorMessage:u.error});default:return null}})()},pe)})})}const vx=new xr({queryCache:yo.getQueryCache(),mutationCache:yo.getMutationCache(),defaultOptions:vo}),yx=ct();function bx({walletRuntimeMode:e}){let{trailsApiKey:t}=Vx(),[n,r]=X(!1);return q(()=>{r(!0),s.console.log(`[trails-sdk] [TrailsHookModalInner] Mounted`)},[]),n?Ar(Z(l,{children:Z(C,{children:Z(C_,{props:{apiKey:t,renderInline:!1},walletRuntimeMode:e,children:Z(_x,{})})})}),document.body):null}function xx(){let e=Qr(),t=hr(zx),n=t?.config??null;s.console.log(`[trails-sdk] [TrailsHookModal] Check:`,{hasWalletContext:e,hasTrailsContext:!!t});let r=bo({hasWalletContext:e});s.console.log(`[trails-sdk] [TrailsHookModal] Runtime mode:`,{walletRuntimeMode:r,hasTrailsContext:!!t});let i=Z(bx,{walletRuntimeMode:r});return r===`parent`?i:r===`builtin-evm`?Z(Cr,{client:vx,children:Z(jr,{chains:yx,walletConnectProjectId:n?.walletConnectProjectId,children:i})}):Z(Cr,{client:vx,children:i})}const Sx=ur(null),Cx=({children:e})=>{let[t,n]=X(!1),[r,i]=X(void 0),[a,o]=X({status:`idle`}),[c,l]=X(null),[u,d]=X([]),[f,p]=X(null),[h,g]=X(null),[_,v]=X(void 0),[y,b]=X(null),[x,S]=X(null),C=Y(null),w=Y(null),T=Y(null),E=Y(null),[D,O]=X(null),k=K(()=>{s.console.log(`[trails-sdk] [TrailsModalProvider] openModal called`),n(!0)},[]),A=K(()=>{n(!1),r&&(r.reject(Error(`Modal was closed before selection completed`)),i(void 0)),_&&(_.reject(new m(`Modal was closed before fee selection completed`)),v(void 0))},[r,_]),j=K(()=>{o({status:`idle`}),l(null),d([]),p(null),g(null),b(null),S(null),C.current=null,T.current=null},[]),M=K(()=>{s.console.log(`[trails-sdk] [TrailsModalProvider] resetForNewTransaction called`),o({status:`awaiting-origin`}),l(null),d([]),p(null),g(null),C.current=null},[]),N=K(e=>{E.current=e},[]),P={isModalOpen:t,openModal:k,closeModal:A,getHandleCloseModal:K(()=>E.current,[]),setHandleCloseModal:N,pendingSelection:r,setPendingSelection:i,hostTransactionState:a,setHostTransactionState:o,resetHostTransactionState:j,resetForNewTransaction:M,hostTransactionQuote:c,setHostTransactionQuote:l,hostTransactionStates:u,setHostTransactionStates:d,hostTransactionTimestamp:f,setHostTransactionTimestamp:p,feeOptions:h,setFeeOptions:g,pendingFeeConfirmation:_,setPendingFeeConfirmation:v,receiptActionButtonText:y,setReceiptActionButtonText:b,onReceiptAction:x,setOnReceiptAction:S,retryTransactionRef:C,repeatTransactionRef:w,restartOriginSelectionRef:T,lastOriginSelection:D,setLastOriginSelection:O};return Q(Sx.Provider,{value:P,children:[e,t&&Z(xx,{})]})};function wx(){let e=hr(Sx);if(!e)throw Error(`useTrailsModal must be used within a TrailsModalProvider`);return e}function Tx(e){let{children:t,svmSources:n,EvmProvider:r,evmProviderProps:i}=e,a=r?dr(r,i??{},t):t;return n.reduceRight((e,t)=>dr(t.Provider,t.providerProps??{},e),a)}function Ex(e,t){return{Provider:Tx,providerProps:{svmSources:e.map(e=>({Provider:e.adapter.Provider,providerProps:e.adapter.providerProps})),EvmProvider:t?.Provider,evmProviderProps:t?.providerProps},namespaces:t?.namespaces,sequenceSupport:t?.sequenceSupport}}function Dx(e){return typeof e==`object`&&!!e&&`adapter`in e}function Ox(e){return Dx(e)?{adapter:e.adapter,key:e.key,managedBy:e.managedBy??`trails`}:{adapter:e,managedBy:`trails`}}function kx(e){let{children:t,walletConnectProjectId:n,wallets:r}=e??{};return dr(jr,{chains:ct(),walletConnectProjectId:n,wallets:r,children:t})}function Ax({walletConnectProjectId:e,wallets:t}){return{Provider:kx,providerProps:{walletConnectProjectId:e,wallets:t},namespaces:[`eip155`]}}function jx({entry:e,fallback:t}){return e?.key??t}function Mx(e){let t=new Set;for(let n of e)for(let e of n.adapter.namespaces??[])e===`eip155`&&t.add(e);return t.size>0?[...t]:void 0}function Nx(e){let{children:t,sources:n}=e;return dr(Mr,{sources:n,errorLabel:`Trails adapter composition`,children:t})}function Px(e){let t=e.adapter.Provider;if(!t)throw Error(`[trails-sdk] Trails adapter composition requires provider-backed adapters.`);return{id:e.id,lifecycleOwner:e.lifecycleOwner,adapter:{Provider:t,providerProps:e.adapter.providerProps}}}function Fx({adapters:e}){return{Provider:Nx,providerProps:{sources:e.map(Px),adapters:e.map(e=>({id:e.id,managedBy:e.lifecycleOwner}))},namespaces:Mx(e),sequenceSupport:e.find(e=>e.adapter.sequenceSupport)?.adapter.sequenceSupport}}function Ix({adapters:e,walletConnectProjectId:t}){if(!e)return;let n=e.map(Ox),r=n.length>0,i=n.filter(e=>e.adapter.namespaces?.includes(`solana`)),a=n.filter(e=>!e.adapter.namespaces?.includes(`solana`)),o=a.map((e,t)=>({adapter:e.adapter,id:jx({entry:e,fallback:`adapter-${t}`}),lifecycleOwner:e.managedBy}));a.length===0&&o.push({adapter:Ax({walletConnectProjectId:t}),id:`builtin-evm`,lifecycleOwner:`trails`});let s;return s=o.length===0?void 0:o.length===1&&(!r||o[0].lifecycleOwner===`trails`)?o[0].adapter:Fx({adapters:o}),i.length===0?s:Ex(i,s)}function Lx(e){let t=Y(void 0);t.current!==e&&(d(e),t.current=e)}function Rx({children:e}){return hr(Sr)?Z(hi,{children:e}):Z(Cr,{client:yo,children:e})}const zx=ur(null),Bx=({children:e,config:t})=>{let n=(t.debug??!1)||pe(`debug`)===`true`,r=t.walletConnectProjectId||`10c5ac56159da00924d110c07c3f6e3a`,i=t.adapters===void 0||t.adapters.length===0;Lx(n);let a=i?r:t.walletConnectProjectId,o=J(()=>Ix({adapters:t.adapters??[],owner:`TrailsProvider config.adapters`,walletConnectProjectId:a}),[t.adapters,a]),s=o?.sequenceSupport,c=J(()=>({trailsApiKey:t.trailsApiKey,trailsApiUrl:t.trailsApiUrl||`https://trails-api.sequence.app`,trailsAppUrl:t.trailsAppUrl||`https://app.trails.build`,sequenceIndexerUrl:t.sequenceIndexerUrl||`https://indexer.sequence.app`,sequenceNodeGatewayUrl:t.sequenceNodeGatewayUrl||`https://nodes.sequence.app`,sequenceMetadataUrl:t.sequenceMetadataUrl||`https://metadata.sequence.app`,sequenceApiUrl:t.sequenceApiUrl||`https://api.sequence.app`,keyMachineUrl:t.keyMachineUrl||`https://keymachine.sequence.app`,solanaRpcUrl:t.solanaRpcUrl?.trim()||void 0,walletConnectProjectId:r,slippageTolerance:t.slippageTolerance??`0.05`,debug:n,commitHash:be(),hasAdapters:!!o,intentProtocol:t.intentProtocol,sequenceSupport:s}),[t.trailsApiKey,t.trailsApiUrl,t.trailsAppUrl,t.sequenceIndexerUrl,t.sequenceMetadataUrl,t.sequenceNodeGatewayUrl,t.sequenceApiUrl,t.keyMachineUrl,t.solanaRpcUrl,t.slippageTolerance,t.intentProtocol,s,n,o,r]);q(()=>{Ne({trailsApiKey:c.trailsApiKey,trailsApiUrl:c.trailsApiUrl,sequenceNodeGatewayUrl:c.sequenceNodeGatewayUrl,solanaRpcUrl:c.solanaRpcUrl,intentProtocol:c.intentProtocol})},[c.trailsApiKey,c.trailsApiUrl,c.sequenceNodeGatewayUrl,c.solanaRpcUrl,c.intentProtocol]),q(()=>{c.trailsApiKey&&af(c.trailsApiKey)},[c.trailsApiKey]);let l=J(()=>({trailsApiKey:c.trailsApiKey,sequenceApiUrl:c.sequenceApiUrl,sequenceIndexerUrl:c.sequenceIndexerUrl,sequenceMetadataUrl:c.sequenceMetadataUrl}),[c.trailsApiKey,c.sequenceApiUrl,c.sequenceIndexerUrl,c.sequenceMetadataUrl]),u=c.sequenceSupport?.Provider,d=o?.Provider,f=o?.providerProps??{},p=u?Z(u,{config:l,children:Z(Cx,{children:e})}):Z(Cx,{children:e}),m=d?Z(d,{...f,children:p}):p;return Z(Rx,{children:Z(zx.Provider,{value:{config:c,hasExplicitWalletConnectProjectId:t.walletConnectProjectId!==void 0},children:Z(V_,{children:m})})})};function Vx(){let e=hr(zx);if(!e)throw Error(`useTrails must be used within a TrailsProvider`);return e.config}function Hx(){let{trailsApiUrl:e,trailsApiKey:t}=Vx();return Or(ic.supported({trailsApiUrl:e,trailsApiKey:t}))}function Ux(){let{trailsApiKey:e,sequenceNodeGatewayUrl:t}=Vx();return or.useCallback((n,r)=>{let i=$(n,{sequenceProjectAccessKey:e,sequenceNodeGatewayUrl:t});return i?pn({chain:i,transport:ot(n,{trailsApiKey:e,sequenceNodeGatewayUrl:t},r)}):(s.console.warn(`[trails-sdk] Chain ${n} not found. Returning null RPC client.`),null)},[e,t])}function Wx(e){let t=Ux();return or.useMemo(()=>!e||W(e)?null:t(e),[e,t])}const Gx=()=>{try{let e=navigator.language||navigator.languages?.[0];if(e){let t=e.split(`-`);if(t.length===2&&t[1]&&t[1].length===2)return s.console.log(`[geolocation] Detected user country from locale:`,t[1]),t[1]}let t=Intl.DateTimeFormat().resolvedOptions().timeZone,n={"America/New_York":`US`,"America/Chicago":`US`,"America/Denver":`US`,"America/Los_Angeles":`US`,"America/Toronto":`CA`,"America/Vancouver":`CA`,"Europe/London":`GB`,"Europe/Paris":`FR`,"Europe/Berlin":`DE`,"Europe/Rome":`IT`,"Europe/Madrid":`ES`,"Europe/Amsterdam":`NL`,"Europe/Brussels":`BE`,"Europe/Vienna":`AT`,"Europe/Zurich":`CH`,"Europe/Stockholm":`SE`,"Europe/Oslo":`NO`,"Europe/Copenhagen":`DK`,"Europe/Helsinki":`FI`,"Europe/Dublin":`IE`,"Europe/Luxembourg":`LU`,"Asia/Tokyo":`JP`,"Asia/Seoul":`KR`,"Asia/Singapore":`SG`,"Asia/Hong_Kong":`HK`,"Australia/Sydney":`AU`,"Australia/Melbourne":`AU`,"Pacific/Auckland":`NZ`};return t&&n[t]?(s.console.log(`[geolocation] Detected user country from timezone:`,n[t]),n[t]):(s.console.log(`[geolocation] Could not detect user country from browser`),null)}catch(e){return s.console.error(`[geolocation] Error detecting user country from browser:`,e),null}},Kx=async()=>{try{let e=await fetch(`https://ipapi.co/json/`);if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if(t.country_code)return t.country_code}catch(e){s.console.error(`[geolocation] IP-based country detection failed`,e)}return s.console.log(`[geolocation] Falling back to browser-based detection`),Gx()||`US`};async function qx(e){return(await e.getCountryList()).countries}const Jx={all:[`geo`],countryCode:()=>wr({queryKey:[...Jx.all,`countryCode`],queryFn:()=>Kx(),staleTime:Te,gcTime:Te,retry:2,...cs,persister:ps.persisterFn}),countryList:e=>{let t=!!e;return wr({queryKey:[...Jx.all,`countryList`],queryFn:t?()=>qx(e):Tr,staleTime:Te,gcTime:Te,...cs,retry:3,retryDelay:De,persister:ps.persisterFn})}};function Yx(e={}){return Or({...Jx.countryCode(),enabled:e.enabled})}function Xx(){let e=gs();return Or(Jx.countryList(e))}const Zx=(e,t)=>{let n=Or({queryKey:[`waitIntentReceipt`,e],queryFn:async()=>{if(!e)throw Error(`Intent ID is required for monitoring`);s.console.log(`[trails-sdk] 🔍 Monitoring intent receipt for ${e}`);let n=await t.waitIntentReceipt({intentId:e});return s.console.log(`[trails-sdk] 📊 Intent ${e} status: ${n.intentReceipt.status}, done: ${n.done}`),n},enabled:!!e,refetchIntervalInBackground:!0,refetchInterval:t=>{let n=t.state.data;return n&&n.done?(s.console.log(`[trails-sdk] ✅ Intent monitoring complete for ${e}`),!1):150},retry:(t,n)=>t>=30?(s.console.error(`[trails-sdk] ❌ Giving up on intent ${e} after 30 failed API attempts:`,n),!1):!0});return{intentReceipt:n.data?.intentReceipt??null,done:n.data?.done??!1,isLoading:n.isLoading,isError:n.isError,error:n.error}};function Qx(e){let t=gs(),{data:n,isLoading:r,error:i,refetch:a}=Or({queryKey:[`earnMarkets`,e.chain,e.provider,e.type,e.sortBy,e.limit,e.offset,e.search],queryFn:()=>Tt(e,t)});return{data:n?.items,total:n?.total??0,offset:n?.offset??e.offset??0,limit:n?.limit??e.limit??0,isLoading:r,error:i,refetch:a}}const $x={56:`binance`,43114:`avalanche-c`};function eS(e){let t=e=>$x[e]??We(e);return typeof e==`number`?t(e):typeof e==`object`&&`id`in e?t(e.id):t(dt(e))}function tS(e){return(`chains`in e&&e.chains?e.chains:[e.chain]).map(t=>({address:e.walletAddress,network:eS(t),...e.marketId?{yieldId:e.marketId}:{},...e.arguments?{arguments:e.arguments}:{}}))}function nS(e){let{enabled:t=!0}=e,n=tS(e),r=gs(),{data:i,isLoading:a,error:o,refetch:s}=Or({queryKey:[`earnBalances`,n],queryFn:()=>$e({queries:n},r),enabled:t&&n.length>0});return{data:i?.items,errors:i?.errors??[],isLoading:a,error:o,refetch:s}}function rS(e={}){let t=gs(),{data:n,isLoading:r,error:i,refetch:a}=Or({queryKey:[`earnProviders`,e.limit,e.offset],queryFn:()=>Dt(e,t)});return{data:n?.items,total:n?.total??0,offset:n?.offset??e.offset??0,limit:n?.limit??e.limit??0,isLoading:r,error:i,refetch:a}}async function iS({actions:e,calls:t,data:n,recipient:r,destinationTokenAddress:i,destinationChain:a,userWalletAddress:o,sweepTarget:s,trailsClient:c,publicClient:l,intentProtocolVersion:u}){let d=!!e?.length,f=xt(t),p=f.length>0,m=!!(n&&n!==`0x`);if(Number(d)+Number(p)+Number(m)>1)throw Error(`Only one of actions, calls, or data may be specified.`);if(!d&&!p)return{recipient:r,destinationCalldata:n?.toString(),isMultiCallEncoding:!1,intentProtocolVersion:u??void 0};let h=ht({calls:d?await nt({actions:e??[],destinationChain:a,userWalletAddress:o,trailsClient:c,publicClient:l}):f,tokenAddress:i,sweepTarget:s,intentProtocolVersion:u});return{recipient:h.recipient,destinationCalldata:h.destinationCalldata,isMultiCallEncoding:h.isMultiCallEncoding,intentProtocolVersion:h.intentProtocolVersion}}function aS(e,t){return W(e)?[...t,...Ze()]:t}function oS(e,t,n){let r=Fe(e,t,aS(t,n));if(!r)throw Error(W(t)?`Could not resolve token "${e}" on chain ${t}. Pass a mint address, a known symbol (e.g. "SOL"), or register the token via TrailsProvider.`:`Could not resolve token "${e}" on chain ${t}. Pass a contract address, a supported symbol (e.g. "USDC", "ETH"), or register the token via TrailsProvider.`);return r}function sS(e,t,n){return oS(e,t,n).address}function cS(e,t,n,r){if(r){let i=Fe(r,t,aS(t,n));if(i?.token&&Pe(i.address,e))return i.token}return Gg([...aS(t,n)],e,t)??(W(t)?Be(e)??void 0:void 0)}function lS(e){let{tokenSymbol:t,chainId:n,requiredFormatted:r,availableFormatted:i}=e,a=t||`token`,o=$(n)?.name??`chain ${n}`;return Error(`Insufficient ${a} balance on ${o}. This transaction needs ${r} ${a} but your wallet only has ${i} ${a}.`)}function uS(e,t){if(t===`eip155`||t===`solana`)return t;let n=e.account?.address?.trim();if(n&&mt(n))return`eip155`;if(n&&ut(n))return`solana`;throw Error(`Trails send flows require an EVM or Solana wallet. Connect a supported wallet to continue.`)}function dS(e,t){return e?.length?t.length===0?e:e.map((e,n)=>{let r=t.find(t=>e.id&&t.id?t.id===e.id:t.label===e.label)??t[n];return r?{...e,...r}:e}):t}function fS(e){let t=ti(),{activeConnection:n}=Yr(),r=ri(),i=t?.session.session.activeAccount?.namespace??t?.namespace,o=Y(r);o.current=r;let c=Y(i);c.current=i;let l=Y(!1);l.current=Ll(n,t?.session.session.activeConnection);let u=gs(),d=Ux(),{trailsApiKey:f,sequenceIndexerUrl:p,sequenceMetadataUrl:h}=Vx(),g=kr(),{openModal:_,setPendingSelection:v,setHostTransactionState:y,setHostTransactionQuote:b,setHostTransactionStates:x,setHostTransactionTimestamp:S,hostTransactionState:C,setFeeOptions:w,pendingFeeConfirmation:T,setPendingFeeConfirmation:E,setReceiptActionButtonText:D,setOnReceiptAction:O,retryTransactionRef:k,repeatTransactionRef:A,restartOriginSelectionRef:j,setLastOriginSelection:M}=wx(),N=$h(),{supportedTokens:P}=Rc(),I=Jg(),ee=Yg(),te=jt(),ne=Y(null),re=Y(void 0),ie=Y(T);ie.current=T;let L=Y(0),R=K(e=>{y(t=>({status:e.status??t.status,details:e.details===null?void 0:e.details?{...t.details,...e.details}:t.details,error:e.error===null?void 0:e.error===void 0?t.error:e.error,result:e.result===null?void 0:e.result?{...t.result,...e.result}:t.result,retryEnabled:e.retryEnabled===void 0?t.retryEnabled:e.retryEnabled}))},[y]),ae=async(n,r,i,_)=>{s.console.log(`[trails-sdk] [useTrailsSendTransaction] Executing transaction`,{variables:n,originSelection:r});let v=()=>_===L.current,y=o.current;if(!y?.account)throw Error(`Wallet client not available. Please connect your wallet.`);uS(y,c.current);let T=y.account;if(!n.to?.token||n.to.chain===void 0)throw Error(`Transaction 'to' requires both a 'token' and a 'chain'.`);let D=dt(n.to.chain),O=sS(n.to.token,D,P);if((e?.actions?.length||xt(n.to.calls).length>0)&&!W(D)&&Pe(O,Cn)){let e=Re(D);if(!e)throw Error(`Composable actions require an ERC20 destination token, but the native token was requested on chain ${D} and no wrapped-native token is registered for it. Pass an ERC20 \`to.token\` (or the wrapped-native address) explicitly.`);s.console.log(`[trails-sdk] [useTrailsSendTransaction] Native destination token with composable actions; using wrapped-native token:`,{toChainId:D,wrappedNativeAddress:e}),O=e}let k=n.to.recipient??T.address,A=n.to.amount!==void 0||n.to.amountRaw!==void 0,j=(n.to.amountRaw??n.to.amount)?.toString()??``,M=n.to.amountRaw!==void 0,ne=A?ln.EXACT_OUTPUT:ln.EXACT_INPUT,ie,ae,z,B=!1;if(r)ie=r.fromTokenAddress,ae=r.fromChainId,z=r.fromAmount;else if(n.from?.token&&n.from.chain!==void 0)ae=dt(n.from.chain),ie=sS(n.from.token,ae,P),z=(n.from.amountRaw??n.from.amount)?.toString(),B=n.from.amountRaw!==void 0;else throw Error(`Origin token parameters are required. Provide 'from' (token + chain, plus amount for EXACT_INPUT) or select via the modal.`);if(ne===ln.EXACT_INPUT&&!z)throw Error(`Origin amount is required for this transaction. Provide 'from.amount' or 'to.amount'.`);if(ne===ln.EXACT_OUTPUT&&!j)throw Error(`Destination amount is required for EXACT_OUTPUT sends.`);let V=[];try{V=(await g.ensureQueryData(Ih.withPrices(T.address,N,u))).balances}catch(e){s.console.warn(`[trails-sdk] [useTrailsSendTransaction] Error fetching balances, proceeding with zero balance`,e),V=[]}let oe=V.find(e=>e.chainId===ae&&(Pe(e.contractAddress,ie)||!e.contractAddress&&ie===Cn))?.balance??`0`,H=0;try{let e=$(ae)?.nativeCurrency?.symbol??``;e&&(H=(await ap(u,{tokenSymbol:e,tokenAddress:Cn,chainId:ae}))?.priceUsd??0)}catch(e){s.console.warn(`[trails-sdk] [useTrailsSendTransaction] Error getting native token price`,e)}let se=cS(ie,ae,P,r?void 0:n.from?.token),ce=cS(O,D,P,n.to.token),U=W(ae)?null:d(ae),le=W(D)?null:d(D),ue=async(e,t)=>{try{if(W(t))return null;let n=t===ae?U:t===D?le:d(t);return n?Pe(e,Cn)?$(t)?.nativeCurrency?.decimals??null:await n.readContract({address:e,abi:_n,functionName:`decimals`}):null}catch(n){return s.console.error(`[trails-sdk] Error fetching decimals on-chain for token ${e} on chain ${t}:`,n),null}},de=(r?void 0:n.from?.decimals)??se?.decimals;if(de==null&&ie){let e=await ue(ie,ae);e!==null&&(de=e)}if(de==null)throw s.console.error(`[trails-sdk] [useTrailsSendTransaction] Source token decimals not found:`,{originToken:se,fromTokenAddress:ie,fromChainId:ae}),Error(`Source token decimals could not be resolved for ${ie} on chain ${ae}. Pass \`from.decimals\` explicitly, register the token via TrailsProvider's token list, or ensure the chain RPC is reachable.`);let fe=n.to.decimals??ce?.decimals;if(fe==null&&O){let e=await ue(O,D);e!==null&&(fe=e)}if(fe==null)throw s.console.error(`[trails-sdk] [useTrailsSendTransaction] Destination token decimals not found:`,{destinationToken:ce,toTokenAddress:O,toChainId:D}),Error(`Destination token decimals could not be resolved for ${O} on chain ${D}. Pass \`to.decimals\` explicitly, register the token via TrailsProvider's token list, or ensure the chain RPC is reachable.`);if(!B&&z)try{z=Sn(z,de).toString()}catch(e){throw Error(`Invalid from.amount "${z}". Pass a human-readable decimal string (e.g. "0.5"). Underlying error: ${e instanceof Error?e.message:String(e)}`,{cause:e})}if(!M)try{j=Sn(j,fe).toString()}catch(e){throw Error(`Invalid to.amount "${j}". Pass a human-readable decimal string (e.g. "3"). Underlying error: ${e instanceof Error?e.message:String(e)}`,{cause:e})}let pe=ne===ln.EXACT_OUTPUT?j:z,me=ce?.symbol??``,he=se?.symbol??``,ge=t=>{i?.trackInWidget&&x(dS(re.current,t)),e?.onStatusUpdate?.(t)},_e=te.find(e=>e.supportsChain(ae))??null,ve=_e?.buildEdgeConfig(ae)??null,ye=te.find(e=>e.supportsDestinationChain?.(D))??null;if(W(ae)){if(!_e)throw Error(`Solana origin requires @0xtrails/svm. Add svmAdapter(...) to TrailsProvider config.adapters.`);if(!ve?.signerPublicKeyBase58?.trim())throw Error(`Solana origin requires a connected Solana wallet that can sign transactions (signSerializedTransaction). Connect Phantom or Solflare via svmAdapter before sending.`)}let be=await iS({actions:e?.actions,calls:n.to.calls,data:n.to.calldata??void 0,recipient:k,destinationTokenAddress:O,destinationChain:D,userWalletAddress:T.address,sweepTarget:T.address,trailsClient:u,publicClient:le??null,intentProtocolVersion:e?.intentProtocolVersion}),{send:xe,quote:Se,feeOptions:Ce}=await s_({queryClient:g,account:T,originTokenAddress:ie,originChainId:ae,originTokenBalance:oe,destinationChainId:D,recipient:be.recipient,destinationTokenAddress:O,swapAmount:pe,tradeType:ne,originTokenSymbol:he,destinationTokenSymbol:me,client:y,trailsClient:u,destinationCalldata:be.destinationCalldata,onTransactionStateChange:ge,sourceTokenDecimals:de,destinationTokenDecimals:fe,slippageTolerance:e?.slippageTolerance?.toString(),originNativeTokenPriceUsd:H,swapProvider:e?.swapProvider,bridgeProvider:e?.bridgeProvider,commitIntentFn:e=>I.mutateAsync(e),executeIntentFn:ee.mutateAsync,checkoutOnHandlers:e?.checkoutOnHandlers,sequenceIndexerUrl:p,sequenceMetadataUrl:h,sequenceProjectAccessKey:f,originPublicClient:U??void 0,destinationPublicClient:le??void 0,isSmartWallet:e?.isSmartWallet??void 0,intentProtocolVersion:be.intentProtocolVersion,mode:e?.mode??void 0,isMultiCallEncoding:be.isMultiCallEncoding,walletId:t?.session.session.activeConnection?.walletId??void 0,...ve?{edge:mo(ve)}:{},..._e?{edgePlugin:_e}:{},...ye?{destinationEdgePlugin:ye}:{}});if(!v())throw new m;if(!r&&n.from?.token&&n.from?.chain!==void 0&&Se?.noSufficientBalance){let e=de!=null&&oe?vn(BigInt(oe),de):`0`,t=lS({tokenSymbol:he||n.from?.token||`token`,chainId:ae,requiredFormatted:Se.originAmountFormatted??`the required amount`,availableFormatted:e});throw i?.trackInWidget&&(b(null),re.current=void 0,x([]),R({status:`error`,error:a(t),retryEnabled:!1,result:null})),t}let we=Hl({originChainId:ae,feeOptions:Ce?.feeOptions,walletRequiresFeeOptions:l.current,showFeeOptions:e?.showFeeOptions,tracksWidget:!!i?.trackInWidget})===`sdk-selectable`;i?.trackInWidget&&(b(Se??null),w(we?Ce??null:null),re.current=Se?.transactionStates,x(Se?.transactionStates??[]),R({status:`confirmation`,error:null}),C.details||R({details:{to:k,tokenAddress:O,tokenAmount:ne===ln.EXACT_OUTPUT?n.to.amount??void 0:void 0,toChainId:D,data:n.to.calldata??void 0}}),(!C.status||C.status===`idle`)&&S(Date.now()));let Te=null;if(we&&(Te=await new Promise((e,t)=>{E({resolve:e,reject:t})}),E(void 0)),!v())throw new m;try{i?.trackInWidget&&R({retryEnabled:!1});let{depositUserTxnReceipt:e,destinationIntentTransaction:t,totalCompletionSeconds:n}=await xe({selectedFeeOption:Te,onOriginSend:()=>{i?.trackInWidget&&v()&&(S(Date.now()),R({status:`pending`,error:null}))}});return i?.trackInWidget&&v()&&R({status:`success`,result:{originTxHash:e?.transactionHash,originExplorerUrl:e?.transactionHash?Xa({txHash:e.transactionHash,chainId:ae}):void 0,destinationTxHash:t?.txnHash,destinationExplorerUrl:t?.txnHash?Xa({txHash:t.txnHash,chainId:D}):void 0}}),{originTransaction:{transactionHash:e?.transactionHash,explorerUrl:Xa({txHash:e?.transactionHash,chainId:ae}),receipt:e},destinationTransaction:{transactionHash:t?.txnHash,explorerUrl:Xa({txHash:t?.txnHash,chainId:D}),receipt:t},totalCompletionSeconds:n}}catch(e){throw e instanceof m?e:v()?(i?.trackInWidget&&(F(e)?R({status:`confirmation`,error:null,retryEnabled:!0}):R({status:`error`,error:a(e),retryEnabled:!1})),e):new m(void 0,{cause:e})}},z=Dr({mutationFn:async t=>{s.console.log(`[trails-sdk] [useTrailsSendTransaction] Starting transaction`,t);let n=ie.current;n&&(n.reject(new m),E(void 0)),L.current+=1;let i=L.current;if(ne.current=t,R({retryEnabled:!1}),D(e?.receiptActionButtonText??`Transact Again`),O(()=>e?.onReceiptAction??null),!t.to?.token||t.to.chain===void 0)throw Error(`Transaction 'to' requires both a 'token' and a 'chain'.`);let o=!!t.from?.token&&t.from?.chain!==void 0;if(o&&!r?.account)throw Error("Wallet client not available. Please connect your wallet before sending with a specified `from` token.");let c=dt(t.to.chain),l=sS(t.to.token,c,P),d=t.to.recipient??r?.account?.address,f=t.from?.token&&t.from.chain!==void 0?cS(sS(t.from.token,dt(t.from.chain),P),dt(t.from.chain),P,t.from.token):void 0,p=t.to.amount!==void 0||t.to.amountRaw!==void 0,h=o,y=t.from?.amount!==void 0||t.from?.amountRaw!==void 0,C=h&&(p||y),w=!0,T=null;if(r?.account&&C&&!p&&t.from)try{let e=dt(t.from.chain),n=sS(t.from.token,e,P),i=t.from.amountRaw===void 0?t.from.amount:BigInt(t.from.amountRaw);if(i&&i!==`0`){let{balances:a}=await g.ensureQueryData(Ih.withPrices(r.account.address,N,u));if(w=Mh(a,n,i,e),s.console.log(`[trails-sdk] [useTrailsSendTransaction] Origin token balance check:`,{tokenAddress:n,amount:i,chainId:e,hasSufficientBalance:w}),!w){let r=a.find(t=>(t.chainId??0)===e&&(Pe(t.contractAddress,n)||!t.contractAddress&&n===Cn)),o=cS(n,e,P,t.from.token),s=t.from.decimals??r?.decimals??o?.decimals,c=r?.symbol??o?.symbol??t.from.token,l=r?.balanceFormatted??(s!=null&&r?.balance?vn(BigInt(r.balance),s):`0`);T=lS({tokenSymbol:c,chainId:e,requiredFormatted:t.from.amountRaw!==void 0&&s!=null?vn(BigInt(t.from.amountRaw),s):String(t.from.amount??i),availableFormatted:l})}}}catch(e){s.console.warn(`[trails-sdk] [useTrailsSendTransaction] Error checking origin balance, proceeding to quote (insufficiency surfaces from the quote):`,e),w=!0}if(T)throw R({status:`error`,error:a(T),details:{to:d,tokenAddress:l,tokenAmount:t.to.amount??void 0,toChainId:c,data:t.to.calldata??void 0,originToken:f},retryEnabled:!1,result:null}),b(null),re.current=void 0,x([]),_(),T;let k=!C;s.console.log(`[trails-sdk] [useTrailsSendTransaction] Origin selection decision:`,{hasOriginParams:C,hasSufficientOriginBalance:w,isExactOutputRequest:p,needsOriginSelection:k});let A=null,j=null;if(k&&p&&!h)try{let e=cS(l,c,P,t.to.token),n=t.to.decimals??e?.decimals,r=t.to.amount===void 0?t.to.amountRaw!==void 0&&n!=null?Number(vn(BigInt(t.to.amountRaw),n)):null:Number(t.to.amount),i=await ap(u,{tokenSymbol:e?.symbol??t.to.token,tokenAddress:l,chainId:c}),a=Number(i?.priceUsd??0);r!=null&&Number.isFinite(r)&&r>0&&Number.isFinite(a)&&a>0&&(A=r*a,j=Ks(A))}catch(e){s.console.warn(`[trails-sdk] [useTrailsSendTransaction] Could not compute destination target USD for origin token selection:`,e)}if(k){let e=!p,n={to:d,tokenAddress:l,tokenAmount:t.to.amount??void 0,toChainId:c,data:t.to.calldata??void 0,targetAmountUsd:A,targetAmountUsdFormatted:j};return R({status:`awaiting-origin`,details:n,error:null,result:null}),b(null),re.current=void 0,x([]),S(Date.now()),new Promise((n,r)=>{v({resolve:async e=>{try{ne.current={...t,from:{token:e.fromTokenAddress,chain:e.fromChainId,amount:e.fromAmount}},M({tokenAddress:e.fromTokenAddress,chainId:e.fromChainId,amount:e.fromAmount}),R({status:`quoting`,details:e.originToken?{originToken:e.originToken}:void 0}),n(await ae(t,e,{trackInWidget:!0},i))}catch(e){if(e instanceof m){r(e);return}F(e)||R({status:`error`,error:a(e)}),r(e)}},reject:e=>{let t=e instanceof Error?e:Error(String(e));R({status:`error`,error:a(t)}),r(t)},requireAmountInput:e}),setTimeout(()=>{s.console.log(`[trails-sdk] [useTrailsSendTransaction] Calling openModal()`),_()},0)})}let I={to:d,tokenAddress:l,tokenAmount:t.to.amount??void 0,toChainId:c,data:t.to.calldata??void 0,originToken:f};return R({status:`quoting`,details:I,error:null,result:null}),b(null),re.current=void 0,x([]),S(Date.now()),_(),ae(t,void 0,{trackInWidget:!0},i)},onSuccess:(t,n)=>{s.console.log(`[trails-sdk] [useTrailsSendTransaction] Transaction successful`,{data:t,variables:n}),g.invalidateQueries({queryKey:[`prepareSend`]}),e?.onSuccess?.(t,n)},onError:(t,n)=>{s.console.error(`[trails-sdk] [useTrailsSendTransaction] Transaction error`,{error:t,variables:n});let r=a(t),i=t instanceof m,o=F(t);C.status!==`idle`&&!o&&!i&&R({status:`error`,error:r}),i||e?.onError?.(Error(r),n)},onSettled:(t,n,r)=>{s.console.log(`[trails-sdk] [useTrailsSendTransaction] Transaction settled`,{data:t,error:n,variables:r}),n instanceof m||e?.onSettled?.(t,n,r)}}),B=K((e,t)=>{z.mutate(e,{onSuccess:e=>{t?.onSuccess?.(e)},onError:e=>{e instanceof m||t?.onError?.(e)},onSettled:(e,n)=>{n instanceof m||t?.onSettled?.(e,n)}})},[z]),V=K(async(e,t)=>z.mutateAsync(e,{onSuccess:e=>{t?.onSuccess?.(e)},onError:e=>{e instanceof m||t?.onError?.(e)},onSettled:(e,n)=>{n instanceof m||t?.onSettled?.(e,n)}}),[z]),oe=K(()=>{ne.current&&B(ne.current)},[B]);return k.current=oe,A.current=oe,j.current=K(()=>{let e=ne.current;e&&B({...e,from:void 0})},[B]),{sendTransaction:B,sendTransactionAsync:V,retry:oe,data:z.data,error:z.error,isPending:z.isPending,isSuccess:z.isSuccess,isError:z.isError,isIdle:z.isIdle,status:z.status,reset:z.reset,variables:z.variables}}function pS(e){return fS(e)}function mS(){let{isModalOpen:e,openModal:t,closeModal:n,...r}=wx();return{...r,isOpen:e,open:t,close:n}}function hS(e){let t=e??ct();if(t.length===0)throw Error(`[trails-sdk] evmAdapter requires at least one EVM chain`);return t}function gS(e){let t=Array.isArray(e)?e:[e];if(t.length===0)throw Error(`[trails-sdk] evmAdapter requires at least one wallet`);let n=t.map(e=>({...e,showDisconnect:e.showDisconnect??!0}));return Array.isArray(e)?n:n[0]}function _S(e){return Fr({wallets:gS(e.wallets),chains:hS(e.chains),runtime:e.runtime??`eip1193`,supportsWalletSelection:e.supportsWalletSelection??!0})}function vS(e){return e?.toUpperCase()||`UNKNOWN`}function yS(e,t,n){let r=Array.isArray(e)?e.filter(Boolean):[];if(r.length===0)return{routeProviders:[]};let i=t!=null&&n!=null&&t!==n;return r.length===1?{routeProviders:r,swapProviderUsed:i?void 0:r[0],bridgeProviderUsed:i?r[0]:void 0}:{routeProviders:r,swapProviderUsed:r[0],bridgeProviderUsed:r[r.length-1]}}function bS(e){let t=e,n=e.receipt,r=n.depositTransaction?.txnHash,i=n.originTransaction?.txnHash,a=n.destinationTransaction?.txnHash,o=n.refundTransaction?.txnHash,s=n.depositTransaction?.status,c=n.originTransaction?.status,l=n.destinationTransaction?.status,u=n.refundTransaction?.status,d=e.intentId,f=e.status,p=n.ownerAddress,m=n.originChainId,h=n.destinationChainId,g=n.summary?.originIntentAddress||``,_=n.summary?.destinationIntentAddress||``,v=n.summary?.originTokenAddress||n.originTransaction?.tokenAddress||n.depositTransaction?.tokenAddress||``,y=n.summary?.originTokenAmount||n.originTransaction?.tokenAmount||n.depositTransaction?.tokenAmount||0n,b=n.summary?.destinationTokenAddress||n.destinationTransaction?.tokenAddress||``,x=n.summary?.destinationTokenAmount||n.destinationTransaction?.tokenAmount||0n,S=n.summary?.destinationToAddress||p,C=n.createdAt||e.createdAt,w=yS(n.summary?.routeProviders,m,h),T=t.intentProtocol||(n.intentProtocol??void 0)||(n.summary?.intentProtocol??void 0),E=n.summary?.originTokenMetadata,D=n.summary?.destinationTokenMetadata,O=n.edge??n.summary?.edge??null;return{originIntentAddress:g,destinationIntentAddress:_,mainSigner:p,mode:n.summary?.mode,intentId:d,metaTxnId:d,txnHash:i||a||void 0,intentStatus:vS(f),executionStatus:vS(f),originChainId:m,destinationChainId:h,originTokenAddress:v,originTokenAmount:y.toString(),destinationTokenAddress:b||``,destinationTokenAmount:(x||0n).toString(),destinationToAddress:S,createdAt:C,depositTransactionHash:r,originTransactionHash:i,destinationTransactionHash:a,depositTransactionStatus:s,originTransactionStatus:c,destinationTransactionStatus:l,refundTransactionHash:o,refundTransactionStatus:u,refundTransactionChainId:n.refundTransaction?.chainId,originToken:E&&v&&v!==``?{symbol:E.symbol||``,name:E.name||``,decimals:E.decimals??18,imageUrl:E.logoUri??``,chainId:E.chainId}:void 0,destinationToken:D&&b&&b!==``?{symbol:D.symbol||``,name:D.name||``,decimals:D.decimals??18,imageUrl:D.logoUri??``,chainId:D.chainId}:void 0,routeProviders:w.routeProviders,swapProviderUsed:w.swapProviderUsed,bridgeProviderUsed:w.bridgeProviderUsed,balances:e.balances,hasBalance:e.hasBalance,intentProtocol:T,edge:O?{rail:O.rail,mode:O.mode,token:(()=>{if(O.edgeTokenMetadata)return{symbol:O.edgeTokenMetadata.symbol||``,name:O.edgeTokenMetadata.name||``,decimals:O.edgeTokenMetadata.decimals??18,imageUrl:O.edgeTokenMetadata.logoUri??``,chainId:O.rail===`SOLANA`?101:O.edgeTokenMetadata.chainId};if(O.edgeTokenAddress&&O.rail===`SOLANA`){let e=Be(O.edgeTokenAddress);return e?{symbol:e.symbol,name:e.name||``,decimals:e.decimals,imageUrl:e.imageUrl??``,chainId:101}:void 0}})(),tokenAmount:O.edgeTokenAmount?.toString(),userAddress:O.edgeUserAddress,initTransactionHash:O.initTransactionHash,fillTransactionHash:O.fillTransactionHash,refundTransactionHash:O.refundTransactionHash}:void 0}}async function xS(e,t){let n=e.executionStatus===`EXECUTING`||e.executionStatus===`PROCESSING`,r=e.createdAt?new Date(e.createdAt).getTime():null;if(!(n&&r&&Date.now()-r>6e4))return{refunded:!1,failed:!1};let i=[];t.originIntentTxHash&&e.originChainId&&i.push({hash:t.originIntentTxHash,chainId:e.originChainId}),t.originIntentDepositTxHash&&e.originChainId&&i.push({hash:t.originIntentDepositTxHash,chainId:e.originChainId}),t.destinationIntentTxHash&&e.destinationChainId&&i.push({hash:t.destinationIntentTxHash,chainId:e.destinationChainId}),t.destinationIntentDepositTxHash&&e.destinationChainId&&i.push({hash:t.destinationIntentDepositTxHash,chainId:e.destinationChainId}),e.originTransactionHash&&e.originChainId&&i.push({hash:e.originTransactionHash,chainId:e.originChainId}),e.destinationTransactionHash&&e.destinationChainId&&i.push({hash:e.destinationTransactionHash,chainId:e.destinationChainId});for(let{hash:e,chainId:t}of i)if(!W(t))try{let n=$(t);if(!n)continue;let r=await Va(n.id).getTransactionReceipt({hash:e}),i=Qm(r).some(e=>e.type===`Refund`||e.type===`RefundAndSweep`),a=$m(r).some(e=>e.type===`CallFailed`);if(i)return s.console.log(`[trails-sdk] Found refund event in transaction`,{hash:e,chainId:t}),{refunded:!0,failed:!1};if(a)return s.console.log(`[trails-sdk] Found CallFailed event in transaction`,{hash:e,chainId:t}),{refunded:!1,failed:!0}}catch(n){s.console.warn(`[trails-sdk] Failed to decode events for transaction`,{hash:e,chainId:t,error:n})}return{refunded:!1,failed:!1}}function SS(e,t,n){let{executionStatus:r,originChainId:i,destinationChainId:a,originIntentAddress:o,destinationIntentAddress:s,createdAt:c}=e,l=e.depositTransactionStatus,u=e.originTransactionStatus,d=e.destinationTransactionStatus;if(e.intentStatus){let t=vS(e.intentStatus);if(t===`INVALID`||t===`REFUNDED`||t===`ABORTED`)return t}if(e.edge?.refundTransactionHash)return`REFUNDED`;if(d&&d!==`ABORTED`&&d!==`UNKNOWN`)return vS(d);if(!d&&u&&u!==`ABORTED`&&u!==`UNKNOWN`)return vS(u);if(l===`ABORTED`&&!(u&&u!==`ABORTED`)&&!(d&&d!==`ABORTED`)||u===`ABORTED`&&!d||d===`ABORTED`)return`ABORTED`;if(n.refunded)return`REFUNDED`;if(n.failed)return`FAILED`;if(r&&r!==`UNKNOWN`&&r!==`EXECUTING`)return r;let f=o?.toLowerCase()===s?.toLowerCase()&&i===a,p=!s||!a||f,m=c?Date.now()-new Date(c).getTime()>5*ge:!1;return t.destinationIntentTxHash||t.originIntentTxHash&&i&&p?`SUCCEEDED`:t.originIntentDepositTxHash&&!t.originIntentTxHash?`PENDING`:t.originIntentTxHash&&!t.destinationIntentTxHash&&i&&a&&!f&&s?m?`FAILED`:`PENDING`:r||`UNKNOWN`}async function CS(e){let t=e.originIntentAddress?.toLowerCase()===e.destinationIntentAddress?.toLowerCase()&&e.originChainId===e.destinationChainId,n=e.originTransactionHash,r=e.destinationTransactionHash,i,a,o=e.depositTransactionHash,s;n&&e.originChainId&&(i=Xa({txHash:n,chainId:e.originChainId})),r&&e.destinationChainId&&(a=Xa({txHash:r,chainId:e.destinationChainId})),o&&e.originChainId&&(s=Xa({txHash:o,chainId:e.originChainId}));let c=await xS(e,{originIntentTxHash:n,destinationIntentTxHash:r,originIntentDepositTxHash:o,destinationIntentDepositTxHash:void 0}),l=SS(e,{originIntentTxHash:n,destinationIntentTxHash:r,originIntentDepositTxHash:o,destinationIntentDepositTxHash:void 0},c);return{...e,...t?{destinationIntentAddress:``,destinationChainId:void 0}:{},originIntentTxHash:n,destinationIntentTxHash:r,originIntentTxExplorerUrl:i,destinationIntentTxExplorerUrl:a,originIntentDepositTxHash:o,destinationIntentDepositTxHash:void 0,originIntentDepositTxExplorerUrl:s,destinationIntentDepositTxExplorerUrl:void 0,executionStatus:l}}function wS(e,t){let n=e.originToken;if(!n&&e.originTokenAddress&&e.originChainId){let r;r=bt(e.originTokenAddress)?t.find(t=>t.isNativeToken&&t.chainId===e.originChainId):t.find(t=>t.contractAddress.toLowerCase()===e.originTokenAddress?.toLowerCase()&&t.chainId===e.originChainId),r&&(n={symbol:r.symbol,name:r.name,decimals:r.decimals,imageUrl:r.imageUrl||``,chainId:e.originChainId})}let r=e.destinationToken;if(!r&&e.destinationTokenAddress&&e.destinationChainId){let n;n=bt(e.destinationTokenAddress)?t.find(t=>t.isNativeToken&&t.chainId===e.destinationChainId):t.find(t=>t.contractAddress.toLowerCase()===e.destinationTokenAddress?.toLowerCase()&&t.chainId===e.destinationChainId),n&&(r={symbol:n.symbol,name:n.name,decimals:n.decimals,imageUrl:n.imageUrl||``,chainId:e.destinationChainId})}return n===e.originToken&&r===e.destinationToken?e:{...e,originToken:n,destinationToken:r}}function TS(e){return{originIntentAddress:e.originIntentAddress,destinationIntentAddress:e.destinationIntentAddress||``,mainSigner:e.ownerAddress,intentId:e.intentId,originChainId:e.originChainId,destinationChainId:e.destinationChainId,originTokenAddress:e.originTokenAddress,destinationTokenAddress:e.destinationTokenAddress,originTokenAmount:e.depositTransaction?.amount?.toString(),createdAt:e.createdAt}}function ES({accountAddress:e,edgeAddress:t,pageSize:n=10,enabled:r=!0,refetchInterval:i,intentStatuses:a}){let o=Vx(),c=kr(),{supportedTokens:l}=Rc(),[u,d]=X(0),[f,p]=X([void 0]),m=f[u],h={staleTime:5*ge,gcTime:5*ge,retry:!1,refetchInterval:i||void 0,refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,structuralSharing:!1},g=async(e,t)=>{let n=hs({apiKey:o.trailsApiKey,hostname:o.trailsApiUrl});s.console.log(`[trails-sdk] getIntentHistory (${t}) request:`,e);let r=await n.getIntentHistory(e);return s.console.log(`[trails-sdk] getIntentHistory (${t}) response:`,{intentCount:r.intents?.length||0,hasNextPage:r.nextPage?.more??!1}),{transactions:await Promise.all((r.intents||[]).map(bS).map(async e=>{try{return await CS(e)}catch(n){return s.console.warn(`[trails-sdk] Failed to enrich ${t} transaction, using raw data:`,n),e}})),nextPage:r.nextPage}},_=e=>({...e,includeBalances:!0,page:m||{pageSize:n},...a&&a.length>0?{byStatuses:a}:{}}),{data:v,isLoading:y,error:b,refetch:x,isFetching:S}=Or({queryKey:[`intentTransactionHistory`,e,t,n,u,a?.join(`,`)??`all`],queryFn:async()=>{if(!e||!o.trailsApiKey)throw Error(`Account address and API key required`);let n=t?{byParticipantAddresses:[e,t]}:{byOwnerAddress:e};try{let{transactions:e,nextPage:r}=await g(_(n),t?`participant`:`owner`);return{transactions:e,nextPage:r,hasMore:r?.more??!1,isOffline:!1}}catch(t){return s.console.warn(`[trails-sdk] getIntentHistory API failed, falling back to localStorage`,t),{transactions:Om(e).map(TS),nextPage:void 0,hasMore:!1,isOffline:!0}}},enabled:r&&!!e&&!!o.trailsApiKey,...h,placeholderData:e=>e}),C=J(()=>{let e=v?.transactions??[];return e.length===0||l.length===0?e:e.map(e=>wS(e,l))},[v?.transactions,l]),w=v?.hasMore??!1,T=v?.nextPage,E=K(()=>{if(!(!w||y)){if(f[u+1]){s.console.log(`[trails-sdk] Using cached page`,u+1),d(e=>e+1);return}T&&(p(e=>{let t=[...e];return t[u+1]=T,t}),d(e=>e+1))}},[w,y,T,u,f]),D=K(()=>{u<=0||y||(s.console.log(`[trails-sdk] Going to previous page`,u-1),d(e=>e-1))},[u,y]),O=K(()=>{!w||S||T&&(p(e=>{let t=[...e];return t[u+1]=T,t}),d(e=>e+1))},[w,S,T,u]),k=K(()=>{d(e=>e===0?e:0),p(e=>e.length===1&&e[0]===void 0?e:[void 0])},[]),A=Y(e);return q(()=>{A.current!==e&&(A.current=e,k())},[e,k]),{transactions:C,loading:y||S,error:b instanceof Error?b.message:null,isOffline:v?.isOffline??!1,refetch:async()=>{await c.invalidateQueries({queryKey:[`intentTransactionHistory`,e],refetchType:`none`}),await x()},loadMore:O,hasMore:w,page:u,nextPage:E,prevPage:D,hasPrev:u>0,resetPagination:k}}function DS({intentId:e,enabled:t=!0}){let n=Vx(),r=gs(),{data:i,isLoading:a,isError:o,error:s,refetch:c}=Or({queryKey:[`getIntent`,e],queryFn:async()=>{if(!e||!n.trailsApiKey)throw Error(`Intent ID and API key required`);return(await Im(r,e)).intent},enabled:t&&!!e&&!!n.trailsApiKey});return{intent:i??null,isLoading:a,isError:o,error:s,refetch:async()=>{await c()}}}async function OS(e,t){let n=await e.getMeldPaymentMethods({fiatCurrency:t});return Array.isArray(n.paymentMethods)?n.paymentMethods:[]}async function kS(e,t){let n=await e.getMeldCryptoCurrencies({countryCode:t});return Array.isArray(n.cryptoCurrencies)?n.cryptoCurrencies:[]}async function AS(e,t={}){return(await e.getMeldServiceProviders(t)).serviceProviders||[]}async function jS(e,t){let n=await e.getMeldFiatCurrencies({countryCode:t});return Array.isArray(n.fiatCurrencies)?n.fiatCurrencies:[]}async function MS(e,t){let n=(await e.getMeldCountryDefaults({countryCode:t})).defaults?.[0];return{defaultCurrencyCode:n?.defaultCurrencyCode??void 0,defaultPaymentMethods:n?.defaultPaymentMethods||[]}}async function NS(e,t,n){let r=(await e.searchMeldTransactions({externalCustomerIds:St(t),limit:n})).transactions?.transactions||[];return{transactions:r,hasMore:r.length>=n}}const PS={all:[`meld`],paymentMethods:()=>[...PS.all,`paymentMethods`],paymentMethodList:(e,t)=>{let n=!!e&&!!t;return wr({queryKey:[...PS.paymentMethods(),t??null],queryFn:n?()=>OS(e,t):Tr,staleTime:Te,gcTime:Te,retry:ss(2),retryDelay:De,persister:ps.persisterFn,...cs})},cryptoCurrencies:()=>[...PS.all,`cryptoCurrencies`],cryptoCurrencyList:(e,t)=>{let n=!!e&&!!t;return wr({queryKey:[...PS.cryptoCurrencies(),t??null],queryFn:n?()=>kS(e,t):Tr,staleTime:Te,gcTime:Te,retry:ss(2),retryDelay:De,persister:ps.persisterFn,...cs})},serviceProviders:()=>[...PS.all,`serviceProviders`],serviceProviderList:(e,t)=>{let n=!!e;return wr({queryKey:[...PS.serviceProviders(),t??null],queryFn:n?()=>AS(e,t):Tr,staleTime:Te,gcTime:Te,retry:ss(2),retryDelay:De,persister:ps.persisterFn,...cs})},fiatCurrencies:()=>[...PS.all,`fiatCurrencies`],fiatCurrencyList:(e,t)=>{let n=!!e&&!!t;return wr({queryKey:[...PS.fiatCurrencies(),t??null],queryFn:n?()=>jS(e,t):Tr,staleTime:Te,gcTime:Te,retry:ss(2),retryDelay:De,persister:ps.persisterFn,...cs})},countryDefaults:()=>[...PS.all,`countryDefaults`],countryDefaultsByCode:(e,t)=>{let n=!!e&&!!t;return wr({queryKey:[...PS.countryDefaults(),t??null],queryFn:n?()=>MS(e,t):Tr,staleTime:10*ge,gcTime:30*ge,retry:ss(2),retryDelay:De,persister:ps.persisterFn,...cs})},transactionHistory:()=>[...PS.all,`transactionHistory`],transactionHistoryList:(e,t,n=20)=>{let r=!!e&&!!t;return wr({queryKey:[...PS.transactionHistory(),t??null,n],queryFn:r?()=>NS(e,t,n):Tr,staleTime:5*ge,gcTime:30*ge,retry:ss(2),retryDelay:De})}};function FS(e){let t=gv();return Or(PS.paymentMethodList(t,e??null))}function IS(e){let t=gv();return Or(PS.serviceProviderList(t,e))}const LS=[`JPY`,`KRW`,`VND`,`CLP`,`ISK`],RS={USD:`$`,EUR:`€`,GBP:`£`,JPY:`¥`,CNY:`¥`,KRW:`₩`,INR:`₹`,CAD:`C$`,AUD:`A$`,CHF:`CHF`,SEK:`kr`,NOK:`kr`,DKK:`kr`};function zS(e){return{decimals:LS.includes(e)?0:2,symbol:RS[e]||e}}const BS=ct();function VS({walletRuntimeMode:e,trailsConfig:t,children:n}){switch(e){case`parent`:case`none`:case`adapter`:return n;case`builtin-evm`:return Z(jr,{chains:BS,walletConnectProjectId:t.walletConnectProjectId,children:n})}}const HS=({widgetContent:e,trailsConfig:t,walletRuntimeMode:n,shouldNestTrailsProvider:r=!1})=>{let i=Qr(),a=hr(zx);return VS({walletRuntimeMode:n??(i?`parent`:`builtin-evm`),trailsConfig:t,children:a&&!r?e:Z(Bx,{config:t,children:e})})};function US(e){let{address:t,chainId:n,connectorName:r,isEvmConnected:i}=e,{screen:a}=y_(),o=Y(null),s=Y(void 0),c=Y(null),l=Y(i);q(()=>{let e=rf(),n=t?.toLowerCase()??null;if(s.current!==n){if(s.current=n,t){e.identifyUser({address:t});return}e.unidentifyUser()}},[t]),q(()=>{if(!i||!t||!n||!r)return;let e=`${t.toLowerCase()}:${n}:${r}`;c.current!==e&&(c.current=e,rf().trackWalletConnected({walletType:r,address:t,chainId:n}))},[i,t,n,r]),q(()=>{let e=`${a}:${t??``}`;o.current!==e&&(o.current=e,of({screen:a,userAddress:t}))},[a,t]),q(()=>{let e=l.current;l.current=i,!(!e||i)&&(c.current=null,s.current=null,uf())},[i])}function WS(e){return Object.entries(e).map(([e,t])=>`${e}: ${t};`).join(`
46
+ `)}const GS=Te;function KS(e){return{id:e.id,name:e.name,protocol:e.protocol,chainId:e.chainId,apy:e.apy,tvl:e.tvl,token:{symbol:e.token.symbol,name:e.token.name,address:e.token.address,decimals:e.token.decimals,logoUrl:e.token.logoUrl},depositAddress:e.depositAddress,isActive:e.isActive,poolUrl:e.poolUrl,protocolUrl:e.protocolUrl,wrappedTokenGatewayAddress:e.wrappedTokenGatewayAddress}}function qS({enabled:e=!0}={}){let t=gs(),n=Or({queryKey:[`pools`,`api`,`v1`,e],queryFn:async()=>{if(!e)return[];s.console.log(`[trails-sdk] Fetching pools from API...`);try{let e=await t.getEarnPools({chainIds:[1,8453,42161,137,10,100],minTvl:1e6,maxApy:20});s.console.log(`[trails-sdk] Fetched`,e.pools.length,`pools from API`,e.cached?`(cached)`:`(fresh)`);let n=e.pools.map(KS);return n.sort((e,t)=>t.apy-e.apy),n}catch(e){throw s.console.error(`[trails-sdk] Failed to fetch pools from API:`,e),e}},enabled:e&&!!t,staleTime:GS,gcTime:GS,refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:2,persister:ps.persisterFn});return{data:n.data||[],loading:n.isLoading,error:n.error}}function JS(e,t,n){try{if(!e)throw Error(`Wallet client is required`);if(!t)throw Error(`Pool is required`);if(!t.token?.address)throw Error(`Pool token address is required`);if(!t.token.address.startsWith(`0x`)||t.token.address.length!==42)throw Error(`Invalid pool token address: ${t.token.address}`);let r=e?.account?.address||e?.account;if(!r)throw Error(`User address not found`);let i=typeof r==`string`?r:String(r);if(!i.startsWith(`0x`)||i.length!==42)throw Error(`Invalid user address: ${i}`);if(!Ss(n))throw Error(`Invalid amount: ${n}`);if(!Cs(n))throw Error(`Invalid amount format: ${n}`);let a=BigInt(n),o=gn({abi:[{name:`supply`,type:`function`,inputs:[{name:`asset`,type:`address`},{name:`amount`,type:`uint256`},{name:`onBehalfOf`,type:`address`},{name:`referralCode`,type:`uint16`}],outputs:[],stateMutability:`nonpayable`}],args:[t.token.address,a,i,0]});return s.console.log(`Generated Aave supply calldata:`,o),o}catch(e){s.console.error(`Error generating Aave deposit calldata:`,e);return}}function YS(e,t){try{let n=e?.account?.address||e?.account;if(!n)throw Error(`User address not found`);if(!Ss(t))throw Error(`Invalid amount`);let r=gn({abi:[{name:`deposit`,type:`function`,inputs:[{name:`assets`,type:`uint256`},{name:`receiver`,type:`address`}],outputs:[{name:`shares`,type:`uint256`}],stateMutability:`nonpayable`}],args:[BigInt(t),n]});return s.console.log(`Generated Morpho deposit calldata:`,r),r}catch(e){s.console.error(`Error generating Morpho deposit calldata:`,e);return}}function XS(e,t){let n=e,r=n.sourceCurrencyCode||n.fiatCurrency,i=n.destinationCurrencyCode||n.cryptoCurrency,a=F_(r),o=F_(i);return{id:e.id||n.transactionId||``,status:n.status||`PENDING`,sourceAmount:n.sourceAmount,sourceCurrencyCode:r,destinationAmount:n.destinationAmount,destinationCurrencyCode:i,walletAddress:n.walletAddress||n.destinationAddress,createdAt:n.createdAt||n.createdDate||n.timestamp,updatedAt:n.updatedAt||n.updatedDate,serviceProvider:n.serviceProvider||n.provider||n.institutionName,paymentMethod:n.paymentMethod||n.paymentMethodType,transactionHash:n.transactionHash||n.hash,externalSessionId:n.externalSessionId||n.sessionId,externalCustomerId:n.externalCustomerId||n.customerId,countryCode:n.countryCode,exchangeRate:n.exchangeRate,totalFee:n.totalFee,networkFee:n.networkFee,transactionFee:n.transactionFee,institutionName:n.institutionName,lowKyc:n.lowKyc,sourceCurrencySymbol:P_(a.symbol),destinationCurrencySymbol:P_(o.symbol),paymentMethodLogo:ZS(n.paymentMethod||n.paymentMethodType,t),currencyFlag:I_(n.countryCode),sourceTokenSymbol:a.symbol,sourceTokenChainId:a.chainId,sourceTokenAddress:void 0,destinationTokenSymbol:o.symbol,destinationTokenChainId:o.chainId,destinationTokenAddress:void 0}}function ZS(e,t){if(!e||!t)return``;let n=t.find(t=>Pe(t.paymentMethod,e)||Pe(t.name,e));return n?.logos&&(n.logos.light||n.logos.dark)||``}function QS({enabled:e=!0,limit:t=20,autoRefetch:n=!1,refetchInterval:r=10*Ee}={}){let{address:i}=Kr(),a=gv(),{data:o}=FS(`USD`),{data:s,isLoading:c,error:l,refetch:u,isFetching:d}=Or({...PS.transactionHistoryList(a,i,t),enabled:e,...n&&{staleTime:0},refetchInterval:n?r:!1,placeholderData:e=>e});return{transactions:J(()=>s?.transactions?.length?s.transactions.map(e=>XS(e,o)):[],[s,o]),loading:c||d,error:l instanceof Error?l.message:null,refetch:async()=>{await u()},hasMore:s?.hasMore??!1}}const $S={all:`Show every transaction in your history.`,succeeded:`Completed successfully and delivered the intended result.`,executing:`Accepted and currently being processed onchain or by the backend.`,failed:`Execution was attempted but ended in a terminal error.`,aborted:`Stopped before completion and will not continue automatically.`,refunded:`Funds were returned after the original flow could not complete.`,invalid:`Rejected because the request or intent data was not valid.`,committed:`Saved and ready to execute, but execution has not started yet.`,quoted:`A quote was created, but the intent has not been committed yet.`,onramp:`Show onramp transactions such as card or exchange funding flows.`,pending:`Still waiting for the next status update.`,on_hold:`Temporarily paused until a prerequisite is met.`,mining:`Submitted onchain and waiting to be mined.`,relaying:`Being relayed between chains or systems.`,sent:`Submitted to the network and awaiting confirmation.`,errored:`Encountered an unexpected error.`,unknown:`Status is not available yet.`},eC=[{key:`all`,label:`All`,activeClass:`bg-gray-200 dark:bg-gray-600 text-gray-800 dark:text-gray-200`,tooltip:$S.all},{key:`succeeded`,label:`Succeeded`,activeClass:`bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20`,tooltip:$S.succeeded},{key:`executing`,label:`Executing`,activeClass:`bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20`,tooltip:$S.executing},{key:`failed`,label:`Failed`,activeClass:`bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20`,tooltip:$S.failed},{key:`aborted`,label:`Aborted`,activeClass:`bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20`,tooltip:$S.aborted},{key:`refunded`,label:`Refunded`,activeClass:`bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 hover:bg-amber-50 dark:hover:bg-amber-900/20`,tooltip:$S.refunded},{key:`invalid`,label:`Invalid`,activeClass:`bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 hover:bg-orange-50 dark:hover:bg-orange-900/20`,tooltip:$S.invalid},{key:`committed`,label:`Committed`,activeClass:`bg-teal-50 dark:bg-teal-900/20 text-teal-600 dark:text-teal-400 hover:bg-teal-50 dark:hover:bg-teal-900/20`,tooltip:$S.committed},{key:`quoted`,label:`Quoted`,activeClass:`bg-gray-200 dark:bg-gray-600 text-gray-800 dark:text-gray-200`,tooltip:$S.quoted},{key:`onramp`,label:`Onramp`,activeClass:`bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 hover:bg-purple-50 dark:hover:bg-purple-900/20`,tooltip:$S.onramp}],tC=new Set([`executing`,`succeeded`,`failed`,`aborted`,`refunded`,`invalid`,`committed`,`quoted`]);function nC(e){return tC.has(e)?[e.toUpperCase()]:void 0}function rC(e,t){return t===`all`?!0:t===`onramp`?!1:e.intentStatus?.toUpperCase()===t.toUpperCase()}function iC(e){return e===`all`?`No transactions found.`:e===`onramp`?`No onramp transactions found. Buy crypto to see them here.`:e===`succeeded`?`No completed transactions yet.`:`No ${e} transactions.`}function aC(e){return e?$S[e.toLowerCase()]:void 0}function oC(e,t){if(!e||!t)return!1;let n=t.toLowerCase();return!!(e.originIntentAddress?.toLowerCase().includes(n)||e.destinationIntentAddress?.toLowerCase().includes(n)||e.mainSigner?.toLowerCase().includes(n)||e.destinationToAddress?.toLowerCase().includes(n)||e.txnHash?.toLowerCase().includes(n)||e.intentId?.toLowerCase().includes(n)||e.intentId?.toLowerCase()===n||e.originTransactionHash?.toLowerCase().includes(n)||e.destinationTransactionHash?.toLowerCase().includes(n)||e.originToken?.symbol?.toLowerCase().includes(n)||e.destinationToken?.symbol?.toLowerCase().includes(n)||e.mode?.toLowerCase().includes(n)||e.executionStatus?.toLowerCase().includes(n))}function sC(e,t){if(!e||!t)return!1;let n=t.toLowerCase();return!!(e.id?.toLowerCase().includes(n)||e.walletAddress?.toLowerCase().includes(n)||e.serviceProvider?.toLowerCase().includes(n)||e.sourceAmount?.includes(t)||e.destinationAmount?.includes(t)||e.sourceCurrencyCode?.toLowerCase().includes(n)||e.destinationCurrencyCode?.toLowerCase().includes(n)||e.destinationTokenSymbol?.toLowerCase().includes(n)||e.paymentMethod?.toLowerCase().includes(n)||e.status?.toLowerCase().includes(n))}function cC({accountAddress:e,edgeAddress:t,intentPageSize:n=10,onrampLimit:r=20,enabled:i=!0,autoRefetch:a=!1,refetchInterval:o=10*Ee,intentStatuses:c}={}){let l=kr(),{transactions:u,loading:d,error:f,isOffline:p,refetch:m,loadMore:h,hasMore:g,page:_,nextPage:v,prevPage:y,hasPrev:b,resetPagination:x}=ES({accountAddress:e,edgeAddress:t,pageSize:n,enabled:i&&!!e,intentStatuses:c}),{transactions:S,loading:C,error:w,refetch:T,hasMore:E}=QS({enabled:i&&!!e,limit:r,autoRefetch:a,refetchInterval:o}),D=J(()=>{let e=[];u.forEach(t=>{e.push({type:`intent`,data:t,timestamp:t.createdAt||new Date().toISOString()})});let t=S;if(u.length>0){let e=u.map(e=>new Date(e.createdAt||0).getTime()).filter(e=>e>0);if(e.length>0){let r=Math.min(...e),i=Math.max(...e);u.length>=n&&(t=S.filter(e=>{let t=new Date(e.createdAt||e.updatedAt||0).getTime();return t>=r&&t<=i}))}}return t.forEach(t=>{e.push({type:`onramp`,data:t,timestamp:t.createdAt||t.updatedAt||new Date().toISOString()})}),e.sort((e,t)=>{let n=new Date(e.timestamp).getTime();return new Date(t.timestamp).getTime()-n}),e},[u,S,n]),O=K(async()=>{s.console.log(`[useCombinedHistory] Refetching both histories`),await l.invalidateQueries({queryKey:[`getIntent`],refetchType:`none`}),await Promise.all([m(),T()])},[l,m,T]),k=K(e=>{try{if(!e?.trim())return D;let t=e.trim().toLowerCase();return D.filter(e=>{try{return e.type===`intent`?oC(e.data,t):sC(e.data,t)}catch(e){return s.console.warn(`[useCombinedHistory] Error searching item:`,e),!1}})}catch(e){return s.console.error(`[useCombinedHistory] Error in searchItems:`,e),D}},[D]),A=K(e=>{switch(e){case`all`:return D;case`onramp`:return[...S].map(e=>({type:`onramp`,data:e,timestamp:e.createdAt||e.updatedAt||new Date().toISOString()})).sort((e,t)=>{let n=new Date(e.timestamp).getTime();return new Date(t.timestamp).getTime()-n});case`executing`:case`succeeded`:case`failed`:case`aborted`:case`refunded`:case`invalid`:case`committed`:case`quoted`:return D.filter(t=>t.type===`intent`&&rC(t.data,e));default:return D}},[D,S]),j=K((e,t)=>{try{let n=A(e);if(t?.trim()){let e=t.trim().toLowerCase();n=n.filter(t=>{try{return t?.data?t.type===`intent`?oC(t.data,e):sC(t.data,e):!1}catch(e){return s.console.warn(`[useCombinedHistory] Error filtering item:`,e),!1}})}return n}catch(e){return s.console.error(`[useCombinedHistory] Error in getFilteredAndSearchedItems:`,e),[]}},[A]);return q(()=>{if(!a||!i)return;let e=setInterval(()=>{s.console.log(`[useCombinedHistory] Auto-refetching`),O()},o);return()=>clearInterval(e)},[a,i,o,O]),{items:D,isOffline:p,isLoading:d||C,errors:{intent:f||void 0,onramp:w||void 0},hasMore:{intent:g,onramp:E},refetch:O,refetchIntent:m,refetchOnramp:T,loadMoreIntent:h,nextPageIntent:v,prevPageIntent:y,hasPrevIntent:b,currentIntentPage:_,resetIntentPagination:x,searchItems:k,filterItems:A,getFilteredAndSearchedItems:j}}function lC({evmAddress:e,solanaAddress:t,selectedFundingWallet:n}){if(n){if(Xu(n))return n.address;if(Zu(n))return t??n.address}return e||(t??void 0)}function uC(e){let{address:t}=Kr(),n=qu(),r=Hu();return J(()=>lC({evmAddress:e??t,solanaAddress:n?.publicKey?.toBase58?.(),selectedFundingWallet:r}),[e,t,r,n?.publicKey])}function dC(e,t){if(!t)return``;let n=e.find(e=>Pe(e.serviceProvider,t));return n?.logos?.light||n?.logos?.dark||n?.logos?.lightShort||n?.logos?.darkShort||``}function fC(e){return e?.toLowerCase()||`unknown`}function pC(e){switch(e){case`COMPLETED`:case`SETTLED`:return`bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200`;case`DECLINED`:case`FAILED`:case`ERROR`:return`bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200`;case`CANCELLED`:return`bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200`;case`PENDING`:return`bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200`;case`PROCESSING`:return`bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200`;case`REFUNDED`:return`bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200`;default:return`bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200`}}function mC(e){if(!e)return`-`;let t=parseFloat(e);return _s(t)?t.toLocaleString(`en-US`,{minimumFractionDigits:2,maximumFractionDigits:6}):e}const hC=({transaction:e,meldProviders:t,onClick:n,isExpanded:r=!1,onToggleExpand:i})=>{let[a,o]=X(!1),s=dC(t,e.serviceProvider),c=je(e.createdAt||e.updatedAt);return Q(`div`,{className:`border border-gray-200 dark:border-gray-700 rounded-lg p-2 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors`,children:[Z(`div`,{className:`flex items-center justify-between mb-2`,children:Q(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[Z(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200`,children:`Onramp`}),c.relative&&Z(`span`,{className:`text-xs text-gray-900 dark:text-gray-100 cursor-help`,title:c.full||void 0,children:c.relative})]})}),Z(`div`,{className:`flex items-center justify-center mb-2`,children:Q(`div`,{className:`flex items-center justify-between w-full gap-3`,children:[Q(`div`,{className:`flex items-start gap-2 flex-1 max-w-[130px]`,children:[Z(`div`,{className:`shrink-0 w-7 h-7 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center overflow-hidden`,children:e.paymentMethodLogo?Z(`img`,{src:e.paymentMethodLogo,alt:e.paymentMethod,className:`w-5 h-5 object-cover`}):Z(Pi,{className:`w-4 h-4 text-gray-500 dark:text-gray-400`})}),Q(`div`,{className:`flex flex-col gap-0.5`,children:[Q(`span`,{className:`text-xs font-medium text-gray-900 dark:text-gray-100 whitespace-nowrap overflow-hidden text-ellipsis`,style:{maxWidth:`85px`},children:[e.sourceCurrencySymbol,mC(e.sourceAmount),` `,e.sourceCurrencyCode]}),Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:e.paymentMethod||`Card`})]})]}),Z(`div`,{className:`flex items-center`,children:Z(`span`,{className:`text-xl text-gray-400 dark:text-gray-500`,children:`→`})}),Q(`div`,{className:`flex items-start gap-2 flex-1 max-w-[130px]`,children:[Z(Jy,{symbol:e.destinationTokenSymbol,chainId:e.destinationTokenChainId,contractAddress:e.destinationTokenAddress,size:28}),Q(`div`,{className:`flex flex-col gap-0.5`,children:[Q(`span`,{className:`text-xs font-medium text-gray-900 dark:text-gray-100 whitespace-nowrap overflow-hidden text-ellipsis`,style:{maxWidth:`85px`},children:[mC(e.destinationAmount),` `,e.destinationTokenSymbol]}),e.destinationTokenChainId&&Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:Ja(e.destinationTokenChainId)})]})]})]})}),Q(`div`,{className:`flex items-center justify-between mt-2`,children:[Q(`div`,{className:`flex items-center gap-2`,children:[Z(`span`,{className:`inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium ${pC(e.status)}`,children:fC(e.status)}),Q(`div`,{className:`flex items-center gap-1`,children:[Z(`div`,{className:`shrink-0 w-4 h-4 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center overflow-hidden`,title:`Provider: ${e.serviceProvider||`Unknown`}`,children:s?Z(`img`,{src:s,alt:e.serviceProvider,className:`w-3 h-3`}):Z(wi,{className:`w-2.5 h-2.5 text-gray-500 dark:text-gray-400`})}),Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:e.serviceProvider||`Provider`})]}),e.currencyFlag&&Z(`span`,{className:`text-xs`,title:`Country: ${e.countryCode}`,children:e.currencyFlag})]}),e.id&&Q(`button`,{type:`button`,onClick:async t=>{if(t.stopPropagation(),e.id)try{await de(e.id),o(!0),setTimeout(()=>o(!1),2*Ee)}catch{}},className:`font-mono text-xs bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 px-2 py-0.5 rounded flex items-center gap-1 transition-colors`,title:`Copy transaction ID: ${e.id}`,children:[Q(`span`,{className:`text-gray-600 dark:text-gray-400`,children:[e.id.slice(0,6),`...`]}),a?Z(Ti,{className:`w-3 h-3 text-green-600 dark:text-green-400`}):Z(Ni,{className:`w-3 h-3 text-gray-500 dark:text-gray-400`})]}),(n||i)&&Q(`button`,{type:`button`,onClick:()=>{n?n(e):i&&i()},className:`flex items-center justify-center gap-1 py-1 px-2 rounded-md transition-colors cursor-pointer text-xs text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700`,"aria-label":r?`Show less`:`More details`,children:[Z(`span`,{children:r?`Less`:`Details`}),Q(`svg`,{className:`w-3 h-3 transition-transform duration-300 ${r?`rotate-180`:``}`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[Z(`title`,{children:r?`Collapse`:`Expand`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M19 9l-7 7-7-7`})]})]})]}),r&&Z(`div`,{className:`mt-3 pt-3 border-t border-gray-200 dark:border-gray-700`,children:Q(`div`,{className:`space-y-1 text-xs`,children:[e.exchangeRate&&Q(`div`,{className:`flex justify-between`,children:[Z(`span`,{className:`text-gray-500 dark:text-gray-400`,children:`Exchange Rate:`}),Z(`span`,{className:`text-gray-900 dark:text-gray-100`,children:e.exchangeRate.toFixed(4)})]}),e.totalFee&&Q(`div`,{className:`flex justify-between`,children:[Z(`span`,{className:`text-gray-500 dark:text-gray-400`,children:`Total Fee:`}),Q(`span`,{className:`text-gray-900 dark:text-gray-100`,children:[e.sourceCurrencySymbol,e.totalFee]})]}),e.walletAddress&&Q(`div`,{className:`flex justify-between`,children:[Z(`span`,{className:`text-gray-500 dark:text-gray-400`,children:`Wallet:`}),Z(`span`,{className:`text-gray-900 dark:text-gray-100 font-mono`,children:wt(e.walletAddress,6,4)})]}),e.institutionName&&Q(`div`,{className:`flex justify-between`,children:[Z(`span`,{className:`text-gray-500 dark:text-gray-400`,children:`Institution:`}),Z(`span`,{className:`text-gray-900 dark:text-gray-100`,children:e.institutionName})]})]})})]})};function gC({hostname:e}){return new lm(e)}const _C=e=>{let t=Vx();return J(()=>gC({hostname:e?.hostname||t.keyMachineUrl}),[e?.hostname,t.keyMachineUrl])};async function vC(e,t){if(W(t))return!1;let n=await Va(t).getCode({address:e}),r=n!==void 0&&n!==`0x`;return s.console.log(`[refund] Address deployment check:`,{address:e,chainId:t,codeLength:n?.length??0,isDeployed:r}),r}async function yC(e,t,n,r){if(!e.account)throw Error(`Wallet client account is required for signing`);await Nr(e);let i=Jt.toTyped(Ca.from(t),n,r),a=await Wr(e.signTypedData({account:e.account,...i}),`Payload signature`);return s.console.log(`[refund] Signature received:`,a),a}async function bC(e){let{trailsClient:t,intentId:n,payload:r,intentAddress:i,signature:a}=e,o=r.calls[0];if(!o)throw Error(`Refund call not found in payload`);if(Ca.isEqual(o.to,Cn))throw Error(`Refund call 'to' address cannot be zero address`);if(!i||Ca.isEqual(i,Cn))throw Error(`Intent address cannot be zero address`);let s={kind:`v3_calls_payload`,encoding:`hex`,encoded:wa.toHex(Jt.encode(r)),intentAddress:i,chainId:r.type===`call`?Number(e.chainId):void 0},c=await t.buildIntentRecoveryTransaction({intentId:n,payload:s,signature:a,intentAddress:i});return{to:Ca.from(c.to),data:c.data}}function xC(e,t){if(e&&typeof e==`object`&&`kind`in e&&e.kind===`v3_calls_payload`){let n=e;if(n.encoding!==`hex`||!n.encoded)throw Error(`PrepareIntentRecovery returned invalid canonical payload encoding`);let r=n.intentAddress?Ca.from(n.intentAddress):t,i=Jt.decode(wa.fromHex(n.encoded),r);if(!Jt.isCalls(i))throw Error(`PrepareIntentRecovery returned non-call payload for recovery`);let a=i.calls?.[0];if(!a)throw Error(`PrepareIntentRecovery returned invalid payload: refund call missing`);return{decodedPayload:i,refundCall:a}}throw Error(`PrepareIntentRecovery returned unsupported payload format (expected v3_calls_payload)`)}function SC(e){if(!e?.tokens)return 0;let t=0;for(let n of e.tokens){let e=n.balanceUsd||0;e>t&&(t=e)}return t}function CC(e){if(!e?.tokens)return 0n;let t=0n;for(let n of e.tokens){let e=BigInt(n.balance||`0`);e>t&&(t=e)}return t}function wC(e,t,n,r,i){let a=SC(t),o=SC(n),s=CC(t),c=CC(n),l=!1;i&&(l=a>0&&o>0?o>a:o>0&&a===0?!0:a>0&&o===0?!1:c>s);let u=()=>!e.originIntentAddress||!r?null:{address:r,chainId:Number(e.originChainId||0),intentAddress:Ca.from(e.originIntentAddress),tokenBalancesData:t,isOrigin:!0};if(l){let t=e.destinationChainId;return!t||!e.destinationIntentAddress||!i?u():{address:i,chainId:Number(t),intentAddress:Ca.from(e.destinationIntentAddress),tokenBalancesData:n,isOrigin:!1}}return u()}function TC(e,t){let n=e=>{if(!e?.tokens)return!1;for(let t of e.tokens)if(Cs(t.balance||`0`))return!0;return!1};return n(e)||n(t)}function EC(e){if(!e?.tokenBalancesData?.tokens)return null;let t=null,n=0n;for(let r of e.tokenBalancesData.tokens){let e=BigInt(r.balance||`0`);e>0n&&e>n&&(n=e,t=r)}return t}function DC(e){if(!e)throw Error(`Refund address is required. Provide refundToAddress or connect a wallet with a valid address`);if(Ca.isEqual(e,Cn))throw Error(`Refund address cannot be zero address`)}async function OC(e){let{txHash:t,chainId:n}=e;if(W(n))return{status:`pending`};let r=Va(n);try{if(await r.getTransaction({hash:t}))try{let e=await r.getTransactionReceipt({hash:t});return e.status===`reverted`||$m(e).some(e=>e.type===`CallFailed`)?{status:`fail`}:{status:`success`}}catch{return{status:`pending`}}}catch{try{let e=await r.getTransactionReceipt({hash:t});return e.status===`reverted`||$m(e).some(e=>e.type===`CallFailed`)?{status:`fail`}:{status:`success`}}catch{return{status:`pending`}}}return{status:`pending`}}function kC(e){if(!e)return null;let t=$(e.chainId);return{address:e.address,chainId:e.chainId,chainName:t?.name||`Chain ${e.chainId}`,isOrigin:e.isOrigin,tokenBalancesData:e.tokenBalancesData}}function AC(e){if(e.length!==132)throw Error(`Invalid recovery signature length: expected 65 bytes, got ${(e.length-2)/2} bytes`);let t=BigInt(`0x${e.slice(2,66)}`),n=BigInt(`0x${e.slice(66,130)}`),r=Number(`0x${e.slice(130)}`);if(Number.isNaN(r))throw Error(`Invalid recovery signature parity byte`);if(r===0||r===27)return{r:t,s:n,yParity:0};if(r===1||r===28)return{r:t,s:n,yParity:1};let i=r>=27?(r-27)%2:r%2;return s.console.warn(`[recover] Normalizing non-standard signature parity`,{yParityOrV:r,yParity:i}),{r:t,s:n,yParity:i}}function jC(e,t){if(e.length!==132)return{type:`erc1271`,address:t,data:e};let n=AC(e);return{type:`hash`,r:n.r,s:n.s,yParity:n.yParity}}async function MC(e){let{trailsClient:t,intentData:n,selected:r,effectiveRefundAddress:i,signature:a,payload:o}=e;DC(i);let s={kind:`v3_calls_payload`,encoding:`hex`,encoded:wa.toHex(Jt.encode(o)),intentAddress:r.intentAddress,chainId:r.chainId},c=await t.buildIntentRecoveryTransaction({intentId:n.intentId,payload:s,signature:a,intentAddress:r.intentAddress,refundToAddress:i}),l=Number(c.chainId),u=Ca.from(c.to);if(!u||Ca.isEqual(u,Cn))throw Error(`Refund transaction 'to' address cannot be zero address`);let d=$(l);if(!d)throw Error(`Chain info not found for chain ID: ${l}`);return{to:u,data:c.data,chainId:l,chain:d}}function NC(){if(!globalThis.crypto?.getRandomValues)throw Error(`Secure random generator not available for recovery space`);let e=new Uint8Array(20);globalThis.crypto.getRandomValues(e);let t=BigInt(`0x${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`);if(t<=1n)throw Error(`Generated reserved recovery space`);return t}async function PC(e){let{trailsClient:t,intentData:n,selectedIntentAddress:r,effectiveRefundAddress:i}=e,a=await t.prepareIntentRecovery({intentId:n.intentId,intentAddress:r.intentAddress,refundToAddress:i}),{decodedPayload:o,refundCall:s}=xC(a.payload,r.intentAddress);return{payload:o,refundCall:s,chainId:Number(a.chainId),typedData:a.typedData}}async function FC(e){let{walletClient:t,prepared:n}=e;if(!t.account)throw Error(`Wallet client account is required for signing`);return await Hh({walletClient:t,desiredChainId:n.chainId}),await Nr(t),{signature:await Wr(t.signTypedData({account:t.account,...n.typedData}),`Recovery signature`),signerAddress:t.account.address,payload:n.payload,refundCall:n.refundCall}}function IC(e){return new Promise(t=>setTimeout(t,e))}function LC(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)}function RC(e){if(LC(e))return e;if(typeof e==`string`&&/^[0-9a-fA-F]{64}$/.test(e))return`0x${e}`}function zC(e,t){let n=e;for(let e of t){if(!n||typeof n!=`object`||!(e in n))return;n=n[e]}return n}function BC(e){let t=RC(e);if(t)return t;let n=e,r=[n?.data?.txHash,n?.data?.nativeReceipt&&zC(n.data.nativeReceipt,[`transactionHash`]),n?.data?.nativeReceipt&&zC(n.data.nativeReceipt,[`hash`]),n?.data?.receipt&&zC(n.data.receipt,[`txHash`]),n?.data?.receipt&&zC(n.data.receipt,[`transactionHash`]),n?.response&&BC(n.response)];for(let e of r){let t=RC(e);if(t)return t}}function VC(e){if(!e||typeof e!=`object`)return;let t=e;return t.data?.metaTxHash??(t.response?VC(t.response):void 0)}async function HC(e){let{accountAddress:t,chainId:n,sentAtMs:r,pollingConfig:i}=e,a=i?.apiKey,o=i?.indexerUrl;if(!a||!o)return null;let c=Qh(n,o);if(!c)return null;let l=new ka(c,a),u=Va(n),d=Date.now();for(;Date.now()-d<6e4;){try{let e=await l.getTransactionHistory({filter:{accountAddress:St(t)},includeMetadata:!1,page:{page:1,pageSize:20}});for(let t of e.transactions??[]){let e=RC(t.txnHash);if(!e)continue;let n=await u.getTransactionReceipt({hash:e}).catch(()=>null);if(!n)continue;let i=await u.getBlock({blockNumber:n.blockNumber}).catch(()=>null),a=i?Number(i.timestamp)*1e3:0;if(!(a&&a<r-3e4))return{txHash:e,receipt:n}}}catch(e){s.console.warn(`[recover] Failed to poll Sequence indexer for recovery tx hash`,{error:e instanceof Error?e.message:String(e)})}await IC(2e3)}return null}async function UC(e){let{sendResult:t,trailsWalletClient:n,recoverTx:r,sentAtMs:i,pollingConfig:a}=e,o=Va(r.chainId),c=BC(t);if(c)return{txHash:c,receipt:await o.waitForTransactionReceipt({hash:c})};let l=VC(t);s.console.warn(`[recover] Recovery send returned no transaction hash; polling for mined transaction`,{metaTxHash:l});let u=await HC({accountAddress:n.account.address,chainId:r.chainId,sentAtMs:i,pollingConfig:a});if(u)return u;throw Error(`Recovery transaction was submitted, but the final transaction hash was not available yet. Please refresh transaction history in a moment.`)}async function WC(e){let{trailsWalletClient:t,recoverTx:n,trailsClient:r,intentId:i,pollingConfig:a,onTransactionSubmitted:o}=e;if(!t.account)throw Error(`Wallet client with account is required for recovery`);let c=Date.now(),l=await t.sendTransaction({account:t.account,to:n.to,data:n.data,chain:n.chain});o?.();let{txHash:u,receipt:d}=await UC({sendResult:l,trailsWalletClient:t,recoverTx:n,sentAtMs:c,pollingConfig:a});if(i&&r)try{await Lm(r,i,n.chainId,u)}catch(e){s.console.error(`[recover] Failed to abort intent after recovery:`,{error:e instanceof Error?e.message:String(e),intentId:i,chainId:n.chainId,txHash:u})}return{txHash:u,receipt:d,chainId:n.chainId}}function GC(e){let{selectedIntentAddress:t,refundToAddress:n}=e,r=[],i=t.tokenBalancesData?.tokens??[];for(let e of i){let i=e.balance??`0`,a=BigInt(i);if(a<=0n)continue;let o=e.isNativeToken===!0,c=e.contractAddress;if(!o&&!c){s.console.warn(`[recover] Skipping invalid recovery token: missing contractAddress for non-native token`,{symbol:e.symbol||`unknown`,balance:i,chainId:t.chainId,intentAddress:t.intentAddress});continue}let l=c||Cn;if(o){r.push({to:n,value:a,data:`0x`,gasLimit:0n,delegateCall:!1,onlyFallback:!1,behaviorOnError:`revert`});continue}let u;try{u=Ca.from(l)}catch{s.console.warn(`[recover] Skipping invalid recovery token: malformed contractAddress`,{contractAddress:l,symbol:e.symbol||`unknown`,balance:i,chainId:t.chainId,intentAddress:t.intentAddress});continue}r.push({to:u,value:0n,data:L_(n,a),gasLimit:0n,delegateCall:!1,onlyFallback:!1,behaviorOnError:`revert`})}if(r.length===0)throw Error(`No recoverable token balances found on selected intent`);return{payload:{type:`call`,space:NC(),nonce:0n,calls:r},refundCall:r[0]}}async function KC(e){let{keyMachineClient:t,selected:n,signerAddress:r,signature:i,payload:a}=e,o=n.intentAddress,s=n.chainId,c=$(s);if(!c)throw Error(`Chain info not found for chain ID: ${s}`);let l=await vC(o,s),u=await t.getDeploy(o);if(!u)throw Error(`Deploy config not found for intent address`);let d=await t.getConfiguration(u.imageHash);if(!d)throw Error(`Configuration not found for intent address`);let f=jC(i,r),p=!1,m=Xt.fillLeaves(d.topology,e=>{if(Ca.isEqual(Ca.from(e.address),Ca.from(r)))return p=!0,f});if(!p)throw Error(`Signer ${r} is not an authorized signer for intent wallet ${o}. Connect the correct wallet to recover.`);let h=Xt.encodeSignature({noChainId:!1,configuration:{threshold:d.threshold,checkpoint:d.checkpoint,checkpointer:d.checkpointer,topology:m}}),g=Sa.encodeData(Kt.EXECUTE,[wa.toHex(Jt.encode(a)),wa.toHex(h)]);if(!l){let e=qt.deploy(u.imageHash,u.context),t=Kt.DefaultGuestAddress,n={type:`call`,space:0n,nonce:0n,calls:[{to:e.to,value:0n,data:e.data,gasLimit:0n,delegateCall:!1,onlyFallback:!1,behaviorOnError:`revert`},{to:o,value:0n,data:g,gasLimit:0n,delegateCall:!1,onlyFallback:!1,behaviorOnError:`revert`}]};return{to:t,data:wa.toHex(Jt.encode(n,t)),chainId:s,chain:c}}return{to:o,data:g,chainId:s,chain:c}}function qC({intent:e,balancesByIntentAddress:t,walletClient:n,refundToAddress:r,keyMachineClient:i,onTransactionSubmitted:a}){let o=_C(),s=i??o,c=gs(),{sequenceIndexerUrl:l,trailsApiKey:u}=Vx(),d=J(()=>({apiKey:u,indexerUrl:l}),[u,l]),f=J(()=>n?pi(n):void 0,[n]),p=e?.originIntentAddress?t[St(e.originIntentAddress)]?.tokenBalancesData:void 0,m=e?.destinationIntentAddress?t[St(e.destinationIntentAddress)]?.tokenBalancesData:void 0,h=e?.originIntentAddress?Ca.from(e.originIntentAddress):null,g=e?.destinationIntentAddress?Ca.from(e.destinationIntentAddress):null,_=J(()=>e?wC(e,p,m,h,g):null,[e,p,m,h,g]),v=J(()=>TC(p,m),[p,m]),y=J(()=>EC(_),[_]),b=J(()=>kC(_),[_]),x=J(()=>{let e=r||f?.account?.address;return!e||Ca.isEqual(e,Cn)?null:e},[r,f?.account?.address]),S=K(async()=>{if(!_)throw Error(`No intent address selected for recovery`);DC(x);let{payload:e,refundCall:t}=GC({selectedIntentAddress:_,refundToAddress:x});return{payload:e,refundCall:t,chainId:_.chainId,typedData:Jt.toTyped(_.intentAddress,_.chainId,e)}},[_,x]),C=K(async e=>{if(!f?.account)throw Error(`Wallet client with account is required for recovery`);let t=e??await S();return FC({walletClient:f,prepared:t})},[f,S]),w=K(async e=>{if(!_)throw Error(`No intent address selected for recovery`);return KC({keyMachineClient:s,selected:_,signerAddress:e.signerAddress,signature:e.signature,payload:e.payload})},[_,s]);return{intent:e,hasIntentBalance:v,recoverToken:y,selectedRecoveryTarget:b,signPayload:C,getDataToSign:S,getRecoverTx:w,recover:K(async()=>{if(!f?.account)throw Error(`Wallet client with account is required for recovery`);let t=await S(),{signature:n,signerAddress:r,payload:i}=await C(t),o=await w({signature:n,signerAddress:r,payload:i});return WC({trailsWalletClient:f,recoverTx:o,trailsClient:c,intentId:e?.intentId,pollingConfig:d,onTransactionSubmitted:a})},[f,S,C,w,c,e?.intentId,d,a]),getRecoverStatus:K(e=>OC(e),[])}}function JC({intentId:e,walletClient:t,refundToAddress:n}){let r=gs(),i=J(()=>t?pi(t):void 0,[t]),a=i?.account?.address,o=YC({intentId:e,walletAddress:a,refundToAddress:n||a}),s=K(async()=>{if(!i?.account)throw Error(`Intent data and wallet client with account required`);let e=await o.getDataToSign();return FC({walletClient:i,prepared:e})},[i,o]),c=K(async e=>o.getRecoverTx({signature:e.signedHash,payload:e.payload}),[o]),l=K(async()=>{if(!i?.account)throw Error(`Intent data and wallet client with account required`);let{signature:t,payload:n}=await s(),a=await c({signedHash:t,payload:n});return WC({trailsWalletClient:i,recoverTx:a,trailsClient:r,intentId:e})},[s,c,i,e,r]);return{...o,signPayload:s,getRecoverTx:c,recover:l}}function YC({intentId:e,walletAddress:t,refundToAddress:n}){let{intent:r,isLoading:i,error:a,refetch:o}=DS({intentId:e,enabled:!!e}),s=gs(),c=r?.originIntentAddress?Ca.from(r.originIntentAddress):null,l=r?.destinationIntentAddress?Ca.from(r.destinationIntentAddress):null,{balancesByAccount:u,isLoading:d,error:f}=$_([c,l],{refetchInterval:J_}),p=c?u[St(c)]?.tokenBalancesData:void 0,m=l?u[St(l)]?.tokenBalancesData:void 0,h=f,g=J(()=>r?wC(r,p,m,c,l):null,[r,p,m,c,l]),_=J(()=>TC(p,m),[p,m]),v=J(()=>EC(g),[g]),y=J(()=>{let e=n??t;return!e||Ca.isEqual(e,Cn)?null:e},[n,t]),b=K(async()=>{if(!r)throw Error(`Intent data required`);if(!y)throw Error(`Refund address required. Provide refundToAddress or walletAddress`);if(Ca.isEqual(y,Cn))throw Error(`Refund address cannot be zero address`);if(!g)throw Error(`No intent address selected for recovery`);return PC({trailsClient:s,intentData:r,selectedIntentAddress:g,effectiveRefundAddress:y})},[r,g,y,s]),x=K(async e=>{if(!r)throw Error(`Intent data required`);if(!g)throw Error(`No intent address selected for recovery`);return MC({trailsClient:s,intentData:r,selected:g,effectiveRefundAddress:y,signature:e.signature,payload:e.payload})},[r,g,y,s]),S=K(e=>OC(e),[]);return{intent:r,isLoadingIntent:i,isLoadingBalances:d,intentError:a,balancesError:h,hasIntentBalance:_,recoverToken:v,selectedRecoveryTarget:J(()=>kC(g),[g]),refetchIntent:o,getDataToSign:b,getRecoverTx:x,getRecoverStatus:S}}const XC=({errorPrettified:e,error:t,severity:n=`error`})=>{let[r,i]=X(!1),[a,o]=X(e||null);q(()=>{if(!e&&t){let e=T(t);e&&o(e)}else o(e||null)},[e,t]);let s=(()=>{switch(n){case`error`:return{bg:`bg-red-500/10`,border:`border-red-500/30`,icon:`text-red-500`,text:`text-red-600 dark:text-red-400`,button:`text-red-500 hover:text-red-600 dark:text-red-400 dark:hover:text-red-300`,expandable:`bg-red-500/5 border-red-500/20 text-red-700 dark:text-red-300`};case`info`:return{bg:`bg-blue-500/10`,border:`border-blue-500/30`,icon:`text-blue-500`,text:`text-blue-600 dark:text-blue-400`,button:`text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300`,expandable:`bg-blue-500/5 border-blue-500/20 text-blue-700 dark:text-blue-300`};case`warning`:return{bg:`bg-amber-500/10`,border:`border-amber-500/30`,icon:`text-amber-500`,text:`text-amber-600 dark:text-amber-400`,button:`text-amber-500 hover:text-amber-600 dark:text-amber-400 dark:hover:text-amber-300`,expandable:`bg-amber-500/5 border-amber-500/20 text-amber-700 dark:text-amber-300`};default:return{bg:`bg-amber-500/10`,border:`border-amber-500/30`,icon:`text-amber-500`,text:`text-amber-600 dark:text-amber-400`,button:`text-amber-500 hover:text-amber-600 dark:text-amber-400 dark:hover:text-amber-300`,expandable:`bg-amber-500/5 border-amber-500/20 text-amber-700 dark:text-amber-300`}}})(),c=a||t;return c?Z(`div`,{className:`px-2 py-3 rounded-lg ${s.bg} border border-solid ${s.border}`,children:Q(`div`,{className:`flex items-start space-x-2`,children:[Z(`svg`,{className:`w-4 h-4 ${s.icon} flex-shrink-0 mt-0.5`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})}),Q(`div`,{className:`flex-1 min-w-0`,children:[Z(`p`,{className:`text-sm ${s.text}`,children:c}),t&&t!==c&&Q(`div`,{className:`mt-2`,children:[Q(`button`,{type:`button`,onClick:()=>i(!r),className:`flex items-center gap-1 text-xs ${s.button} transition-colors cursor-pointer`,"aria-label":`Show full error details`,children:[Q(`span`,{children:[r?`Hide`:`Show`,` full error`]}),Z(`svg`,{className:`w-3 h-3 transition-transform duration-300 ease-out ${r?`rotate-180`:``}`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M19 9l-7 7-7-7`})})]}),r&&Z(`div`,{className:`mt-2 p-2 ${s.expandable} rounded text-xs font-mono max-h-[200px] overflow-y-auto overflow-x-auto`,children:t})]})]})]})}):null},ZC=({status:e})=>{let t=aC(e);return Z(`span`,{title:t,className:`inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium ${t?`cursor-help`:``} ${(e=>{switch(e?.toUpperCase()){case`SUCCEEDED`:return`bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200`;case`EXECUTING`:return`bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200`;case`MINING`:return`bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200`;case`RELAYING`:return`bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200`;case`SENT`:return`bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200`;case`PENDING`:return`bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200`;case`ON_HOLD`:return`bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200`;case`FAILED`:return`bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200`;case`ABORTED`:return`bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200`;case`ERRORED`:return`bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200`;case`QUOTED`:return`bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200`;case`COMMITTED`:return`bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-200`;case`UNKNOWN`:return`bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200`;default:return`bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200`}})(e)}`,children:fC(e)})},QC=Z(`svg`,{"aria-hidden":`true`,className:`w-3 h-3`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14`})}),$C=({transaction:e,className:t=``,intentProtocol:n})=>{let{trailsAppUrl:r}=Vx(),i=e=>e?e.replaceAll(`_`,` `):null;return Q(`div`,{className:`space-y-2 text-sm ${t}`,children:[e.intentId&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Intent ID:`}),Q(`a`,{href:`${r}/intent/${e.intentId}`,target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono text-gray-900 dark:text-gray-100 hover:underline flex items-center gap-1`,title:`View on Trails`,children:[wt(e.intentId),QC]})]}),e.edge?.mode===`ORIGIN`&&e.edge.initTransactionHash&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Edge Tx:`}),Q(`a`,{href:Xa({txHash:e.edge.initTransactionHash,chainId:101}),target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono hover:underline flex items-center gap-1 text-gray-900 dark:text-gray-100`,children:[Z(Ty,{chainId:101,size:16}),wt(e.edge.initTransactionHash),QC]})]}),e.edge?.mode===`ORIGIN`&&e.edge.refundTransactionHash&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Edge Refund Tx:`}),Q(`a`,{href:Xa({txHash:e.edge.refundTransactionHash,chainId:101}),target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono hover:underline flex items-center gap-1 text-gray-900 dark:text-gray-100`,children:[Z(Ty,{chainId:101,size:16}),wt(e.edge.refundTransactionHash),QC]})]}),e.edge?.mode===`ORIGIN`&&e.edge.token&&Q(`div`,{className:`flex justify-between items-start`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Edge Origin Token:`}),Q(`div`,{className:`flex items-center gap-1 justify-end text-xs font-mono text-gray-900 dark:text-gray-100`,children:[Z(Jy,{symbol:e.edge.token.symbol,imageUrl:e.edge.token.imageUrl,chainId:e.edge.token.chainId,size:16}),Q(`span`,{className:`font-mono`,children:[e.edge.tokenAmount==null?``:`${Xs(e.edge.tokenAmount,e.edge.token.decimals)} `,e.edge.token.symbol]})]})]}),tg(e.depositTransactionHash)&&e.originChainId&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Deposit Tx:`}),Q(`a`,{href:Xa({txHash:e.depositTransactionHash,chainId:e.originChainId}),target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono hover:underline flex items-center gap-1 text-gray-900 dark:text-gray-100`,children:[Z(Ty,{chainId:e.originChainId,size:16}),wt(e.depositTransactionHash),QC]})]}),tg(e.refundTransactionHash)&&(e.refundTransactionChainId||e.originChainId)&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Refund Tx:`}),Q(`a`,{href:Xa({txHash:e.refundTransactionHash,chainId:e.refundTransactionChainId||e.originChainId||0}),target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono hover:underline flex items-center gap-1 text-gray-900 dark:text-gray-100`,children:[Z(Ty,{chainId:e.refundTransactionChainId||e.originChainId||0,size:16}),wt(e.refundTransactionHash),QC]})]}),e.originToken&&Q(`div`,{className:`flex justify-between items-start`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Origin Token:`}),Z(`div`,{className:`text-right`,children:e.originTokenAddress&&!bt(e.originTokenAddress)?Q(`a`,{href:Za({address:e.originTokenAddress,chainId:e.originToken.chainId}),target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center gap-1 justify-end hover:underline text-xs font-mono text-gray-900 dark:text-gray-100`,children:[Z(Jy,{symbol:e.originToken.symbol,imageUrl:e.originToken.imageUrl,chainId:e.originToken.chainId,size:16}),Q(`span`,{className:`font-mono`,children:[Xs(e.originTokenAmount||`0`,e.originToken.decimals),` `,e.originToken.symbol]}),QC]}):Q(`div`,{className:`flex items-center gap-1 justify-end text-xs font-mono text-gray-900 dark:text-gray-100`,children:[Z(Jy,{symbol:e.originToken.symbol,imageUrl:e.originToken.imageUrl,chainId:e.originToken.chainId,size:16}),Q(`span`,{className:`font-mono`,children:[Xs(e.originTokenAmount||`0`,e.originToken.decimals),` `,e.originToken.symbol]})]})})]}),tg(e.destinationIntentDepositTxHash)&&e.destinationIntentDepositTxExplorerUrl&&e.destinationChainId&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Destination Deposit Tx:`}),Q(`a`,{href:e.destinationIntentDepositTxExplorerUrl,target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono hover:underline flex items-center gap-1 text-gray-900 dark:text-gray-100`,children:[Z(Ty,{chainId:e.destinationChainId,size:16}),wt(e.destinationIntentDepositTxHash),QC]})]}),e.originIntentAddress&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Origin Intent:`}),Q(`a`,{href:Za({address:e.originIntentAddress,chainId:e.originChainId||e.originToken?.chainId||1}),target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono hover:underline flex items-center gap-1 text-gray-900 dark:text-gray-100`,children:[e.originChainId&&Z(Ty,{chainId:e.originChainId,size:16}),wt(e.originIntentAddress),QC]})]}),tg(e.originIntentTxHash)&&e.originIntentTxExplorerUrl&&e.originChainId&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Origin Intent Tx:`}),Q(`a`,{href:e.originIntentTxExplorerUrl,target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono hover:underline flex items-center gap-1 text-gray-900 dark:text-gray-100`,children:[Z(Ty,{chainId:e.originChainId,size:16}),wt(e.originIntentTxHash),QC]})]}),e.destinationToken&&Q(`div`,{className:`flex justify-between items-start`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Destination Token:`}),Z(`div`,{className:`text-right`,children:e.destinationTokenAddress&&!bt(e.destinationTokenAddress)?Q(`a`,{href:Za({address:e.destinationTokenAddress,chainId:e.destinationToken.chainId}),target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center gap-1 justify-end hover:underline text-xs font-mono text-gray-900 dark:text-gray-100`,children:[Z(Jy,{symbol:e.destinationToken.symbol,imageUrl:e.destinationToken.imageUrl,chainId:e.destinationToken.chainId,size:16}),Q(`span`,{className:`font-mono`,children:[Xs(e.destinationTokenAmount||`0`,e.destinationToken.decimals),` `,e.destinationToken.symbol]}),QC]}):Q(`div`,{className:`flex items-center gap-1 justify-end text-xs font-mono text-gray-900 dark:text-gray-100`,children:[Z(Jy,{symbol:e.destinationToken.symbol,imageUrl:e.destinationToken.imageUrl,chainId:e.destinationToken.chainId,size:16}),Q(`span`,{className:`font-mono`,children:[Xs(e.destinationTokenAmount||`0`,e.destinationToken.decimals),` `,e.destinationToken.symbol]})]})})]}),e.destinationIntentAddress&&e.destinationChainId&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Destination Intent:`}),Q(`a`,{href:Za({address:e.destinationIntentAddress,chainId:e.destinationChainId}),target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono hover:underline flex items-center gap-1 text-gray-900 dark:text-gray-100`,children:[Z(Ty,{chainId:e.destinationChainId,size:16}),wt(e.destinationIntentAddress),QC]})]}),e.destinationToAddress&&!gt(e.destinationToAddress)&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Destination To Address:`}),Q(`a`,{href:Za({address:e.destinationToAddress,chainId:e.destinationChainId||1}),target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono hover:underline flex items-center gap-1 text-gray-900 dark:text-gray-100`,children:[e.destinationChainId&&Z(Ty,{chainId:e.destinationChainId,size:16}),wt(e.destinationToAddress),QC]})]}),tg(e.destinationIntentTxHash)&&e.destinationIntentTxExplorerUrl&&e.destinationChainId&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Destination Intent Tx:`}),Q(`a`,{href:e.destinationIntentTxExplorerUrl,target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono hover:underline flex items-center gap-1 text-gray-900 dark:text-gray-100`,children:[Z(Ty,{chainId:e.destinationChainId,size:16}),wt(e.destinationIntentTxHash),QC]})]}),e.edge?.mode===`DESTINATION`&&e.edge.fillTransactionHash&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Edge Tx:`}),Q(`a`,{href:Xa({txHash:e.edge.fillTransactionHash,chainId:101}),target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-mono hover:underline flex items-center gap-1 text-gray-900 dark:text-gray-100`,children:[Z(Ty,{chainId:101,size:16}),wt(e.edge.fillTransactionHash),QC]})]}),e.edge?.mode===`DESTINATION`&&e.edge.token&&Q(`div`,{className:`flex justify-between items-start`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Edge Destination Token:`}),Q(`div`,{className:`flex items-center gap-1 justify-end text-xs font-mono text-gray-900 dark:text-gray-100`,children:[Z(Jy,{symbol:e.edge.token.symbol,imageUrl:e.edge.token.imageUrl,chainId:e.edge.token.chainId,size:16}),Q(`span`,{className:`font-mono`,children:[e.edge.tokenAmount==null?``:`${Xs(e.edge.tokenAmount,e.edge.token.decimals)} `,e.edge.token.symbol]})]})]}),n&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Intent Protocol:`}),Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 opacity-50`,children:n})]}),e.routeProviders&&e.routeProviders.length>0&&Q(`div`,{className:`flex justify-between items-center`,children:[Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:e.routeProviders.length>1?`Route Providers:`:`Route Provider:`}),Z(`span`,{className:`text-xs font-medium text-gray-900 dark:text-gray-100`,children:e.routeProviders.map(e=>i(e)).join(`, `)})]})]})};function ew(e){return!e||e===`UNKNOWN`?null:e.charAt(0)+e.slice(1).toLowerCase()}function tw(e){switch(e){case`PAY`:return`bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200`;case`SWAP`:return`bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200`;case`FUND`:return`bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200`;case`EARN`:return`bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200`;case`WITHDRAW`:return`bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200`;default:return`bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200`}}function nw(e){return e?e.replaceAll(`_`,` `):null}const rw=({transaction:e,index:t,fetchedIntent:n,isOffline:r=!1,commitIntentMutation:i,onCommitSuccess:a,selectedWalletClient:o,balancesByIntentAddress:c,onRecover:l})=>{let[u,d]=X(!1),f=Y(null),p=je(e.createdAt),m=ew(e.mode),{data:h}=si(),g=nw(e.swapProviderUsed),_=nw(e.bridgeProviderUsed),v=e.edge?.mode===`ORIGIN`&&!!e.edge.token,y=e.edge?.mode===`DESTINATION`&&!!e.edge.token,b=v?e.edge.token:e.originToken,x=v?e.edge.tokenAmount:e.originTokenAmount,S=y?e.edge.token:e.destinationToken,C=y?e.edge.tokenAmount:e.destinationTokenAmount,w=o||h,T=e.refundTransactionHash,E=J(()=>!e.intentId||T?!1:e.hasBalance??!1,[e.intentId,e.hasBalance,T]),D=e.executionStatus===rn.QUOTED&&!n,O=!!e.intentId&&E,k=J(()=>!e.intentId||!e.mainSigner?null:Om(e.mainSigner).find(t=>t.intentId===e.intentId)??null,[e.intentId,e.mainSigner]),{intent:A,isLoading:j,error:M}=DS({intentId:D||O?e.intentId:void 0,enabled:D||O}),N=n||A||k,[P,F]=X(!1),[I,ee]=X(null),[te,ne]=X(!1),[re,ie]=X(null),{recoverToken:L}=qC({intent:T?null:N,balancesByIntentAddress:c,walletClient:w||void 0}),R=e.intentId&&w&&!T&&(E||r&&!!k),ae=Yg(),z=(e.executionStatus===rn.QUOTED||n?.status===rn.QUOTED)&&i&&e.intentId,B=new Set([rn.EXECUTING,rn.SUCCEEDED,rn.FAILED,rn.ABORTED,rn.REFUNDED,rn.INVALID,dn.MINING]),V=(e.executionStatus===rn.COMMITTED||n?.status===rn.COMMITTED)&&e.intentId&&!B.has(e.executionStatus??``)&&E,oe=async()=>{if(!e.intentId||!i){s.console.error(`[AccountIntentTransactionHistory] Cannot commit: missing intentId or mutation`);return}try{if(F(!0),ee(null),n)await i.mutateAsync(n),s.console.log(`[AccountIntentTransactionHistory] Fetched intent committed successfully`,{intentId:n.intentId});else{if(!A)throw Error(`Intent data not available for committing`);await i.mutateAsync(A),s.console.log(`[AccountIntentTransactionHistory] Regular transaction intent committed successfully`,{intentId:e.intentId})}a&&a()}catch(t){s.console.error(`[AccountIntentTransactionHistory] Failed to commit intent`,{intentId:e.intentId,error:t});let n=t instanceof Error?t.message:typeof t==`string`?t:`Failed to commit intent. Please try again.`;ee(n)}finally{F(!1)}},H=async t=>{if(!e.intentId){s.console.error(`[AccountIntentTransactionHistory] Cannot execute: missing intentId`);return}try{ne(!0),ie(null);let n=t||e.originTransactionHash||e.originIntentTxHash||e.originIntentDepositTxHash||e.txnHash||pe(`depositTransactionHash`);await ae.mutateAsync({intentId:e.intentId}),s.console.log(`[AccountIntentTransactionHistory] Intent executed successfully`,{intentId:e.intentId,depositTransactionHash:n}),a&&a()}catch(t){s.console.error(`[AccountIntentTransactionHistory] Failed to execute intent`,{intentId:e.intentId,error:t});let n=t instanceof Error?t.message:typeof t==`string`?t:`Failed to execute intent. Please try again.`;ie(n)}finally{ne(!1)}},se=()=>{if(!e.intentId||!w){s.console.error(`[AccountIntentTransactionHistory] Cannot recover: missing intentId or walletClient`);return}if(!l){s.console.error(`[AccountIntentTransactionHistory] Cannot recover: missing recover navigation handler`);return}l()},ce=J(()=>e.destinationTransactionHash&&e.destinationChainId?{hash:e.destinationTransactionHash,chainId:e.destinationChainId}:e.destinationIntentTxHash&&e.destinationChainId?{hash:e.destinationIntentTxHash,chainId:e.destinationChainId}:e.originTransactionHash&&e.originChainId?{hash:e.originTransactionHash,chainId:e.originChainId}:e.originIntentTxHash&&e.originChainId?{hash:e.originIntentTxHash,chainId:e.originChainId}:e.txnHash?{hash:e.txnHash,chainId:e.destinationChainId||e.originChainId}:null,[e.destinationTransactionHash,e.destinationIntentTxHash,e.originTransactionHash,e.originIntentTxHash,e.txnHash,e.destinationChainId,e.originChainId]),U=J(()=>!ce?.hash||!ce.chainId?null:Xa({txHash:ce.hash,chainId:ce.chainId}),[ce]),le=J(()=>{if(e.intentProtocol)return e.intentProtocol;let t=n||A;return t?.intentProtocol?t.intentProtocol:t?.quoteRequest?.options?.intentProtocol},[e.intentProtocol,n,A]),ue=J(()=>!T||!e.originChainId?null:Xa({txHash:T,chainId:e.refundTransactionChainId??e.originChainId}),[T,e.originChainId,e.refundTransactionChainId]);return Q(`div`,{className:`border border-gray-200 dark:border-gray-700 rounded-lg p-2 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors`,children:[Q(`div`,{className:`flex items-center justify-between mb-2`,children:[Z(`div`,{className:`flex items-center gap-2 flex-wrap`,children:p.relative&&Z(`span`,{className:`text-xs text-gray-900 dark:text-gray-100 cursor-help`,title:p.full||void 0,children:p.relative})}),Q(`div`,{className:`flex items-center gap-2`,children:[U&&Q(`a`,{href:U,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 text-xs whitespace-nowrap`,title:`View transaction on block explorer`,children:[Z(`span`,{children:`View on Explorer`}),Q(`svg`,{className:`w-3 h-3 shrink-0`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`External Link`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14`})]})]}),m&&Z(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${tw(e.mode)}`,children:m})]})]}),(g||_)&&Q(`div`,{className:`mb-2 flex flex-wrap gap-2`,children:[g&&Q(`span`,{className:`inline-flex items-center rounded bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-700 dark:bg-gray-800 dark:text-gray-200`,children:[`Swap: `,g]}),_&&Q(`span`,{className:`inline-flex items-center rounded bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-700 dark:bg-gray-800 dark:text-gray-200`,children:[`Bridge: `,_]})]}),Z(`div`,{className:`flex items-center justify-center mb-2`,children:b&&S?Q(`div`,{className:`flex items-center justify-between w-full gap-3`,children:[Q(`div`,{className:`flex items-start gap-2 flex-1 max-w-[130px]`,children:[Z(Jy,{symbol:b.symbol,imageUrl:b.imageUrl,chainId:b.chainId,size:28}),Q(`div`,{className:`flex flex-col gap-0.5`,children:[Q(`span`,{className:`text-xs font-medium text-gray-900 dark:text-gray-100 whitespace-nowrap overflow-hidden text-ellipsis`,style:{maxWidth:`85px`},children:[x==null?``:`${Xs(x,b.decimals)} `,b.symbol]}),(v?e.edge.userAddress:e.mainSigner)&&Q(`div`,{className:`flex items-center gap-1 whitespace-nowrap`,children:[Z(Uy,{value:v?e.edge.userAddress:e.mainSigner,size:12}),Z(`span`,{className:`text-xs`,style:{color:`#71717A`},title:v?e.edge.userAddress:e.mainSigner,children:wt(v?e.edge.userAddress:e.mainSigner)})]})]})]}),Z(`div`,{className:`flex items-center`,children:Z(`span`,{className:`text-xl text-gray-400 dark:text-gray-500`,children:`→`})}),Q(`div`,{className:`flex items-start gap-2 flex-1 max-w-[130px]`,children:[Z(Jy,{symbol:S.symbol,imageUrl:S.imageUrl,chainId:S.chainId,size:28}),Q(`div`,{className:`flex flex-col gap-0.5`,children:[Q(`span`,{className:`text-xs font-medium text-gray-900 dark:text-gray-100 whitespace-nowrap overflow-hidden text-ellipsis`,style:{maxWidth:`85px`},children:[C==null?``:`${Xs(C,S.decimals)} `,S.symbol]}),(y?e.edge.userAddress:e.destinationToAddress)&&Q(`div`,{className:`flex items-center gap-1 whitespace-nowrap`,children:[Z(Uy,{value:y?e.edge.userAddress:e.destinationToAddress,size:12}),Z(`span`,{className:`text-xs`,style:{color:`#71717A`},title:y?e.edge.userAddress:e.destinationToAddress,children:wt(y?e.edge.userAddress:e.destinationToAddress)})]})]})]})]}):Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400 italic`,children:`Transaction details available below`})}),I&&Z(`div`,{className:`w-full`,children:Z(XC,{error:I,severity:`error`})}),re&&Z(`div`,{className:`w-full`,children:Z(XC,{error:re,severity:`error`})}),Q(`div`,{className:`flex items-center justify-between mt-2`,children:[Q(`div`,{className:`flex items-center gap-2`,children:[Z(ZC,{status:e.executionStatus||e.intentStatus}),T&&ue?Q(`a`,{href:ue,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 text-xs transition-colors`,"aria-label":`View refund transaction on explorer`,children:[Z(`span`,{children:`View refund`}),Q(`svg`,{className:`w-3 h-3 shrink-0`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`External Link`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14`})]})]}):Q(hi,{children:[z&&Z(`button`,{type:`button`,onClick:oe,disabled:P,className:`text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 text-xs transition-colors disabled:text-gray-400 focus:outline-none cursor-pointer disabled:cursor-not-allowed`,"aria-label":`Commit intent`,children:P||j?`Committing...`:`Commit`}),V&&Z(`button`,{type:`button`,onClick:()=>H(),disabled:te,className:`text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 text-xs transition-colors disabled:text-gray-400 focus:outline-none cursor-pointer disabled:cursor-not-allowed`,"aria-label":`Execute intent`,children:te?`Executing...`:`Execute`}),R&&Q(`div`,{className:`flex items-center gap-1`,children:[Q(`button`,{type:`button`,onClick:se,className:`flex items-center gap-1 text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 text-xs transition-colors disabled:text-gray-400 focus:outline-none whitespace-nowrap cursor-pointer disabled:cursor-not-allowed`,"aria-label":`Recover funds from intent`,children:[Q(`svg`,{width:`12`,height:`12`,viewBox:`0 0 12 12`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,"aria-hidden":`true`,children:[Z(`title`,{children:`Recover icon`}),Z(`path`,{d:`M1.5 7.24996C1.5 6.38801 1.84217 5.56112 2.45166 4.95162C3.06115 4.34213 3.88805 3.99996 4.75 3.99996H8.79297L7.14648 2.35348C6.95122 2.15822 6.95122 1.84171 7.14648 1.64645C7.34175 1.45118 7.65825 1.45118 7.85352 1.64645L10.3535 4.14645C10.5488 4.34171 10.5488 4.65822 10.3535 4.85348L7.85352 7.35348C7.65825 7.54874 7.34175 7.54874 7.14648 7.35348C6.95122 7.15822 6.95122 6.84171 7.14648 6.64645L8.79297 4.99996H4.75C4.15326 4.99996 3.58114 5.23719 3.15918 5.65914C2.73722 6.0811 2.5 6.65323 2.5 7.24996C2.5 7.54539 2.55835 7.83786 2.67139 8.1108C2.78446 8.38378 2.95025 8.63185 3.15918 8.84078C3.58114 9.26274 4.15326 9.49996 4.75 9.49996H6.5C6.77614 9.49996 7 9.72382 7 9.99996C7 10.2761 6.77614 10.5 6.5 10.5H4.75C3.88805 10.5 3.06115 10.1578 2.45166 9.5483C2.14987 9.24651 1.91089 8.88792 1.74756 8.49361C1.58423 8.09931 1.5 7.67676 1.5 7.24996Z`,fill:`currentColor`})]}),`Recover funds`]}),L&&Q(`div`,{className:`relative group`,children:[Z(Vi,{className:`w-3 h-3 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 cursor-help`,"aria-label":`Token balance info`}),Q(`div`,{className:`absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-2 bg-gray-900 dark:bg-gray-700 text-white text-xs rounded-lg shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50 pointer-events-none`,children:[Q(`div`,{className:`flex flex-col gap-0.5`,children:[Q(`span`,{className:`font-medium`,children:[`Recover `,L.symbol]}),L.chainName&&Q(`span`,{className:`text-gray-400 text-xs`,children:[`on `,L.chainName]}),Q(`span`,{className:`text-gray-300`,children:[L.balanceFormatted,` `,L.symbol]}),L.balanceUsdDisplay&&Q(`span`,{className:`text-gray-400`,children:[`≈ `,L.balanceUsdDisplay]})]}),Z(`div`,{className:`absolute top-full left-1/2 -translate-x-1/2 -mt-px border-4 border-transparent border-t-gray-900 dark:border-t-gray-700`})]})]})]})]})]}),!u&&Q(`button`,{type:`button`,onClick:()=>d(!0),className:`flex items-center justify-center gap-1 py-1 px-3 rounded-md transition-colors cursor-pointer text-xs text-gray-900 dark:text-gray-100 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 whitespace-nowrap`,"aria-label":`Show more details`,children:[Z(`span`,{children:`More Details`}),Q(`svg`,{className:`w-3 h-3 transition-transform duration-300 ease-out`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[Z(`title`,{children:`Expand`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M19 9l-7 7-7-7`})]})]})]}),Z(`div`,{ref:f,className:`overflow-hidden transition-all duration-300 ease-out ${u?`max-h-[400px] opacity-100`:`max-h-0 opacity-0`}`,children:Q(`div`,{className:`p-3 rounded-lg bg-gray-50 dark:bg-gray-800`,children:[Z(`div`,{className:`flex justify-center mb-3 -mt-1`,children:Q(`button`,{type:`button`,onClick:()=>d(!1),className:`flex items-center gap-1 px-3 py-1 text-xs bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 rounded-md transition-colors duration-200 text-gray-600 dark:text-gray-300 hover:text-gray-700 dark:hover:text-gray-200 cursor-pointer`,"aria-label":`Close details`,children:[Z(`span`,{children:`Close`}),Q(`svg`,{className:`w-3 h-3 transition-transform duration-300 ease-out rotate-180`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[Z(`title`,{children:`Collapse`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M19 9l-7 7-7-7`})]})]})}),Z($C,{transaction:e,intentProtocol:le})]})})]})};function iw(e){return e?.tokenBalancesData?.tokens?.some(e=>BigInt(e.balance||`0`)>0n)??!1}const aw=({onBack:e,onRefresh:t,loading:n,effectiveAccountAddress:r,onWalletSelect:i,searchInput:a,setSearchInput:o,statusFilter:s,setStatusFilter:c,resetIntentPagination:l})=>{let[u,d]=X(!1),f=Y(null),p=Jr();return Q(hi,{children:[Z(M_,{onBack:e,headerContent:`History`,rightSideContent:Q(`div`,{className:`flex items-center gap-2`,children:[Z(`button`,{type:`button`,onClick:t,disabled:n,className:`p-2 rounded-md transition-colors cursor-pointer ${n?`opacity-50 cursor-not-allowed text-gray-400 dark:text-gray-500`:`text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-gray-700 dark:hover:text-gray-200`} focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400`,title:`Refresh`,children:Q(`svg`,{className:`w-4 h-4 ${n?`animate-spin`:``}`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`Refresh`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15`})]})}),p.length>1&&r&&Q(`div`,{className:`relative`,ref:f,children:[Q(`button`,{type:`button`,onClick:()=>d(!u),className:`flex h-8 px-4 justify-between items-center gap-2 rounded-full border border-gray-300 bg-gray-50 dark:border-gray-600 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-600`,title:`Filter by wallet`,children:[Q(`div`,{className:`flex items-center gap-2`,children:[Z(Uy,{value:r,size:16}),Z(`span`,{className:`text-xs text-gray-600 dark:text-gray-400 font-medium whitespace-nowrap`,children:wt(r,4,4)})]}),Z(Di,{className:`w-4 h-4`})]}),u&&Z(`div`,{className:`absolute top-full right-0 mt-0.5 min-w-[140px] max-w-[180px] trails-bg-secondary border border-gray-200 dark:border-gray-700 rounded-xl shadow-lg z-20 whitespace-nowrap`,children:p.map(e=>Q(`button`,{type:`button`,onClick:()=>{i(e),d(!1)},className:`w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer first:rounded-t-xl last:rounded-b-xl ${r===e.address?`bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400`:`text-gray-700 dark:text-gray-300`}`,children:[Z(Uy,{value:e.address,size:16}),Z(`span`,{className:`text-xs font-mono`,children:wt(e.address,4,4)})]},e.address))})]})]})}),Z(`div`,{className:`py-2 border-b border-gray-200 dark:border-gray-700 mb-2`,children:Z(Xy,{value:a,onChange:o,placeholder:`Search history or enter Intent ID (0x...)...`,rightAlignedComponent:Z(`div`,{className:`flex items-center gap-1`,children:a&&Z(`button`,{type:`button`,onClick:()=>o(``),className:`p-2 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 transition-colors cursor-pointer`,title:`Clear search`,children:Q(`svg`,{className:`w-4 h-4`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`Clear`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M6 18L18 6M6 6l12 12`})]})})})})}),Z(`div`,{className:`py-2`,children:Z(`div`,{className:`flex items-center gap-2 mt-2 overflow-x-auto scrollbar-hide`,children:eC.map(e=>Z(`button`,{type:`button`,title:e.tooltip,onClick:()=>{c(e.key),l()},className:`px-2 py-1.5 rounded-xl transition-colors cursor-pointer text-xs ${s===e.key?e.activeClass:`trails-bg-secondary text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600`}`,children:Z(`span`,{className:`text-xs font-medium whitespace-nowrap`,children:e.label})},e.key))})})]})},ow=({errors:e,refetch:t})=>Z(hi,{children:(e.intent||e.onramp)&&!(e.intent&&e.onramp)&&Z(`div`,{className:`mx-4 mb-2 p-2 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-700 rounded-lg`,children:Q(`p`,{className:`text-xs text-yellow-800 dark:text-yellow-200`,children:[e.intent&&!e.onramp?`Unable to load intent history. Showing onramp transactions only.`:!e.intent&&e.onramp?`Unable to load onramp history. Showing intent transactions only.`:`Some data could not be loaded.`,Z(`button`,{type:`button`,onClick:t,className:`ml-2 underline hover:no-underline cursor-pointer`,children:`Retry`})]})})}),sw=({accountAddress:e,className:t=``,onBack:n,onRecoverIntent:r})=>{let[i,a]=X(``),[o,c]=X(`all`),[l,u]=X(null),[d,f]=X(null),p=Jr(),m=Y(null),h=O_(),g=uC(e),_=Jg(),{data:v=[]}=IS();q(()=>{l&&l!==i&&u(null)},[i,l]);let y=i.startsWith(`0x`)&&/^0x[a-fA-F0-9]+$/.test(i)&&i.length>=42,b=qu(),x=d?.address||g,S=ci(d?.connectionId,d?.address),C=!d&&b?.connected&&b.publicKey?b.publicKey.toBase58():void 0,w=J(()=>nC(o),[o]),T=d?.address;q(()=>{T&&(p.some(e=>e.address.toLowerCase()===T.toLowerCase())||f(null))},[p,T]),s.console.log(`[AccountIntentTransactionHistory] Using account address:`,x);let{items:E,isOffline:D,isLoading:O,errors:k,refetch:A,hasMore:j,nextPageIntent:M,prevPageIntent:N,hasPrevIntent:P,currentIntentPage:F,refetchIntent:I,resetIntentPagination:ee,getFilteredAndSearchedItems:te}=cC({accountAddress:x,edgeAddress:C,intentPageSize:10,enabled:!!x,intentStatuses:w}),ne=j.intent,re=J(()=>{let e={};for(let t of E)if(!(t.type!==`intent`||!t.data.balances))for(let n of t.data.balances){let t=n.intentAddress.toLowerCase(),r=n.tokens.map(e=>({symbol:e.symbol,name:e.symbol,decimals:e.decimals,contractAddress:e.contractAddress,chainId:e.chainId,isNativeToken:bt(e.contractAddress),balance:e.balance,balanceFormatted:Xs(e.balance,e.decimals),balanceUsd:e.balanceUsd?Number.parseFloat(e.balanceUsd):void 0})),i={tokenBalancesData:{tokens:r,nativeTokens:r.filter(e=>e.isNativeToken),erc20Tokens:r.filter(e=>!e.isNativeToken),page:{page:1}},isLoading:!1,error:null},a=e[t];a&&iw(a)&&!iw(i)||(e[t]=i)}return e},[E]),ie=k.intent&&k.onramp?k.intent||k.onramp:null,L=J(()=>te(o,i),[o,i,te]);return g?Q(`div`,{className:`flex flex-col h-full max-h-[600px] ${t}`,children:[Z(aw,{onBack:n,onRefresh:A,loading:O,effectiveAccountAddress:x,onWalletSelect:f,searchInput:i,setSearchInput:a,statusFilter:o,setStatusFilter:c,resetIntentPagination:ee}),Z(ow,{errors:k,refetch:A}),Q(`div`,{className:`flex-1 overflow-hidden flex flex-col relative`,children:[O&&E.length>0&&Z(`div`,{className:`absolute inset-0 bg-white/50 dark:bg-gray-900/50 backdrop-blur-sm z-10 flex items-center justify-center`,children:Q(`div`,{className:`flex flex-col items-center gap-2`,children:[Z(`div`,{className:`animate-spin rounded-full h-10 w-10 border-b-2 border-blue-600 dark:border-blue-400`}),Z(`span`,{className:`text-sm text-gray-600 dark:text-gray-400`,children:`Loading...`})]})}),ie?Z(`div`,{className:`text-center flex-1 flex items-center justify-center px-6 py-8`,children:Q(`div`,{children:[Z(`div`,{className:`w-16 h-16 mx-auto mb-4 bg-red-100 dark:bg-red-900/20 rounded-full flex items-center justify-center`,children:Q(`svg`,{className:`w-8 h-8 text-red-400 dark:text-red-500`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`Error`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.464 0L4.34 16.5c-.77.833.192 2.5 1.732 2.5z`})]})}),Z(`h3`,{className:`text-lg font-medium text-gray-900 dark:text-gray-100 mb-2`,children:`Error Loading Transactions`}),Z(`p`,{className:`text-sm text-gray-600 dark:text-gray-400 mb-4`,children:ie}),Z(`button`,{type:`button`,onClick:A,className:`inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 cursor-pointer`,children:`Try Again`})]})}):O&&E.length===0?Z(`div`,{className:`flex items-center justify-center flex-1`,children:Q(`div`,{className:`flex flex-col items-center`,children:[Z(`div`,{className:`animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 dark:border-blue-400 mb-4`}),Z(`p`,{className:`text-gray-600 dark:text-gray-400`,children:`Loading intent transactions...`})]})}):E.length===0?Z(`div`,{className:`text-center flex-1 flex items-center justify-center px-6 py-8`,children:Q(`div`,{children:[Z(`div`,{className:`w-16 h-16 mx-auto mb-4 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center`,children:Q(`svg`,{className:`w-8 h-8 text-gray-400 dark:text-gray-500`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`No Transactions`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z`})]})}),Z(`h3`,{className:`text-lg font-medium text-gray-900 dark:text-gray-100 mb-2`,children:o===`quoted`?`No Quoted Transactions`:`No Intent Transactions`}),Z(`p`,{className:`text-gray-600 dark:text-gray-400`,children:o===`quoted`?`No quoted transactions found for this account.`:`No intent transactions found for this account. Create your first intent transaction to see it here.`})]})}):L.length===0?Z(`div`,{className:`text-center flex-1 flex items-center justify-center`,children:Q(`div`,{children:[Z(`div`,{className:`w-16 h-16 mx-auto mb-4 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center`,children:Q(`svg`,{className:`w-8 h-8 text-gray-400 dark:text-gray-500`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`No Results`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z`})]})}),Z(`h3`,{className:`text-lg font-medium text-gray-900 dark:text-gray-100 mb-2`,children:`No Results Found`}),Z(`p`,{className:`text-gray-600 dark:text-gray-400`,children:i&&o!==`all`?o===`onramp`?`No onramp transactions match "${i}".`:`No ${o} transactions match "${i}".`:i?`No transactions match your search "${i}".`:iC(o)})]})}):Z(`div`,{ref:m,className:`flex-1 overflow-y-auto space-y-3 pr-2 relative trails-scrollbar`,children:L.map((e,t)=>e.type===`intent`?Z(rw,{transaction:e.data,index:F*10+t,onRefetch:A,isOffline:D,commitIntentMutation:_,balancesByIntentAddress:re,selectedWalletClient:S,onRefetchBalances:I,onRecover:()=>{r?.({transaction:e.data,balancesByIntentAddress:re,isOffline:D,selectedWallet:d?{address:d.address,connectionId:d.connectionId}:null})},onCommitSuccess:()=>{y&&(u(i),setTimeout(()=>u(null),1e4)),setTimeout(()=>{A()},1e3)}},`intent-${e.data.intentId}`):Z(hC,{transaction:e.data,meldProviders:v},`onramp-${e.data.id}`))}),!i&&(P||ne)&&o!==`onramp`&&Q(`div`,{className:`flex items-center justify-center pt-2 mt-2 pb-2 gap-4`,children:[Z(`button`,{type:`button`,onClick:()=>{N(),m.current?.scrollTo({top:0,behavior:`smooth`})},disabled:!P||O,className:`p-2 rounded-full transition-colors text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-gray-700 dark:hover:text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer`,children:Q(`svg`,{className:`w-4 h-4`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`Previous Page`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M15 19l-7-7 7-7`})]})}),Z(`button`,{type:`button`,onClick:()=>{M(),m.current?.scrollTo({top:0,behavior:`smooth`})},disabled:!ne||O,className:`p-2 rounded-full transition-colors text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-gray-700 dark:hover:text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer`,children:Q(`svg`,{className:`w-4 h-4`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`Next Page`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M9 5l7 7-7 7`})]})})]})]})]}):Z(`div`,{className:`flex flex-col items-center justify-center py-12 ${t}`,children:Q(`div`,{className:`text-center`,children:[Z(`div`,{className:`w-16 h-16 mx-auto mb-4 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center`,children:Q(`svg`,{className:`w-8 h-8 text-gray-400 dark:text-gray-500`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`Wallet Lock Icon`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z`})]})}),Z(`h3`,{className:`text-lg font-medium text-gray-900 dark:text-gray-100 mb-2`,children:h?`No Wallet Address`:`Connect Wallet`}),Z(`p`,{className:`text-gray-600 dark:text-gray-400 max-w-sm`,children:h?`Unable to resolve a wallet address for transaction history.`:`Please connect your wallet to view your intent transaction history.`})]})})},cw=({address:e,startChars:t=6,endChars:n=4,className:r})=>{let{ensName:i}=Iy({address:e});return Z(`span`,{className:r,children:i||wt(e,t,n)})},lw=`https://assets.coingecko.com/coins/images/4128/standard/solana.png?1718769756`;function uw({walletId:e,connector:t}){return ma(e)?!1:t?t.flow?.toLowerCase()===`embedded`?!1:!Ir({id:t.id??``,name:t.name??``}):!0}function dw(e,t,n){if(e.isActive&&n)return n;let r=t.find(t=>t.id===e.connectionId);if(r)return r.accounts.find(t=>t.address.toLowerCase()===e.address.toLowerCase())?.chainId??r.activeAccount?.chainId??r.accounts[0]?.chainId}function fw(e){return e.filter((t,n)=>e.indexOf(t)===n)}function pw(e,t){return fw(e).filter(e=>e!==`evm`||t!==void 0)}function mw(e,t,n){let r=pw(e,n);if(r.length===0)return 0;let i=Math.round(t*.38);return Math.round(i*(r.length>1?.55:.3))}function hw({networks:e,evmChainId:t,size:n}){let r=pw(e,t);if(r.length===0)return null;let i=Math.round(n*.38),a=Math.round(i*(r.length>1?.5:.28)),o=Math.round(i*.12);return Z(`div`,{className:`absolute flex items-end justify-end pointer-events-none`,style:{right:-a,bottom:-o},children:r.map((e,n)=>Z(`div`,{className:`rounded-full border border-white dark:border-gray-900 bg-white dark:bg-gray-900`,style:{marginLeft:n>0?-Math.round(i*.35):0,zIndex:n+1},children:e===`evm`?Z(Ty,{chainId:t,size:i}):Z(`img`,{src:lw,alt:`Solana`,className:`rounded-full object-cover`,style:{width:i,height:i}})},e))})}const gw=({walletAddress:e,walletId:t,connector:n,icon:r,iconAlt:i=`Wallet`,chainId:a,networks:o,size:s=40,className:c,hideNetworkBadge:l=!1})=>{let u=!l&&uw({walletId:t,connector:n}),d=u?mw(o,s,a):0,f=r?.trim()||void 0;return Q(`div`,{className:`relative shrink-0 overflow-visible ${c??``}`,style:{width:s,height:s,marginRight:d},children:[t||f?Z(Na,{walletId:t,icon:f,label:i,size:s,className:`block shrink-0`,imageClassName:`rounded-full object-cover`,fallback:e?Z(Wy,{size:s,walletAddress:e}):void 0}):e?Z(Wy,{size:s,walletAddress:e}):Z(`div`,{role:`img`,className:`flex items-center justify-center rounded-full bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300`,style:{width:s,height:s},"aria-label":i,children:Z(na,{style:{width:s*.5,height:s*.5}})}),u?Z(hw,{networks:o,evmChainId:a,size:s}):null]})},_w=[];function vw(e,t){return t.length===0?!1:[e.evmWallet?.address,e.solanaAddress].filter(e=>!!e).some(e=>t.some(t=>t.toLowerCase()===e.toLowerCase()))}function yw(e){return e.evmWallet?.address??e.solanaAddress??xd(e)}const bw=({groupedWallet:e,onWalletSwitch:t,onWalletSelect:n,onWalletActivate:r,useFundingWalletActiveState:i=!1,onDisconnectEvm:a,onDisconnectSolana:o,showDisconnect:s=!1,hideActiveState:c=!1,disableZeroBalanceWallets:l=!1,showZeroBalanceMessage:u=!1,showWalletAddress:d=!0,evmChainId:f,isActiveFundingWallet:p=!1})=>{let m=e.evmWallet,h=yw(e),{totalBalanceUsd:g,isLoading:_}=iv({evmAddress:m?.address,solanaAddress:e.solanaAddress,networks:e.networks}),v=Ks(g),y=qs(g),b=!_&&g===0,x=l&&b,S=!m&&e.networks.includes(`solana`)&&!!e.solanaAddress,C=!c&&(n||i?p:!!m?.isActive),w=d&&!!m?.address&&!!e.solanaAddress,T=!n&&!c&&(i?!p:!!m);return Q(`button`,{type:`button`,disabled:x,onClick:()=>{if(!x){if(n){n({groupedWallet:e,evmWallet:m});return}if(i&&r&&!p){r({groupedWallet:e,evmWallet:m});return}m&&!m.isActive&&t(m)}},className:`group w-full text-left px-4 py-3 flex items-center justify-between transition-colors trails-hover-bg rounded-xl ${C?`trails-selected-bg`:``} ${x?`cursor-not-allowed opacity-50`:``} ${!x&&(n||T)?`cursor-pointer`:`cursor-default`}`,children:[Q(`div`,{className:`flex items-center gap-3 flex-1`,children:[Z(gw,{walletAddress:m?.address,walletId:e.walletId??m?.walletId,connector:m?.connector,icon:e.icon??m?.icon,iconAlt:e.name,chainId:f,networks:e.networks,size:30}),Q(`div`,{className:`flex flex-col min-w-0`,children:[d?Q(hi,{children:[Z(`span`,{className:`text-sm font-medium truncate`,children:e.name}),Q(`div`,{className:`flex items-center gap-1`,children:[Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 truncate`,children:w?Q(hi,{children:[Z(cw,{address:m.address,startChars:6,endChars:4}),` / `,wt(e.solanaAddress)]}):m?Z(cw,{address:h,startChars:6,endChars:4}):h?wt(h):null}),h?Z(U,{text:h,size:`sm`,stopPropagation:!0,className:`p-1`,as:`span`}):null]})]}):Q(`div`,{className:`flex items-center gap-1 min-w-0`,children:[Z(`span`,{className:`text-sm font-medium truncate`,children:e.name}),h?Z(U,{text:h,size:`sm`,stopPropagation:!0,className:`p-1 shrink-0`,as:`span`}):null]}),!_&&(u&&b?Z(`span`,{className:`text-xs text-gray-400 dark:text-gray-500`,children:`No balance available for funding`}):v&&Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400`,title:v,children:y||v}))]})]}),Q(`div`,{className:`flex items-center gap-2`,children:[C?Z(`span`,{className:`text-xs px-2 py-1 rounded font-medium trails-selected-text`,children:`Active`}):T&&!c?Z(`span`,{className:`whitespace-nowrap text-xs px-2 py-1 rounded font-medium bg-gray-200 text-gray-700 dark:bg-gray-600 dark:text-gray-300 opacity-0 group-hover:opacity-100 transition-opacity duration-200`,children:`Set active`}):null,s&&(m?.showDisconnect===!0||S)&&Z(`span`,{role:`button`,tabIndex:0,onClick:e=>{if(e.stopPropagation(),m){a(m);return}o()},onKeyDown:e=>{if(e.key===`Enter`||e.key===` `){if(e.preventDefault(),e.stopPropagation(),m){a(m);return}o()}},className:`p-1 rounded-full hover:bg-gray-200 dark:hover:bg-gray-600 cursor-pointer`,title:`Disconnect wallet`,children:Z(ra,{className:`w-4 h-4 text-gray-500 dark:text-gray-400`})}),n&&!C&&Z(ki,{className:`w-5 h-5 text-gray-400`})]})]})},xw=({onWalletSwitch:e,onWalletSelect:t,showActiveWallet:n=!0,showConnectNewWallet:r=!1,showDisconnect:i=!1,className:a=``,backScreen:o=`connect`,hiddenWallets:c=_w,disableZeroBalanceWallets:l=!1,showZeroBalanceMessage:u=!1,showWalletAddress:d=!0,activeFundingWallet:f})=>{let{address:p,chainId:m,connectionId:h}=Yr(),g=Xr(),_=Jr(),v=ni(),y=qu(),{mode:b}=y_(),x=ux(),{setConnectionContext:S}=$o(),{selectedFundingWallet:C,setSelectedFundingWallet:w,setSelectedFundMethod:T}=Vu(),{selectedToken:E,clearSelectedToken:D,setHasManualSelection:O}=ul(),{clearChainFilter:k}=mu(),[A,j]=X(null),{selectedRecipient:M,setSelectedRecipient:N}=cu(),{hideAddWallet:P}=wo(),F=li().filter(e=>e.namespace===`eip155`),{disconnect:I,switchAccount:ee}=ai(),te=Ao(),ne=J(()=>vd({connectedWallets:_,svmWallet:y,session:v}),[_,y,v]),re=o===`account-settings`&&!t,ie=J(()=>yd({groupedWallets:ne,selectedFundingWallet:C}),[ne,C]),L=ne.filter(e=>!(!n&&(e.evmWallet?.isActive||f!=null&&Qu(e.selection,f))||vw(e,c))),R=L.length>0,ae=F.some(Rr),z=r&&!P&&te&&ae,B=t=>{try{j(null),ee(t.connectionId,t.address),s.console.log(`[trails-sdk] Switched to wallet: ${t.address}`),e?.(t.address)}catch(e){s.console.error(`[trails-sdk] Failed to switch wallet:`,e),j(e instanceof Error?e.message:`Failed to switch wallet`)}},V=({groupedWallet:e,evmWallet:t})=>{let n=t?Ju(t):e.selection;w(n),T(`wallet`),$u(E?.chainId,n)&&(D(),O(!1),k()),t&&B(t)},oe=async e=>{try{if(j(null),await I(e.connectionId),td(C,e)&&w(null),M===e.address){let t=_.filter(t=>t.address!==e.address)[0]?.address;N(t||null)}s.console.log(`[trails-sdk] Disconnected wallet`)}catch(e){s.console.error(`[trails-sdk] Failed to disconnect wallet:`,e),j(e instanceof Error?e.message:`Failed to disconnect wallet`)}},H=async()=>{if(y?.disconnect)try{j(null),await Promise.resolve(y.disconnect()),Zu(C)&&w(null);let e=y.publicKey?.toBase58?.();if(e&&M===e){let e=_[0]?.address??null;N(e)}s.console.log(`[trails-sdk] Disconnected Solana wallet`)}catch(e){s.console.error(`[trails-sdk] Failed to disconnect Solana wallet:`,e),j(e instanceof Error?e.message:`Failed to disconnect wallet`)}};if(!R&&!z)return null;let se=()=>{s.console.log(`[trails-sdk] Navigating from connected-wallets to wallet-list`),o===`recipients`?(s.console.log(`[trails-sdk] Setting wallet connection context for recipient selection`),S(`recipient-selection`,o,p,h)):o===`fund-methods`||o===`account-settings`&&b===`fund`?(s.console.log(`[trails-sdk] Setting wallet connection context for fund method selection`),S(`fund-method-selection`,o)):S(`general`,o),x({backTarget:o})};return Q(hi,{children:[R&&Q(`div`,{className:`px-3 pb-2 flex items-center justify-between gap-2`,children:[Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`Connected wallets`}),z?Q(`button`,{type:`button`,onClick:se,className:`inline-flex items-center gap-1 rounded-full px-2 py-1 text-xs font-medium text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer transition-colors`,"aria-label":`Connect new wallet`,children:[Z(ji,{"aria-hidden":`true`,className:`h-3.5 w-3.5`}),Z(`span`,{children:`Add wallet`})]}):null]}),Z(`div`,{className:`space-y-2 ${a}`,children:Q(`div`,{className:`flex flex-col gap-1`,children:[A&&Z(`div`,{className:`border rounded-lg p-4 bg-red-50 border-red-200 dark:bg-red-900/20 dark:border-red-800 mx-4 mb-2`,children:Z(`p`,{className:`text-sm wrap-break-word text-red-600 dark:text-red-200`,children:A})}),L.map(e=>Z(bw,{groupedWallet:e,onWalletSwitch:B,onWalletSelect:t,onWalletActivate:V,useFundingWalletActiveState:re,onDisconnectEvm:oe,onDisconnectSolana:H,showDisconnect:i,hideActiveState:o===`recipients`,disableZeroBalanceWallets:l,showZeroBalanceMessage:u,showWalletAddress:d,isActiveFundingWallet:t||re?Qu(e.selection,f??ie??null):!1,evmChainId:e.evmWallet?dw(e.evmWallet,g,m):void 0},rd(e.selection))),z&&!R&&Q(`button`,{type:`button`,onClick:se,className:`w-full text-left px-4 py-3 flex items-center justify-between cursor-pointer transition-colors trails-hover-bg rounded-xl`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(ji,{"aria-hidden":`true`,className:`h-6 w-6 shrink-0 text-gray-600 dark:text-gray-100`}),Z(`span`,{className:`text-sm font-medium`,children:`Connect wallet`})]}),Z(ki,{className:`w-5 h-5 text-gray-400`})]})]})})]})},Sw=[{label:`Buy Crypto`,screen:`fund-form`,icon:Pi,disabled:!1,subtitle:void 0,modeOverride:`fund`},{label:`History`,screen:`account-history`,icon:zi,disabled:!1,subtitle:void 0},{label:`User preferences`,screen:`user-preferences`,icon:ta,disabled:!1,subtitle:void 0},{label:`Disconnect`,screen:`disconnect`,icon:Ui,disabled:!1,subtitle:void 0}],Cw=()=>{window.open(`https://support.trails.build/en/`,`_blank`)},ww=({onBack:e})=>{let{activeConnection:t}=Yr(),{fundOptions:n}=wo(),{overrideMode:r,navigate:i}=y_(),{setSelectedFundMethod:a,setPaymentMethod:o}=Vu(),s=(t?.showDisconnect??t?.ui?.showDisconnect)!==!0;return Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{headerContent:`Settings`,headerContentAlign:`left`,onBack:e,rightSideContent:Z(y,{message:`Get help`,children:Z(`button`,{type:`button`,onClick:Cw,className:`flex h-8 w-8 justify-center items-center rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600`,title:`Get help`,children:Z(Ri,{className:`w-4 h-4`})})})}),Z(`div`,{className:`flex-1`,children:Q(`div`,{className:`flex flex-col gap-1`,children:[Z(xw,{showConnectNewWallet:!0,showDisconnect:!0,showWalletAddress:!1,backScreen:`account-settings`,hiddenWallets:n?.hideWallets??[]}),Z(`div`,{className:`my-3 border-t border-gray-200 dark:border-gray-700`}),Z(`div`,{className:`flex flex-col gap-1`,children:Sw.map(e=>{if(e.disabled||s&&e.screen===`disconnect`)return null;let t=e.icon;return Q(`button`,{type:`button`,onClick:()=>{e.label===`Buy Crypto`&&(a(`onramp-meld`),o({id:`CREDIT_DEBIT_CARD`,name:`Credit/Debit Card`})),e.modeOverride?(r(e.modeOverride),i(e.screen,{backTarget:`account-settings`})):i(e.screen)},className:`w-full text-left px-4 py-3 flex items-center justify-between cursor-pointer transition-colors trails-hover-bg rounded-xl`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(t,{className:`w-5 h-5 text-gray-700 dark:text-gray-200`}),Q(`div`,{children:[Z(`span`,{className:`text-sm font-medium`,children:e.label}),e.subtitle&&Z(`p`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:e.subtitle})]})]}),Z(ki,{className:`w-5 h-5 text-gray-400`})]},e.screen)})})]})})]})},Tw=({className:e})=>Z(`div`,{className:`animate-spin rounded-full h-4 w-4 border-solid border-b-2 trails-primary ${e}`});function Ew(e,t){return t.find(t=>t.countryCode===e)?.name||e}function Dw(e,t){return t.find(t=>t.countryCode===e)?.flag||`🌍`}function Ow(e){return e}const kw=e=>{if(e?.length!==2)return`🌍`;let t=e.toUpperCase().split(``).map(e=>127397+e.charCodeAt(0));return String.fromCodePoint(...t)},Aw=({onBack:e,onSelectCountry:t,selectedCountry:n})=>{let{data:r=[],isLoading:i,error:a,refetch:o}=Xx(),s=J(()=>Ow(r),[r]),[c,l]=X(``),{data:u}=Yx({enabled:!0}),d=J(()=>{let e=s;if(c.trim()){let t=c.toLowerCase().trim();e=s.filter(e=>e.name.toLowerCase().includes(t)||e.countryCode.toLowerCase().includes(t))}return e.sort((e,t)=>{if(u){if(e.countryCode===u&&t.countryCode!==u)return-1;if(t.countryCode===u&&e.countryCode!==u)return 1}return e.name.localeCompare(t.name)})},[s,c,u]),f=e=>{t&&t(e)};return Q(`div`,{className:`flex flex-col h-full`,children:[Z(bv,{onBack:e,title:`Select Country`}),Q(`div`,{className:`flex-1 overflow-y-auto`,children:[Z(`div`,{className:`p-4 border-b border-gray-200 dark:border-gray-700`,children:Q(`div`,{className:`relative`,children:[Z(`div`,{className:`absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none`,children:Z(qi,{className:`h-5 w-5 text-gray-500 dark:text-gray-500`})}),Z(`input`,{type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`Search countries...`,className:`block w-full pl-10 pr-4 py-2 border border-solid border-gray-200 dark:border-gray-700 rounded-lg focus:ring-2 focus:ring-polygon-500 focus:border-polygon-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400`})]})}),i&&Q(`div`,{className:`flex items-center justify-center py-8 space-x-3`,children:[Z(`div`,{className:`animate-spin rounded-full h-6 w-6 border-b-2 border-polygon-500`}),Z(`div`,{className:`text-gray-600 dark:text-gray-400`,children:`Loading countries...`})]}),a&&Z(`div`,{className:`flex items-center justify-center py-8 px-4`,children:Q(`div`,{className:`text-center p-4 border border-solid border-red-200 dark:border-red-700 rounded-lg bg-red-50 dark:bg-red-900/20 max-w-md`,children:[Z(`div`,{className:`text-red-600 dark:text-red-400 font-medium mb-2`,children:`Error loading countries`}),Z(`div`,{className:`text-sm text-red-500 dark:text-red-300`,children:a.message||`Failed to load country list. Please check your internet connection and try again.`}),a.message?.includes(`Network`)&&Z(`div`,{className:`text-xs text-red-400 dark:text-red-400 mt-1`,children:`Check that the trails-api server is running and accessible.`}),Z(`button`,{type:`button`,onClick:()=>o(),className:`mt-3 px-4 py-2 text-sm bg-red-100 hover:bg-red-200 dark:bg-red-800 dark:hover:bg-red-700 text-red-700 dark:text-red-200 rounded-md transition-colors`,children:`Retry`})]})}),!i&&!a&&Z(`div`,{className:`space-y-2 p-4 max-h-[400px] overflow-y-auto`,children:d.length===0&&c.trim()?Z(`div`,{className:`flex items-center justify-center py-8`,children:Q(`div`,{className:`text-gray-600 dark:text-gray-400`,children:[`No countries found matching "`,c,`"`]})}):d.map(e=>{let t=n?.countryCode===e.countryCode,r=u===e.countryCode;return Q(`button`,{type:`button`,onClick:()=>f(e),className:`w-full flex items-center justify-between cursor-pointer font-semibold py-4 px-6 rounded-lg transition-all duration-200 ${t?`bg-polygon-50 dark:bg-polygon-900/20 border-2 border-polygon-500 dark:border-polygon-400`:`bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 border-2 border-transparent`} text-gray-900 dark:text-white`,children:[Q(`div`,{className:`flex items-center space-x-3 flex-1`,children:[Z(`div`,{className:`w-10 h-10 rounded-lg flex items-center justify-center text-2xl`,children:kw(e.countryCode)}),Z(`div`,{className:`flex-1 text-left`,children:Q(`div`,{className:`flex items-center gap-2`,children:[Z(`h4`,{className:`font-semibold text-gray-900 dark:text-gray-100`,children:e.name}),r&&Z(`span`,{className:`text-xs px-2 py-0.5 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 rounded-full`,children:`Your Location`})]})})]}),t&&Z(`div`,{className:`text-polygon-500 dark:text-polygon-400`,children:Q(`svg`,{className:`w-5 h-5`,fill:`currentColor`,viewBox:`0 0 20 20`,"aria-label":`Selected`,children:[Z(`title`,{children:`Selected`}),Z(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z`,clipRule:`evenodd`})]})}),!t&&Z(`div`,{className:`text-gray-400`,children:Q(`svg`,{className:`w-5 h-5`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-label":`Chevron right`,children:[Z(`title`,{children:`Chevron right`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M9 5l7 7-7 7`})]})})]},e.countryCode)})})]})]})},jw=({onBack:e,onSelectPaymentMethod:t,selectedPaymentMethod:n,hideHeader:r=!1,trailsClient:i,fiatCurrency:a=`USD`,onNavigateToFund:o})=>{let{data:c=[],isLoading:l,error:u}=Or(PS.paymentMethodList(i||null,a)),[d,f]=X(``),[p,m]=X(new Set),h=J(()=>{if(!d.trim())return c;let e=d.toLowerCase().trim();return c.filter(t=>t.name.toLowerCase().includes(e)||t.paymentType.toLowerCase().includes(e)||t.paymentMethod.toLowerCase().includes(e))},[c,d]),g=e=>{s.console.log(`[onramp] Selected Meld payment method: ${e}`),t&&t(e),e===`CREDIT_DEBIT_CARD`&&o&&o()},_=e=>{m(t=>new Set(t).add(e))};return Q(`div`,{className:`flex flex-col h-full`,children:[!r&&Z(bv,{onBack:e,title:`Select Payment Method`}),Q(`div`,{className:`flex-1 overflow-y-auto`,children:[l&&Z(`div`,{className:`flex items-center justify-center py-8`,children:Q(`div`,{className:`text-center`,children:[Z(`div`,{className:`w-8 h-8 border-solid border-2 border-polygon-500 border-t-transparent rounded-full animate-spin mx-auto mb-4`}),Z(`p`,{className:`text-gray-600 dark:text-gray-400`,children:`Loading payment methods...`})]})}),u&&Z(`div`,{className:`flex items-center justify-center py-8`,children:Z(`div`,{className:`text-center p-4 border border-solid border-red-200 dark:border-red-700 rounded-lg bg-red-50 dark:bg-red-900/20`,children:Q(`p`,{className:`text-red-600 dark:text-red-400`,children:[`Error loading payment methods: `,u.message]})})}),!l&&!u&&c.length===0&&Z(`div`,{className:`flex items-center justify-center py-8`,children:Z(`div`,{className:`text-gray-600 dark:text-gray-400`,children:`No payment methods available`})}),!l&&!u&&c.length>0&&Q(hi,{children:[Z(`div`,{className:`p-4 border-b border-gray-200 dark:border-gray-700`,children:Q(`div`,{className:`relative`,children:[Z(`div`,{className:`absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none`,children:Z(qi,{className:`h-5 w-5 text-gray-500 dark:text-gray-500`})}),Z(`input`,{type:`text`,value:d,onChange:e=>f(e.target.value),placeholder:`Search payment methods...`,className:`block w-full pl-10 pr-4 py-2 border border-solid border-gray-200 dark:border-gray-700 rounded-lg focus:ring-2 focus:ring-polygon-500 focus:border-polygon-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400`})]})}),Z(`div`,{className:`space-y-4 p-4 max-h-[400px] overflow-y-auto`,children:h.length===0&&d.trim()?Z(`div`,{className:`flex items-center justify-center py-8`,children:Q(`div`,{className:`text-gray-600 dark:text-gray-400`,children:[`No payment methods found matching "`,d,`"`]})}):h.map(e=>{let t=n===e.paymentMethod;return Q(`button`,{type:`button`,onClick:()=>g(e.paymentMethod),className:`w-full flex items-center justify-between cursor-pointer font-semibold py-4 px-6 rounded-lg transition-all duration-200 ${t?`bg-polygon-50 dark:bg-polygon-900/20 border-2 border-polygon-500 dark:border-polygon-400`:`bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 border-2 border-transparent`} text-gray-900 dark:text-white`,children:[Q(`div`,{className:`flex items-center space-x-3 flex-1`,children:[(e.logos?.light||e.logos?.dark)&&!p.has(e.paymentMethod)?Z(`div`,{className:`w-12 h-12 rounded-lg flex items-center justify-center bg-white dark:bg-gray-700 p-2`,children:Z(`img`,{src:e.logos?.light||e.logos?.dark||``,alt:`${e.name} logo`,className:`max-w-full max-h-full object-contain`,onError:()=>_(e.paymentMethod)})}):Z(`div`,{className:`w-12 h-12 rounded-lg flex items-center justify-center ${t?`bg-polygon-500 dark:bg-polygon-400`:`bg-gray-200 dark:bg-gray-700`}`,children:Q(`svg`,{className:`w-6 h-6 text-white`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-label":`Payment method icon`,children:[Z(`title`,{children:`Payment method icon`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z`})]})}),Q(`div`,{className:`flex-1 text-left`,children:[Z(`h4`,{className:`font-semibold text-gray-900 dark:text-gray-100`,children:e.name}),Z(`p`,{className:`text-sm text-gray-600 dark:text-gray-400`,children:e.paymentType})]})]}),t&&Z(`div`,{className:`text-polygon-500 dark:text-polygon-400`,children:Q(`svg`,{className:`w-5 h-5`,fill:`currentColor`,viewBox:`0 0 20 20`,"aria-label":`Selected`,children:[Z(`title`,{children:`Selected`}),Z(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z`,clipRule:`evenodd`})]})}),!t&&Z(`div`,{className:`text-gray-400`,children:Q(`svg`,{className:`w-5 h-5`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-label":`Chevron right`,children:[Z(`title`,{children:`Chevron right`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M9 5l7 7-7 7`})]})})]},e.paymentMethod)})})]})]})]})},Mw=e=>({BANXA:`bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400`,TRANSAK:`bg-polygon-100 dark:bg-polygon-900/30 text-polygon-600 dark:text-polygon-400`,MOONPAY:`bg-indigo-100 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400`})[e]||`bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400`,Nw=({onBack:e,onSelectProvider:t,selectedProvider:n,providers:r,isLoading:i=!1})=>{let a=e=>{t&&t(e)};return Q(`div`,{className:`flex flex-col h-full`,children:[Z(bv,{onBack:e,title:`Select Provider`}),Z(`div`,{className:`flex-1 overflow-y-auto p-4 max-h-[400px]`,children:i?Q(`div`,{className:`flex items-center justify-center py-8 space-x-3`,children:[Z(`div`,{className:`animate-spin rounded-full h-6 w-6 border-b-2 border-polygon-500`}),Z(`div`,{className:`text-gray-600 dark:text-gray-400`,children:`Finding best providers...`})]}):r.length===0?Z(`div`,{className:`flex items-center justify-center py-8`,children:Z(`div`,{className:`text-gray-600 dark:text-gray-400`,children:`No providers available. Please select country and token first.`})}):Z(`div`,{className:`space-y-3`,children:r.map((e,t)=>{let r=n?.serviceProvider===e.serviceProvider,i=t===0;return Q(`button`,{type:`button`,onClick:()=>a(e),className:`w-full p-4 rounded-lg transition-all duration-200 cursor-pointer ${r?`bg-polygon-50 dark:bg-polygon-900/20 border-2 border-polygon-500 dark:border-polygon-400`:`bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 border-2 border-transparent`}`,children:[Q(`div`,{className:`flex items-center justify-between mb-3`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(`div`,{className:`w-10 h-10 rounded-lg flex items-center justify-center ${Mw(e.serviceProvider)}`,children:Z(wi,{className:`w-5 h-5`})}),Q(`div`,{className:`text-left`,children:[Z(`h4`,{className:`font-bold text-gray-900 dark:text-gray-100`,children:e.serviceProvider}),i&&Q(`div`,{className:`flex items-center gap-1 text-xs text-green-600 dark:text-green-400`,children:[Z(Zi,{className:`w-3 h-3 fill-current`}),Z(`span`,{children:`Best Rate`})]})]})]}),r&&Z(`div`,{className:`text-polygon-500 dark:text-polygon-400`,children:Q(`svg`,{className:`w-6 h-6`,fill:`currentColor`,viewBox:`0 0 20 20`,"aria-label":`Selected`,children:[Z(`title`,{children:`Selected`}),Z(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z`,clipRule:`evenodd`})]})})]}),Q(`div`,{className:`grid grid-cols-2 gap-3 text-sm`,children:[Q(`div`,{className:`flex items-center gap-2`,children:[Z(Ii,{className:`w-4 h-4 text-gray-500`}),Q(`div`,{className:`text-left`,children:[Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`You Get`}),Z(`div`,{className:`font-semibold text-gray-900 dark:text-gray-100`,children:e.destinationAmount.toFixed(6)})]})]}),Q(`div`,{className:`flex items-center gap-2`,children:[Z(Qi,{className:`w-4 h-4 text-gray-500`}),Q(`div`,{className:`text-left`,children:[Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`Total Fee`}),Q(`div`,{className:`font-semibold text-gray-900 dark:text-gray-100`,children:[`$`,e.totalFee.toFixed(2)]})]})]}),Q(`div`,{className:`flex items-center gap-2`,children:[Z(Zi,{className:`w-4 h-4 text-gray-500`}),Q(`div`,{className:`text-left`,children:[Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`Score`}),Z(`div`,{className:`font-semibold text-gray-900 dark:text-gray-100`,children:e.customerScore})]})]}),Q(`div`,{className:`flex items-center gap-2`,children:[Z(Ii,{className:`w-4 h-4 text-gray-500`}),Q(`div`,{className:`text-left`,children:[Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`Rate`}),Z(`div`,{className:`font-semibold text-gray-900 dark:text-gray-100`,children:e.exchangeRate.toFixed(2)})]})]})]}),Z(`div`,{className:`mt-3 pt-3 border-t border-gray-200 dark:border-gray-700`,children:Q(`div`,{className:`flex justify-between text-xs text-gray-600 dark:text-gray-400`,children:[Q(`span`,{children:[`Transaction Fee: $`,e.transactionFee.toFixed(2)]}),Q(`span`,{children:[`Network Fee: $`,e.networkFee.toFixed(2)]})]})})]},e.serviceProvider)})})})]})},Pw={ETH:Kn.id,BASE:Mn.id,OP:Yn.id,ARB:Tn.id,MATIC:Zn.id,AVAX:On.id,BSC:Ln.id};function Fw(e,t){let n=he(`trailsApiUrl`);return hv({apiKey:e,hostname:t||n||`https://trails-api.sequence.app`})}const Iw=e=>({ETH:`bg-polygon-100 dark:bg-polygon-900/30 text-polygon-700 dark:text-polygon-400`,BASE:`bg-polygon-100 dark:bg-polygon-900/30 text-polygon-700 dark:text-polygon-400`,OP:`bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400`,ARB:`bg-cyan-100 dark:bg-cyan-900/30 text-cyan-700 dark:text-cyan-400`,MATIC:`bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400`,AVAX:`bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400`,BSC:`bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400`,CELO:`bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400`})[e]||`bg-gray-100 dark:bg-gray-900/30 text-gray-700 dark:text-gray-400`,Lw=({onBack:e,onSelectToken:t,selectedToken:n,trailsClient:r,countryCode:i})=>{let{data:a=[],isLoading:o,error:s}=Or(PS.cryptoCurrencyList(r,i??null)),{data:c=[]}=Hx(),l=J(()=>c.map(e=>e.id),[c]),u=J(()=>{let e=new Set([`ETH`,`MATIC`,`AVAX`,`BNB`,`USDC`,`USDT`,`DAI`]),t=[`USDC`,`USDT`,`DAI`];return a.map(e=>{let t=e.currencyCode||``,n=e.name||t,r=t.split(`_`),i=r[0]||t,a=r[1]||``,o=Pw[a],s;return o&&i&&(s=i===`ETH`&&[1,10,8453,42161].includes(o)||i===`MATIC`&&o===137||i===`AVAX`&&o===43114||i===`BNB`&&o===56?Cn:qe.find(e=>e.symbol===i&&e.chainId===o)?.contractAddress),{code:t,name:n,symbol:i,chain:a,chainName:o?$(o)?.name??a:a,chainId:o,contractAddress:s}}).filter(t=>e.has(t.symbol)).filter(e=>e.chainId!=null&&l.includes(e.chainId)).filter((e,t,n)=>t===n.findIndex(t=>t.code===e.code)).sort((e,n)=>{let r=t.includes(e.symbol),i=t.includes(n.symbol);return r&&!i?-1:!r&&i?1:e.symbol.localeCompare(n.symbol)})},[a,l]),d=o,f=s,[p,m]=X(``),h=J(()=>{let e=u;if(p.trim()){let t=p.toLowerCase().trim();e=u.filter(e=>e.name.toLowerCase().includes(t)||e.symbol.toLowerCase().includes(t)||e.chainName.toLowerCase().includes(t))}if(n){let t=[...e],r=t.findIndex(e=>e.code===n.code);if(r>0){let[e]=t.splice(r,1);e&&t.unshift(e)}return t}return e},[u,p,n]),g=e=>{t&&t(e)};return Q(`div`,{className:`flex flex-col h-full`,children:[Z(bv,{onBack:e,title:`Select Token`}),Q(`div`,{className:`flex-1 overflow-y-auto`,children:[d&&Z(`div`,{className:`flex items-center justify-center py-8`,children:Q(`div`,{className:`text-center`,children:[Z(`div`,{className:`w-8 h-8 border-solid border-2 border-polygon-500 border-t-transparent rounded-full animate-spin mx-auto mb-4`}),Z(`p`,{className:`text-gray-600 dark:text-gray-400`,children:`Loading tokens...`})]})}),f&&Z(`div`,{className:`flex items-center justify-center py-8`,children:Z(`div`,{className:`text-center p-4 border border-solid border-red-200 dark:border-red-700 rounded-lg bg-red-50 dark:bg-red-900/20`,children:Q(`p`,{className:`text-red-600 dark:text-red-400`,children:[`Error loading tokens: `,f.message]})})}),!d&&!f&&Q(hi,{children:[Z(`div`,{className:`p-4 border-b border-gray-200 dark:border-gray-700`,children:Q(`div`,{className:`relative`,children:[Z(`div`,{className:`absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none`,children:Z(qi,{className:`h-5 w-5 text-gray-500 dark:text-gray-500`})}),Z(`input`,{type:`text`,value:p,onChange:e=>m(e.target.value),placeholder:`Search tokens...`,className:`block w-full pl-10 pr-4 py-2 border border-solid border-gray-200 dark:border-gray-700 rounded-lg focus:ring-2 focus:ring-polygon-500 focus:border-polygon-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400`})]})}),Z(`div`,{className:`space-y-2 p-4 max-h-[400px] overflow-y-auto`,children:h.length===0&&p.trim()?Z(`div`,{className:`flex items-center justify-center py-8`,children:Q(`div`,{className:`text-gray-600 dark:text-gray-400`,children:[`No tokens found matching "`,p,`"`]})}):u.length===0&&!p.trim()?Z(`div`,{className:`flex items-center justify-center py-8`,children:Q(`div`,{className:`text-gray-600 dark:text-gray-400`,children:[`No tokens available for `,i||`this country`]})}):h.map(e=>{let t=n?.code===e.code;return Q(`button`,{type:`button`,onClick:()=>g(e),className:`w-full flex items-center justify-between cursor-pointer font-semibold py-4 px-6 rounded-lg transition-all duration-200 ${t?`bg-polygon-50 dark:bg-polygon-900/20 border-2 border-polygon-500 dark:border-polygon-400`:`bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 border-2 border-transparent`} text-gray-900 dark:text-white`,children:[Q(`div`,{className:`flex items-center space-x-3 flex-1`,children:[Z(`div`,{className:`mr-2`,children:Z(Jy,{symbol:e.symbol,chainId:e.chainId,contractAddress:e.contractAddress,size:48})}),Q(`div`,{className:`flex-1 text-left`,children:[Q(`div`,{className:`flex items-center gap-2`,children:[Z(`h4`,{className:`font-semibold text-gray-900 dark:text-gray-100`,children:e.symbol}),Z(`span`,{className:`text-xs px-2 py-0.5 rounded-full ${Iw(e.chain)}`,children:e.chainName===`Ethereum/mainnet`?`Ethereum`:e.chainName})]}),Z(`p`,{className:`text-sm text-gray-600 dark:text-gray-400`,children:e.name})]})]}),t&&Z(`div`,{className:`text-polygon-500 dark:text-polygon-400`,children:Q(`svg`,{className:`w-5 h-5`,fill:`currentColor`,viewBox:`0 0 20 20`,"aria-label":`Selected`,children:[Z(`title`,{children:`Selected`}),Z(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z`,clipRule:`evenodd`})]})}),!t&&Z(`div`,{className:`text-gray-400`,children:Q(`svg`,{className:`w-5 h-5`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-label":`Chevron right`,children:[Z(`title`,{children:`Chevron right`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M9 5l7 7-7 7`})]})})]},e.code)})})]})]})]})},Rw=e=>typeof e==`string`&&e.length>0?e:void 0,zw=e=>{if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===`transak.com`||t.endsWith(`.transak.com`)}catch{return!1}},Bw=({serviceProvider:e,widgetUrl:t,serviceProviderWidgetUrl:n,fallbackUrl:r})=>{let i=Rw(t),a=Rw(n),o=Rw(r),s=(typeof e==`string`?e.toLowerCase():``)===`transak`||zw(a);return{selectedWidgetUrl:s?i||a||o:a||i||o,meldWidgetUrl:i,serviceProviderWidgetUrl:a,fallbackUrl:o,isTransakProvider:s}};function Vw(e={}){let{enabled:t=!0}=e,{data:n,isLoading:r,error:i}=Yx({enabled:t}),a=gv(),{data:o,isLoading:s,error:c}=Or({...PS.countryDefaultsByCode(a,n??null),enabled:t}),l=r||s,u=i||c;return{countryCode:n||null,defaultCurrencyCode:o?.defaultCurrencyCode||null,defaultPaymentMethods:o?.defaultPaymentMethods||[],isLoading:l,error:u}}const Hw=(e,t)=>{if(typeof window>`u`)return`width=${e},height=${t},left=0,top=0,resizable=yes,scrollbars=yes`;let n=window.screenLeft||window.screenX||0,r=window.screenTop||window.screenY||0,i=window.innerWidth||document.documentElement.clientWidth||screen.width,a=window.innerHeight||document.documentElement.clientHeight||screen.height;return`width=${e},height=${t},left=${Math.round(n+(i-e)/2)},top=${Math.round(r+(a-t)/2)},resizable=yes,scrollbars=yes`},Uw=(e,t,n)=>{if(typeof window>`u`)return{popup:null,blocked:!0,error:`Window not available (SSR)`};let r=Hw(t,n),i=window.open(`about:blank`,e,r);if(!i||i.closed)return{popup:null,blocked:!0,error:`Popup blocked. Please allow popups for this site to continue with payment.`};try{i.document.write(`
47
+ <!DOCTYPE html>
48
+ <html>
49
+ <head>
50
+ <title>Loading...</title>
51
+ <style>
52
+ body {
53
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
54
+ display: flex;
55
+ flex-direction: column;
56
+ align-items: center;
57
+ justify-content: center;
58
+ height: 100vh;
59
+ margin: 0;
60
+ background: #f5f5f5;
61
+ color: #333;
62
+ }
63
+ .spinner {
64
+ width: 40px;
65
+ height: 40px;
66
+ border: 3px solid #e0e0e0;
67
+ border-top-color: #3b82f6;
68
+ border-radius: 50%;
69
+ animation: spin 1s linear infinite;
70
+ }
71
+ @keyframes spin {
72
+ to { transform: rotate(360deg); }
73
+ }
74
+ p {
75
+ margin-top: 16px;
76
+ font-size: 14px;
77
+ color: #666;
78
+ }
79
+ </style>
80
+ </head>
81
+ <body>
82
+ <div class="spinner"></div>
83
+ <p>Preparing payment...</p>
84
+ </body>
85
+ </html>
86
+ `),i.document.close()}catch{}return{popup:i,blocked:!1}},Ww=(e,t)=>{if(!e||e.closed)return console.warn(`[SafePopup] Cannot set URL - popup is closed or null`),!1;try{return e.location.href=t,!0}catch(e){return console.error(`[SafePopup] Failed to set popup URL:`,e),!1}},Gw=e=>{if(e&&!e.closed)try{e.close()}catch{}};function Kw(e){let{sessionId:t,transactionId:n,externalSessionId:r,enabled:i=!0,trackTimeElapsed:a=!0,onWindowClosed:o,onStatusChange:c,popupOpened:l=!1}=e,u=gv(),d=Vx(),[f,p]=X(null),[m,h]=X(0),[g,_]=X(!1),[v,y]=X(null),b=Y(null),x=Y(null),S=r||n||t,C=!!r,{data:w,refetch:T,isLoading:E,error:D}=Or({queryKey:[`meld-transaction-status`,S,C],queryFn:async()=>{if(!S)throw Error(`Transaction ID, Session ID, or External Session ID is required`);s.console.log(`[useMeldTransactionStatus] Fetching transaction status`,{sessionId:t,transactionId:n,externalSessionId:r,activeId:S,useSearchAPI:C});try{if(C){let e={externalSessionIds:S,limit:20},t=await u.searchMeldTransactions(e);s.console.log(`[useMeldTransactionStatus] SearchMeldTransactions response:`,{transactionCount:t.transactions?.transactions?.length||0});let n=t.transactions?.transactions||[];if(n.length===0)return s.console.debug(`[useMeldTransactionStatus] No transactions found for externalSessionId, continuing to poll`,{externalSessionId:S}),{id:S,status:`PENDING`,sourceAmount:void 0,sourceCurrencyCode:void 0,destinationAmount:void 0,destinationCurrencyCode:void 0,walletAddress:void 0,createdAt:void 0,updatedAt:void 0,serviceProvider:void 0,paymentMethod:void 0,transactionHash:void 0,externalSessionId:S,externalCustomerId:void 0};let r=n.reduce((e,t)=>{let n=new Date(e.updatedAt||e.createdAt||0).getTime();return new Date(t.updatedAt||t.createdAt||0).getTime()>n?t:e}),i=qw(r),a=i?.hash||r.transactionHash,o=r.walletAddress||r.cryptoDetails?.destinationWalletAddress||r.cryptoDetails?.sessionWalletAddress,c=r.status===`SETTLED`&&!a&&o;if(s.console.log(`[useMeldTransactionStatus] Checking if need to fetch tx hash`,{status:r.status,hasSettledHash:!!i?.hash,hasTransactionHash:!!r.transactionHash,finalHash:a,walletAddress:o,destinationChainId:r.destinationChainId||r.cryptoDetails?.chainId,needsHashResolution:c,willFetchHistory:c&&!!(r.destinationChainId||r.cryptoDetails?.chainId)}),c&&(r.destinationChainId||r.cryptoDetails?.chainId))try{let e=await ig({chainId:r.destinationChainId||Number(r.cryptoDetails?.chainId),accountAddress:o,pageSize:5,includeMetadata:!0,apiKey:d.trailsApiKey||``,indexerUrl:d.sequenceIndexerUrl||``});if(e.transactions.length>0){for(let t of e.transactions){let e=t.transfers?.find(e=>e.transferType===`RECEIVE`&&Pe(e.to,o));if(e){a=t.txnHash,s.console.log(`[useMeldTransactionStatus] Found matching transaction from deposit address`,{txnHash:t.txnHash,depositAddress:o,tokenAddress:e.contractAddress,amount:e.amounts?.[0]});break}}!a&&e.transactions.length>0&&(a=e.transactions[0]?.txnHash,s.console.log(`[useMeldTransactionStatus] Using most recent transaction to deposit address`,{txnHash:a,depositAddress:r.walletAddress}))}}catch(e){s.console.warn(`[useMeldTransactionStatus] Error fetching transaction history`,e)}return s.console.log(`[useMeldTransactionStatus] Transaction status fetched via search`,{externalSessionId:S,transactionId:r.id,status:r.status,settledHash:i?.hash,settledAmount:i?.amount,finalHash:a,fullTransaction:r}),{...r,transactionHash:a,destinationAmount:i?.amount||r.destinationAmount,walletAddress:o,destinationChainId:r.destinationChainId||r.cryptoDetails?.chainId}}else{let e=await u.getMeldTransaction({transactionId:S}),t;try{t=typeof e.transaction==`string`?JSON.parse(e.transaction):e.transaction}catch(e){throw s.console.error(`[useMeldTransactionStatus] Error parsing transaction:`,e),Error(`Invalid transaction data format`,{cause:e})}if(t?.transaction&&(t=t.transaction),!t)throw Error(`No transaction data found`);return s.console.log(`[useMeldTransactionStatus] Transaction status fetched via getMeldTransaction`,{transactionId:S,status:t.status}),t}}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`404`)||t.includes(`not found`)||t.includes(`status 404`)||t.includes(`request failed with status 404`)||t.includes(`WebrpcEndpoint`)||t.includes(`endpoint error`)||t.includes(`Connection Error`)||t.includes(`Failed to fetch`)||t.includes(`NetworkError`)||e?.status===404||e?.response?.status===404)return s.console.debug(`[useMeldTransactionStatus] Transaction not yet ready, continuing to poll`,{activeId:S,useSearchAPI:C,errorType:t.split(` `)[0]}),{id:S,status:`PENDING`,sourceAmount:void 0,sourceCurrencyCode:void 0,destinationAmount:void 0,destinationCurrencyCode:void 0,walletAddress:void 0,createdAt:void 0,updatedAt:void 0,serviceProvider:void 0,paymentMethod:void 0,transactionHash:void 0,externalSessionId:C?S:void 0,externalCustomerId:void 0};throw s.console.error(`[useMeldTransactionStatus] Error fetching transaction:`,e),e}},enabled:i&&!!S&&l,refetchInterval:e=>{let t=e.state.data?.status;return t===`COMPLETED`||t===`SETTLED`||t===`FAILED`||t===`DECLINED`||t===`CANCELLED`||t===`REFUNDED`||g?!1:3e3},retry:!1,retryDelay:Ee});q(()=>{S&&!f&&a&&l&&p(Date.now())},[S,f,a,l]),q(()=>{if(!(!a||!f))return b.current=setInterval(()=>{h(xe(ke(f)))},Ee),()=>{b.current&&clearInterval(b.current)}},[f,a]),q(()=>{if(v)return x.current=setInterval(()=>{try{v.closed&&!g&&(_(!0),o?.(),s.console.log(`[useMeldTransactionStatus] Popup window closed`))}catch(e){if(e instanceof Error&&e.name===`SecurityError`)return;s.console.warn(`[useMeldTransactionStatus] Error checking window state:`,e)}},1e3),()=>{x.current&&clearInterval(x.current)}},[v,g,o]);let O=w||null,k=O?.status,A=k===`COMPLETED`||k===`SETTLED`||k===`FAILED`||k===`DECLINED`||k===`CANCELLED`||k===`REFUNDED`,j=k===`COMPLETED`||k===`SETTLED`,M=j&&O?.transactionHash||null,N=j&&O?.destinationAmount?.toString()||null,P=k===`FAILED`||k===`DECLINED`||k===`CANCELLED`,F=`idle`;g&&!A?F=`window-closed`:D?F=`error`:j?F=`success`:P?F=`failed`:(S&&l&&E||S&&l)&&(F=`polling`);let I=J(()=>({state:F,message:Jw(F,k,m),timeElapsed:m,transaction:O,error:D}),[F,k,m,O,D]);return q(()=>{c&&c(I)},[c,I]),q(()=>()=>{b.current&&clearInterval(b.current),x.current&&clearInterval(x.current)},[]),{transaction:O,isLoading:E,error:D,isComplete:A,isSuccess:j,isFailed:P,state:F,timeElapsed:m,startTime:f,statusInfo:I,windowClosed:g,settledTransactionHash:M,settledAmount:N,refetch:async()=>{await T()},reset:()=>{p(null),h(0),_(!1),y(null)},resetWindowClosed:()=>{p(null),h(0),_(!1)},setWindowRef:y}}function qw(e){try{if(e?.serviceProviderDetails?.details?.data?.[0]){let t=e.serviceProviderDetails.details.data[0];if(t?.withdraw?.hash&&t?.withdraw?.amount)return{hash:t.withdraw.hash,amount:t.withdraw.amount}}if(e?.cryptoDetails){let t=e.cryptoDetails.transactionHash||e.cryptoDetails.hash,n=e.destinationAmount;if(t)return{hash:t,amount:n?n.toString():void 0}}if(e?.transactionHash&&e?.destinationAmount)return{hash:e.transactionHash,amount:e.destinationAmount.toString()}}catch(e){s.console.warn(`[useMeldTransactionStatus] Error extracting settled details:`,e)}return null}function Jw(e,t,n){switch(e){case`idle`:return`Ready`;case`opening`:return`Payment window opened. Complete your payment to continue...`;case`polling`:return`Checking payment status...`;case`success`:return`Payment completed successfully`;case`failed`:return t===`FAILED`?`Payment failed or transaction not found`:t===`DECLINED`?`Payment was declined`:`Payment failed`;case`window-closed`:return`Payment window was closed`;case`error`:return`Error checking payment status`;default:return t||`Processing...`}}function Yw({sessionId:e,transactionId:t,externalSessionId:n,className:r=``,onStatusChange:i,onWindowClosed:o,showTimeElapsed:s=!0,showPopupOpened:c=!1,isPopupOpen:l=!1,onSetWindowRef:u}){let[d,f]=X(!1),{state:p,statusInfo:m,timeElapsed:h,isLoading:g,setWindowRef:_}=Kw({sessionId:e,transactionId:t,externalSessionId:n,enabled:!!e||!!t||!!n,trackTimeElapsed:s,onStatusChange:i,onWindowClosed:o,popupOpened:l});return q(()=>{u&&u(_)},[u,_]),q(()=>{f(!0)},[]),!d||!e&&!t&&!n&&!c?null:p===`idle`&&c&&l?Q(`div`,{className:`flex items-center gap-3 p-4 rounded-lg border transition-all duration-200 bg-blue-50 border-blue-200 text-blue-800 ${r}`,children:[Z(`div`,{className:`flex-shrink-0`,children:Z(Li,{className:`w-4 h-4 text-blue-600`})}),Q(`div`,{className:`flex-1 min-w-0`,children:[Z(`div`,{className:`flex items-center gap-2`,children:Z(`span`,{className:`text-sm font-medium trails-text-primary`,children:`Payment Window Opened`})}),Z(`p`,{className:`text-xs trails-text-secondary mt-1`,children:`Complete your payment to continue...`})]})]}):p===`idle`?null:Q(`div`,{className:`flex items-center gap-3 p-4 rounded-lg border transition-all duration-200 ${Qw(p)} ${r}`,children:[Z(`div`,{className:`flex-shrink-0`,children:Xw(p,g)}),Q(`div`,{className:`flex-1 min-w-0`,children:[Q(`div`,{className:`flex items-center gap-2`,children:[Z(`span`,{className:`text-sm font-medium trails-text-primary`,children:Zw(p)}),s&&h>0&&p===`polling`&&Q(`div`,{className:`flex items-center gap-1 text-xs trails-text-tertiary`,children:[Z(Mi,{className:`w-3 h-3`}),Z(`span`,{children:Ce(h)})]})]}),Z(`p`,{className:`text-xs trails-text-secondary mt-1`,children:m.message}),p===`success`&&m.transaction&&Z(`div`,{className:`mt-2 flex items-center gap-1.5 text-xs trails-text-tertiary`,children:m.transaction.destinationAmount&&m.transaction.destinationCurrencyCode&&Q(hi,{children:[Z(Jy,{symbol:m.transaction.destinationCurrencyCode?.split(`_`)[0]||m.transaction.destinationCurrencyCode,chainId:m.transaction.destinationChainId,size:14}),Q(`span`,{children:[m.transaction.destinationAmount,` `,m.transaction.destinationCurrencyCode,m.transaction.destinationChainId&&Q(`span`,{className:`text-gray-500`,children:[` `,`on`,` `,Ja(m.transaction.destinationChainId)]}),m.transaction.serviceProvider&&Q(`span`,{className:`ml-1`,children:[` `,`via`,` `,m.transaction.serviceProvider.toUpperCase()]})]})]})}),(p===`error`||p===`failed`)&&Q(`div`,{className:`mt-2 text-xs text-red-600`,children:[m.error?a(m.error):null,m.transaction?.serviceProvider&&Q(`div`,{className:`mt-1`,children:[`Provider: `,m.transaction.serviceProvider]})]})]})]})}function Xw(e,t){switch(e){case`polling`:return Z(Hi,{className:`w-4 h-4 animate-spin text-blue-600`});case`success`:return Z(Ei,{className:`w-4 h-4 text-green-600`});case`failed`:case`error`:return Z(ia,{className:`w-4 h-4 text-red-600`});case`window-closed`:return Z(_i,{className:`w-4 h-4 text-orange-600`});default:return t?Z(Hi,{className:`w-4 h-4 animate-spin text-gray-400`}):Z(Mi,{className:`w-4 h-4 text-gray-400`})}}function Zw(e){switch(e){case`opening`:return`Payment Window Opened`;case`polling`:return`Processing Payment`;case`success`:return`Payment Completed`;case`failed`:return`Payment Failed`;case`error`:return`Connection Error`;case`window-closed`:return`Payment Window Closed`;default:return`Payment Status`}}function Qw(e){switch(e){case`success`:return`bg-green-50 border-green-200 text-green-800`;case`failed`:case`error`:return`bg-red-50 border-red-200 text-red-800`;case`window-closed`:return`bg-orange-50 border-orange-200 text-orange-800`;case`polling`:return`bg-blue-50 border-blue-200 text-blue-800`;case`opening`:return`bg-yellow-50 border-yellow-200 text-yellow-800`;default:return`bg-gray-50 border-gray-200 text-gray-800`}}const $w=[{countryCode:`US`,name:`United States`},{countryCode:`CA`,name:`Canada`},{countryCode:`GB`,name:`United Kingdom`},{countryCode:`EU`,name:`European Union`},{countryCode:`AU`,name:`Australia`}],eT=[{code:`CREDIT_DEBIT_CARD`,label:`Credit Card`,icon:Pi},{code:`DEBIT_CARD`,label:`Debit Card`,icon:Pi},{code:`APPLE_PAY`,label:`Apple Pay`,icon:Xi},{code:`GOOGLE_PAY`,label:`Google Pay`,icon:Xi},{code:`EXCHANGE`,label:`Exchange`,icon:wi}],tT=[{code:`USDC_BASE`,name:`USD Coin`,symbol:`USDC`,chain:`BASE`,chainName:`Base`,chainId:8453,contractAddress:`0x833589fcd6edb6e08f4c7c32d4f71b54bda02913`},{code:`DAI_BASE`,name:`Dai Stablecoin`,symbol:`DAI`,chain:`BASE`,chainName:`Base`,chainId:8453,contractAddress:`0x50c5725949a6f0c72e6c4a641f24049a917db0cb`},{code:`USDC_ETH`,name:`USD Coin`,symbol:`USDC`,chain:`ETH`,chainName:`Ethereum`,chainId:1,contractAddress:`0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`},{code:`ETH`,name:`Ethereum`,symbol:`ETH`,chain:`ETH`,chainName:`Ethereum`,chainId:1,contractAddress:Cn}],nT=[10,25,50,100],rT=`meld-current-session-id`;function iT(e){return e?{ETH:1,BASE:8453,ARBITRUM:42161,OPTIMISM:10,POLYGON:137,BSC:56,AVAX:43114}[e.toUpperCase()]:void 0}const aT=({trailsApiKey:e,onBack:t,onTransactionStatus:n,onNavigateToCountries:r,onNavigateToPaymentMethods:i,onNavigateToTokens:o,onNavigateToProviders:c,onNavigateToHistory:l,onSelectProvider:u,onProvidersLoaded:d,selectedCountry:f,selectedPaymentMethod:p,selectedToken:m,selectedProvider:h})=>{let{address:g}=Kr(),_=Vx(),{data:v=[]}=Xx(),{countryCode:y}=Vw({enabled:!f}),b=J(()=>f||(y?$w.find(e=>e.countryCode===y)||{countryCode:y,name:Ew(y,v)}:$w[0]||{countryCode:`US`,name:`United States`}),[f,y,v]),x=p||`CREDIT_DEBIT_CARD`,[S,C]=X(()=>localStorage.getItem(`meld-form-amount`)||`25`),[w]=X(`USD`),T=J(()=>Fw(e,_?.trailsApiUrl),[e,_?.trailsApiUrl]),{data:E=[]}=Or(PS.paymentMethodList(T,w)),D=J(()=>!x||!E.length?null:E.find(e=>e.paymentMethod===x),[x,E]),O=m||tT[0]||{code:`USDC_BASE`,name:`USD Coin`,symbol:`USDC`,chain:`BASE`,chainName:`Base`},[k,A]=X([]),j=h,[M,N]=X(!1),[P,F]=X(``),[I,ee]=X(!1),[te,ne]=X(null),[re,ie]=X(!1),[L,R]=X(null),[ae,z]=X(null),[B,V]=X(null),[oe,H]=X(null),[se,ce]=X(!1),[U,le]=X(null),ue=Y(n);q(()=>{ue.current=n},[n]);let de=e=>{let t={type:e.state===`success`?`success`:e.state===`failed`||e.state===`error`?`error`:e.state===`polling`?`pending`:null,message:e.message};ue.current?.(t)},fe=()=>{s.console.log(`[MeldForm] Popup window was closed`),z(null),ie(!1),ce(!1)};q(()=>{let e=new URLSearchParams(window.location.search),t=e.get(`sessionId`)||e.get(`externalSessionId`)||e.get(`orderId`);t&&!L&&(s.console.log(`[MeldForm] Found session ID in URL parameters:`,t),R(t),V(t),localStorage.setItem(rT,t))},[L]);let pe=K(async()=>{if(!b||!O||!S){s.console.log(`[MeldForm] Missing required parameters for loadProviders:`,{selectedCountry:b,selectedToken:O,amount:S});return}s.console.log(`[MeldForm] Loading providers with params:`,{walletAddress:g||`fallback`,countryCode:b.countryCode,sourceCurrencyCode:w,sourceAmount:S,destinationCurrencyCode:O.code,paymentMethodType:x}),N(!0),A([]),F(``),ie(!1);try{let e=await T.getMeldQuote({walletAddress:g||`0x1234567890123456789012345678901234567890`,countryCode:b.countryCode,sourceCurrencyCode:w,sourceAmount:S,destinationCurrencyCode:O.code});s.console.log(`[MeldForm] Quote response:`,e);let t;try{t=e.QuoteResponse?.quotes||(typeof e.quoteResponse==`string`?JSON.parse(e.quoteResponse):e.quoteResponse)?.quotes}catch(e){s.console.error(`[MeldForm] Error parsing quote response:`,e),N(!1);return}if(s.console.log(`[MeldForm] Extracted quotes:`,t),!t||t.length===0){s.console.log(`[MeldForm] No quotes available`),N(!1);return}A(t),s.console.log(`[MeldForm] Set providers:`,t.length,`quotes`)}catch(e){s.console.error(`[MeldForm] Error loading providers:`,e)}finally{N(!1)}},[b,O,S,w,x,T,g]),me=K(async()=>{if(!(!j||!g)){ee(!0),ne(null);try{let e=`meld-${Date.now()}-${Math.random().toString(36).substring(2,8)}`,t=St(g),n=(await T.createMeldWidgetSession({sessionData:{walletAddress:g,countryCode:b.countryCode,sourceCurrencyCode:w,sourceAmount:S,destinationCurrencyCode:O.code,serviceProvider:j.serviceProvider,paymentMethodType:x||void 0},sessionType:`BUY`,externalCustomerId:t,externalSessionId:e})).WidgetSession;if(!n)throw Error(`No widget session data received`);let{selectedWidgetUrl:r,isTransakProvider:i,meldWidgetUrl:a,serviceProviderWidgetUrl:o}=Bw({serviceProvider:j.serviceProvider,widgetUrl:n.widgetUrl,serviceProviderWidgetUrl:n.serviceProviderWidgetUrl,fallbackUrl:n.url});if(s.console.log(`[MeldForm] Selected widget URL`,{isTransakProvider:i,widgetUrl:a,serviceProviderWidgetUrl:o,selectedWidgetUrl:r}),!r)throw Error(`No widget URL found in session data`);F(r);let c=n.sessionId||n.id||e,l=n.externalSessionId||e;s.console.log(`[MeldForm] Session data from response:`,{sessionId:c,externalSessionId:l,generatedExternalSessionId:e}),V(c),H(l),R(c),localStorage.setItem(rT,c),localStorage.setItem(`meld-current-external-session-id`,l)}catch(e){s.console.error(`Error creating widget session:`,e);let t=a(e);ne(t)}finally{ee(!1)}}},[j,g,b,w,S,O,x,T]);return q(()=>{pe(),ne(null)},[pe]),q(()=>{k.length>0&&(d?.(k),!j&&u&&k[0]&&(s.console.log(`[MeldForm] Auto-selecting first provider:`,k[0]),u(k[0])))},[k,j,d,u]),q(()=>{j&&me()},[j,me]),Q(`div`,{className:`max-w-md mx-auto p-6 space-y-4`,children:[Z(M_,{onBack:t,headerContent:`Buy Crypto`,rightSideContent:Q(`div`,{className:`flex items-center gap-2`,children:[l&&Z(`button`,{type:`button`,onClick:l,className:`flex items-center justify-center w-8 h-8 bg-transparent border border-gray-300 dark:border-gray-600 rounded-lg trails-text-primary hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors cursor-pointer`,title:`Onramp History`,children:Z(zi,{className:`w-4 h-4`})}),Q(`button`,{type:`button`,onClick:r,className:`flex items-center gap-2 bg-transparent border border-gray-300 dark:border-gray-600 rounded-lg px-2 py-1 text-sm trails-text-primary hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors cursor-pointer`,children:[Z(`span`,{className:`text-base`,children:Dw(b.countryCode,v)}),Z(`span`,{className:`font-medium`,children:b.countryCode}),Z(Di,{className:`w-4 h-4 text-gray-500`})]})]})}),Q(`div`,{children:[Z(`span`,{className:`block text-sm font-medium trails-text-primary mb-2`,children:`Payment Method`}),Q(`button`,{type:`button`,onClick:i,className:`w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-3 trails-text-primary bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors cursor-pointer flex items-center justify-between`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[D?.logos?.light||D?.logos?.dark?Z(`div`,{className:`w-8 h-8 rounded-lg flex items-center justify-center bg-gray-100 dark:bg-gray-700 p-1`,children:Z(`img`,{src:D.logos?.light||D.logos?.dark||``,alt:`${D.name} logo`,className:`max-w-full max-h-full object-cover`})}):Z(Pi,{className:`w-5 h-5 text-gray-500`}),Q(`div`,{className:`text-left`,children:[Z(`div`,{className:`font-medium`,children:D?.name||eT.find(e=>e.code===x)?.label||x||`Select Payment Method`}),D?.paymentType&&Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:D.paymentType})]})]}),Z(Di,{className:`w-5 h-5 text-gray-500`})]})]}),Q(`div`,{children:[Z(`label`,{htmlFor:`meld-amount-input`,className:`block text-sm font-medium trails-text-primary mb-2`,children:`Amount`}),Q(`div`,{className:`space-y-3`,children:[Q(`div`,{className:`relative`,children:[Z(Ii,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-500`}),Z(`input`,{id:`meld-amount-input`,type:`number`,value:S,onChange:e=>{let t=e.target.value;C(t),t&&localStorage.setItem(`meld-form-amount`,t)},placeholder:`Enter amount`,className:`w-full border border-gray-300 dark:border-gray-600 rounded-lg pl-10 pr-3 py-3 trails-text-primary bg-white dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500`})]}),Z(`div`,{className:`flex gap-2`,children:nT.map(e=>Q(`button`,{type:`button`,onClick:()=>{let t=e.toString();C(t),localStorage.setItem(`meld-form-amount`,t)},className:`px-3 py-1 text-sm rounded-md border transition-colors ${S===e.toString()?`bg-blue-100 border-blue-500 text-blue-700 dark:bg-blue-900/30 dark:border-blue-400 dark:text-blue-300`:`border-gray-300 dark:border-gray-600 trails-text-secondary hover:bg-gray-50 dark:hover:bg-gray-800`}`,children:[`$`,e]},e))})]})]}),Q(`div`,{children:[Z(`span`,{className:`block text-sm font-medium trails-text-primary mb-2`,children:`Token`}),Q(`button`,{type:`button`,onClick:o,className:`w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-3 trails-text-primary bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors cursor-pointer flex items-center justify-between`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(Jy,{symbol:O.symbol,chainId:O.chainId||iT(O.chain),contractAddress:O.contractAddress,size:24}),Q(`div`,{className:`text-left`,children:[Z(`div`,{className:`font-medium`,children:O.symbol}),Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:O.chainName})]})]}),Z(Di,{className:`w-5 h-5 text-gray-500`})]})]}),Q(`div`,{children:[Z(`span`,{className:`block text-sm font-medium trails-text-primary mb-2`,children:`Provider`}),M?Q(`div`,{className:`border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-3 flex items-center`,children:[Z(`div`,{className:`animate-spin rounded-full h-4 w-4 border-b-2 border-blue-500 mr-2`}),Z(`span`,{className:`text-gray-600 dark:text-gray-400`,children:`Loading providers...`})]}):k.length===0?Z(`div`,{className:`border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-3 text-gray-600 dark:text-gray-400`,children:`No providers available`}):Q(`button`,{type:`button`,onClick:c,className:`w-full border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-3 trails-text-primary bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors cursor-pointer flex items-center justify-between`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(wi,{className:`w-5 h-5 text-gray-500`}),Z(`span`,{children:j?`${j.serviceProvider} - $${j.totalFee.toFixed(2)} fee`:`Select Provider`})]}),Z(Di,{className:`w-5 h-5 text-gray-500`})]})]}),te&&Z(XC,{error:te,severity:`error`}),Z(`button`,{type:`button`,onClick:()=>{if(P&&!re){ie(!0);let e=window.open(P,`_blank`,Hw(800,600));if(!e){s.console.error(`[MeldForm] Popup blocked by browser`),ie(!1);return}z(e),ce(!0),U&&U(e),s.console.log(`[MeldForm] Payment window opened, session ID:`,B)}},disabled:I||!P||re||!j||!!te,className:`w-full flex items-center justify-center py-3 px-4 font-semibold rounded-lg transition-colors ${I||!P||re||!j||te?`bg-gray-400 text-gray-200 cursor-not-allowed`:`bg-blue-600 hover:bg-blue-700 text-white cursor-pointer`}`,children:I?Q(hi,{children:[Z(`div`,{className:`animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2`}),Z(`span`,{children:`Preparing...`})]}):Q(hi,{children:[Z(`span`,{children:re?`Provider Opened`:`Continue to Provider`}),Z(Li,{className:`w-4 h-4 ml-2`})]})}),Z(Yw,{sessionId:B,transactionId:L,externalSessionId:oe,onStatusChange:de,onWindowClosed:fe,showTimeElapsed:!0,showPopupOpened:re,isPopupOpen:se,onSetWindowRef:le})]})},oT=`meld-form-amount`,sT=`meld-debug-currency`,cT=({onBack:e,onContinue:t,_selectedCountry:n,_selectedToken:r,_selectedPaymentMethod:i,initialAmount:a=``,initialCurrency:o=`USD`})=>{let[s,c]=X(a),[l,u]=X(o),d=parseFloat(s),f=s.trim()!==``&&vs(d)&&d<=1e4;return q(()=>{s&&localStorage.setItem(oT,s),l&&localStorage.setItem(sT,l)},[s,l]),Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:()=>e(s,l),headerContent:`Enter Amount`}),Z(`div`,{className:`flex-1 p-4`,children:Q(`div`,{className:`max-w-md mx-auto`,children:[Z(`label`,{htmlFor:`meld-steps-amount`,className:`block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2`,children:`How much do you want to spend?`}),Q(`div`,{className:`relative`,children:[Q(`select`,{value:l,onChange:e=>u(e.target.value),className:`absolute left-3 top-1/2 transform -translate-y-1/2 bg-transparent border-none text-lg font-semibold text-gray-700 dark:text-gray-300 focus:outline-none`,children:[Z(`option`,{value:`USD`,children:`$`}),Z(`option`,{value:`EUR`,children:`€`}),Z(`option`,{value:`GBP`,children:`£`})]}),Z(`input`,{id:`meld-steps-amount`,type:`number`,value:s,onChange:e=>c(e.target.value),placeholder:`0.00`,className:`w-full pl-12 pr-4 py-3 text-2xl font-semibold border-2 border-gray-200 dark:border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-white`,min:`1`,max:`10000`,step:`0.01`})]}),Z(`div`,{className:`mt-4 grid grid-cols-4 gap-2`,children:[`25`,`50`,`100`,`500`].map(e=>Q(`button`,{type:`button`,onClick:()=>c(e),className:`py-2 px-3 text-sm text-black dark:text-white border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer`,children:[l===`USD`?`$`:l===`EUR`?`€`:`£`,e]},e))}),s&&!f&&Z(`div`,{className:`mt-2 text-sm text-red-600 dark:text-red-400`,children:`Please enter a valid amount between $1 and $10,000`})]})}),Z(`div`,{className:`p-4 border-t border-gray-200 dark:border-gray-700`,children:Z(`button`,{type:`button`,onClick:()=>t(s,l),disabled:!f,className:`w-full py-3 px-4 rounded-lg font-semibold transition-colors ${f?`bg-blue-600 hover:bg-blue-700 text-white cursor-pointer`:`bg-gray-300 dark:bg-gray-600 text-gray-500 dark:text-gray-400 cursor-not-allowed`}`,children:`Continue to Providers`})})]})},lT=({onBack:e})=>{let t=Vx(),{navigate:n,goHome:r}=y_(),{setSelectedToken:i}=ul(),{filteredTokens:a}=Cy({onContinue:()=>{},onError:()=>{}}),{address:o}=Kr(),c=J(()=>Fw(t.trailsApiKey,t.trailsApiUrl),[t.trailsApiKey,t.trailsApiUrl]),[l,u]=X(`menu`);q(()=>{let e=localStorage.getItem(oT),t=localStorage.getItem(sT);e&&v(e),t&&b(t)},[]);let[d,f]=X(()=>{try{let e=localStorage.getItem(`meld-debug-country`);return e?JSON.parse(e):null}catch{return null}}),[p,m]=X(()=>{try{return localStorage.getItem(`meld-debug-payment-method`)||null}catch{return null}}),[h,g]=X(()=>{try{let e=localStorage.getItem(`meld-debug-token`);return e?JSON.parse(e):null}catch{return null}}),[_,v]=X(``),[y,b]=X(`USD`),[x,S]=X(``),[C,w]=X(!1),[T,E]=X(``),[D,O]=X([]),[k,A]=X(!1),[j,M]=X(null),[N,P]=X(!1),[F,I]=X(null),[ee,te]=X({status:``,message:``,type:null});q(()=>{let e=new URLSearchParams(window.location.search);s.console.log(`[MeldStepsFlow] All URL parameters:`,Object.fromEntries(e.entries()));let t=e.get(`orderId`)||e.get(`partnerOrderId`)||e.get(`transactionId`)||e.get(`meld_transaction_id`)||e.get(`transaction_id`)||e.get(`id`),n=e.get(`status`)||e.get(`meld_status`)||e.get(`transaction_status`)||e.get(`state`),r=e.get(`fiatAmount`),i=e.get(`cryptoAmount`),a=e.get(`fiatCurrency`),o=e.get(`cryptoCurrency`),l=e.get(`totalFeeInFiat`),u=e.get(`walletAddress`),d=e.get(`network`);s.console.log(`[MeldStepsFlow] Meld transaction details:`,{transactionId:t,status:n,fiatAmount:r,cryptoAmount:i,fiatCurrency:a,cryptoCurrency:o,totalFee:l,walletAddress:u,network:d}),s.console.log(`[MeldStepsFlow] Extracted transaction ID:`,t),s.console.log(`[MeldStepsFlow] Extracted status:`,n);let f=t;if(f||(s.console.log(`[MeldStepsFlow] No transaction ID in URL, will search by wallet address:`,u),u?(s.console.log(`[MeldStepsFlow] Searching for transactions by wallet address (external customer ID):`,u),setTimeout(async()=>{try{let e=localStorage.getItem(`meld-current-customer-id-for-search`);s.console.log(`[MeldStepsFlow] About to call searchMeldTransactions with params:`,{customerIds:e,fallbackCustomerIds:u,limit:10});let t=e?{customerIds:e,limit:10}:{customerIds:u,limit:10},n=await c.searchMeldTransactions(t);s.console.log(`[MeldStepsFlow] Also searching for any recent transactions...`);let r=await c.searchMeldTransactions({limit:5});s.console.log(`[MeldStepsFlow] All recent transactions:`,r),s.console.log(`[MeldStepsFlow] Search response:`,n);let i;try{i=typeof n.transactions==`string`?JSON.parse(n.transactions):n.transactions}catch(e){s.console.error(`[MeldStepsFlow] Error parsing search response:`,e);return}if(i?.transactions&&i.transactions.length>0){let e=i.transactions[0];s.console.log(`[MeldStepsFlow] Found transaction from search:`,e);let t=e.id||e.transactionId;s.console.log(`[MeldStepsFlow] Setting currentTransactionId for polling:`,t),I(t);let n=`pending`,r=`Payment is being processed...`;switch((e.status||``).toLowerCase()){case`settled`:{n=`success`;let t=e.destinationAmount||``,i=e.destinationCurrencyCode||``,a=e.destinationChainId||e.networkId,o=e.serviceProvider||`provider`,s=a?Ja(Number(a)):``;r=`Payment completed! ${t&&i?`${t} ${i}${s?` on ${s}`:``} via ${o.toUpperCase()}`:`crypto`} purchased${e.walletAddress?` to ${wt(e.walletAddress,6,4)}`:``}`;break}case`failed`:n=`error`,r=`Payment failed. Please try again with a different payment method.`;break;case`declined`:n=`error`,r=`Payment declined by your bank. Please check your payment method or try a different card.`;break;case`cancelled`:n=`error`,r=`Payment was cancelled. You can start a new transaction.`;break;case`refunded`:n=`error`,r=`Payment was refunded. Crypto could not be delivered.`;break;case`pending_created`:case`pending created`:n=`pending`,r=`Transaction created. Waiting for provider processing...`;break;case`pending`:n=`pending`,r=`Payment submitted for review and verification...`;break;case`settling`:n=`pending`,r=`Payment approved! Crypto transfer in progress...`;break;case`two_fa_required`:case`2fa_required`:n=`pending`,r=`Please complete 2FA verification to continue...`;break;case`two_fa_provided`:case`2fa_provided`:n=`pending`,r=`2FA submitted. Validating with card issuer...`;break;case`error`:n=`pending`,r=`Processing error. Retrying automatically...`;break;case`accepted`:case`authorized`:case`partially_settled`:case`completed`:case`success`:case`processing`:n=`pending`,r=`Payment is being processed...`;break;case`authorization_expired`:n=`error`,r=`Payment authorization expired. Please try again.`;break;default:n=`pending`;break}if(n===`pending`&&!r.includes(`Transaction created`)&&!r.includes(`Payment submitted`)&&!r.includes(`Payment approved`)&&!r.includes(`complete 2FA`)&&!r.includes(`2FA submitted`)&&!r.includes(`Processing error`)){let t=e.destinationAmount||``,n=e.destinationCurrencyCode||``,i=e.destinationChainId||e.networkId,a=e.serviceProvider||`provider`,o=i?Ja(Number(i)):``;r=`${t&&n?`${t} ${n}${o?` on ${o}`:``} via ${a.toUpperCase()}`:`payment`} is being processed...`}te({status:e.status||`PROCESSING`,message:r,type:n}),s.console.log(`[MeldStepsFlow] Set transaction status from search:`,{status:e.status,type:n,message:r})}else s.console.log(`[MeldStepsFlow] No transactions found for wallet address:`,u),s.console.log(`[MeldStepsFlow] Search result shows no transactions, this is normal for first-time users`)}catch(e){s.console.error(`[MeldStepsFlow] Error searching for transactions:`,e)}},100)):s.console.log(`[MeldStepsFlow] No wallet address available for transaction search`)),f){if(s.console.log(`[MeldStepsFlow] Setting transaction ID for tracking from URL:`,f),I(f),n){let e=(n||``).toLowerCase(),t=`pending`;switch(e){case`settled`:t=`success`;break;case`failed`:case`declined`:case`cancelled`:case`refunded`:case`authorization_expired`:t=`error`;break;case`pending_created`:case`pending created`:case`pending`:case`settling`:case`two_fa_required`:case`2fa_required`:case`two_fa_provided`:case`2fa_provided`:case`error`:case`accepted`:case`authorized`:case`partially_settled`:case`completed`:case`success`:case`processing`:t=`pending`;break;default:t=`pending`;break}let c=`Payment is being processed...`;if(t===`success`){let e=i||``,t=o||``,n=d||``;c=`Payment completed! ${e&&t?`${e} ${t}${n?` on ${n}`:``} via MELD`:`crypto`} purchased${u?` to ${wt(u,6,4)}`:``}`}else if(t===`error`)c=`Payment failed or was cancelled.`;else{let e=i||r||``,t=o||``,n=d||``;c=e&&t?`${`${e} ${t}${n?` on ${n}`:``} via MELD`} is being processed...`:`${r&&a?`${a} ${r}`:`payment`} is being processed...`}te({status:n,message:c,type:t}),s.console.log(`[MeldStepsFlow] Set initial transaction status:`,{status:n,type:t,message:c})}let e=new URL(window.location.href);for(let t of[`transactionId`,`meld_transaction_id`,`transaction_id`,`id`,`sessionId`,`session_id`,`status`,`meld_status`,`transaction_status`,`state`,`orderId`,`partnerOrderId`,`partnerCustomerId`,`fiatAmount`,`cryptoAmount`,`fiatCurrency`,`cryptoCurrency`,`totalFeeInFiat`,`walletAddress`,`network`,`isBuyOrSell`,`isNFTOrder`])e.searchParams.delete(t);window.history.replaceState(null,``,e.toString())}else s.console.log(`[MeldStepsFlow] No transaction ID found in URL parameters`)},[c]);let ne=K(async e=>{if(!e||e.trim()===``||e===`null`||e===`undefined`){s.console.warn(`[MeldStepsFlow] Invalid transaction ID, skipping API call:`,e);return}try{s.console.log(`[MeldStepsFlow] Checking transaction status for ID:`,e),s.console.log(`[MeldStepsFlow] Making API call to getMeldTransaction...`);let t=await c.getMeldTransaction({transactionId:e});s.console.log(`[MeldStepsFlow] Raw API response:`,t),s.console.log(`[MeldStepsFlow] Response type:`,typeof t),s.console.log(`[MeldStepsFlow] Response keys:`,Object.keys(t||{})),s.console.log(`[MeldStepsFlow] Transaction data:`,t?.transaction),s.console.log(`[MeldStepsFlow] Transaction data type:`,typeof t?.transaction);let n;try{n=typeof t.transaction==`string`?JSON.parse(t.transaction):t.transaction}catch(e){s.console.error(`[MeldStepsFlow] Error parsing transaction data:`,e);return}if(n?.transaction&&(n=n.transaction),!n){s.console.warn(`[MeldStepsFlow] No transaction data in response`);return}let r=`pending`,i=`Payment is being processed...`;switch(s.console.log(`[MeldStepsFlow] Transaction status:`,n.status),(n.status||``).toLowerCase()){case`settled`:{r=`success`;let e=n.walletAddress||n.destinationWalletAddress||n.cryptoDetails?.destinationWalletAddress||n.cryptoDetails?.sessionWalletAddress||``,t=e&&typeof e==`string`?` sent to ${wt(e)}`:``,a=n.destinationAmount||n.cryptoDetails?.destinationAmount||``,o=n.destinationCurrencyCode||``,s=n.destinationChainId||n.networkId,c=n.serviceProvider||`MELD`,l=s?Ja(Number(s)):``;i=`Payment completed! ${a&&o?`${a} ${o}${l?` on ${l}`:``} via ${c.toUpperCase()}`:`crypto`} purchased${t}`;break}case`failed`:r=`error`,i=`Payment failed. Please try again with a different payment method.`;break;case`declined`:r=`error`,i=`Payment declined by your bank. Please check your payment method or try a different card.`;break;case`cancelled`:r=`error`,i=`Payment was cancelled. You can start a new transaction.`;break;case`refunded`:r=`error`,i=`Payment was refunded. Crypto could not be delivered.`;break;case`pending_created`:case`pending created`:r=`pending`,i=`Transaction created. Waiting for provider processing...`;break;case`pending`:r=`pending`,i=`Payment submitted for review and verification...`;break;case`settling`:r=`pending`,i=`Payment approved! Crypto transfer in progress...`;break;case`two_fa_required`:case`2fa_required`:r=`pending`,i=`Please complete 2FA verification to continue...`;break;case`two_fa_provided`:case`2fa_provided`:r=`pending`,i=`2FA submitted. Validating with card issuer...`;break;case`error`:r=`pending`,i=`Processing error. Retrying automatically...`;break;case`accepted`:case`authorized`:case`partially_settled`:r=`pending`,i=`Payment is being processed...`;break;case`authorization_expired`:r=`error`,i=`Payment authorization expired. Please try again.`;break;case`processing`:case`completed`:case`success`:r=`pending`,i=`Payment is being processed...`;break;default:r=`pending`,i=`Payment status: ${n.status||`Processing...`}`}return s.console.log(`[MeldStepsFlow] Setting transaction status:`,{status:n.status,message:i,type:r}),te({status:n.status,message:i,type:r}),n}catch(t){s.console.error(`[MeldStepsFlow] Error checking transaction status:`,t);let n=`Unable to check payment status.`;t instanceof Error&&(n=`Error: ${t.message}`,t.message.includes(`404`)||t.message.includes(`not found`)?n=`Transaction not found. ID: ${e}`:t.message.includes(`401`)||t.message.includes(`Unauthorized`)?n=`Not authorized to access transaction data.`:t.message.includes(`timeout`)&&(n=`Request timed out. Please try again.`)),te({status:`error`,message:n,type:`error`})}},[c]),re=K(async()=>{if(!j||!d||!h||!_){S(``),E(`Please select all required options`);return}if(!o){S(``),E(`Please connect your wallet first`);return}w(!0),E(``);try{let e=`meld-${Date.now()}-${Math.random().toString(36).substring(7)}`;s.console.log(`[MeldStepsFlow] Generated external session ID:`,e),localStorage.setItem(`meld-current-external-session-id`,e),s.console.log(`[MeldStepsFlow] Stored external session ID in localStorage`),window.location.origin+window.location.pathname,s.console.log(`[MeldStepsFlow] Creating widget session with:`,{countryCode:d.countryCode,destinationCurrencyCode:h.code,serviceProvider:j.serviceProvider,paymentMethodType:p,externalSessionId:e,walletAddress:o});let t=St(o),n=await c.createMeldWidgetSession({sessionData:{walletAddress:o,countryCode:d.countryCode,sourceCurrencyCode:y,sourceAmount:_,destinationCurrencyCode:h.code,serviceProvider:j.serviceProvider,paymentMethodType:p||void 0},sessionType:`BUY`,externalCustomerId:t,externalSessionId:e});s.console.log(`[MeldStepsFlow] Session response:`,n);let r=n.WidgetSession||n.widgetSession;if(!r){s.console.error(`[MeldStepsFlow] No WidgetSession found in response. Keys:`,Object.keys(n)),S(`Error: No widget session data returned from API`),w(!1);return}s.console.log(`[MeldStepsFlow] Widget session data:`,r);let i=r.customerId;i&&(s.console.log(`[MeldStepsFlow] Storing customer ID for search:`,i),localStorage.setItem(`meld-current-customer-id-for-search`,i));let{selectedWidgetUrl:a,isTransakProvider:l,meldWidgetUrl:u,serviceProviderWidgetUrl:f}=Bw({serviceProvider:j.serviceProvider,widgetUrl:r.widgetUrl,serviceProviderWidgetUrl:r.serviceProviderWidgetUrl,fallbackUrl:r.url||(typeof r==`string`?r:null)});if(s.console.log(`[MeldStepsFlow] Selected widget URL`,{isTransakProvider:l,widgetUrl:u,serviceProviderWidgetUrl:f,selectedWidgetUrl:a}),!a){s.console.error(`[MeldStepsFlow] No widget URL found in session data. Keys:`,Object.keys(r)),S(`Error: No widget URL found in session data`),w(!1);return}s.console.log(`[MeldStepsFlow] Widget URL:`,a),S(a),E(``)}catch(e){s.console.error(`[MeldStepsFlow] Error generating widget URL:`,e),S(``);let t=e instanceof Error?e.message:String(e);t.includes(`Invalid Customer`)?t=`Payment provider issue: ${j?.serviceProvider||`Unknown provider`} is currently unavailable. Please try again later or contact support.`:t.includes(`BAD_REQUEST`)&&(t=`Invalid request parameters. Please check your selection and try again.`),E(t)}finally{w(!1)}},[j,d,h,_,y,p,o,c]);K(async()=>{await re(),x&&!x.startsWith(`Error`)&&!x.startsWith(`Please`)&&!x.startsWith(`No`)&&window.open(x,`_blank`)},[x,re]),K(()=>{if(!h)return;let e=a.find(e=>e.symbol.toUpperCase()===h.symbol.toUpperCase()&&e.chainId===h.chainId);e&&(i(e),r())},[h,a,i,r]),q(()=>{if(s.console.log(`[MeldStepsFlow] Polling useEffect triggered:`,{currentTransactionId:F,transactionStatusType:ee.type,shouldReturn:!F||ee.type===`success`||ee.type===`error`}),F&&s.console.log(`[MeldStepsFlow] Will poll getMeldTransaction API with transaction ID:`,F),!F||ee.type===`success`||ee.type===`error`){s.console.log(`[MeldStepsFlow] Polling useEffect: Not starting poll, conditions not met`);return}s.console.log(`[MeldStepsFlow] Starting transaction polling for ID:`,F);let e=setInterval(()=>{s.console.log(`[MeldStepsFlow] Interval check for transaction:`,F),ne(F)},10*Ee);return s.console.log(`[MeldStepsFlow] Initial transaction status check for:`,F),ne(F),()=>clearInterval(e)},[F,ee.type,ne]),q(()=>{d&&localStorage.setItem(`meld-debug-country`,JSON.stringify(d))},[d]),q(()=>{p&&localStorage.setItem(`meld-debug-payment-method`,p)},[p]),q(()=>{h&&localStorage.setItem(`meld-debug-token`,JSON.stringify(h))},[h]);let ie=K(async()=>{if(!(!d||!h||!_)){A(!0),O([]);try{let e=await c.getMeldQuote({walletAddress:`0x1234567890123456789012345678901234567890`,countryCode:d.countryCode,sourceCurrencyCode:y,sourceAmount:_,destinationCurrencyCode:h.code});s.console.log(`[MeldStepsFlow] Quote response:`,e);let t;try{t=typeof e.quoteResponse==`string`?JSON.parse(e.quoteResponse):e.quoteResponse}catch(e){s.console.error(`[MeldStepsFlow] Error parsing quote response:`,e),A(!1);return}s.console.log(`[MeldStepsFlow] Parsed quote response:`,t);let n=t?.quotes;if(!n||n.length===0){S(`No quotes available for this selection`),w(!1);return}O(n),n.length>0&&M(n[0]),A(!1)}catch(e){s.console.error(`Error loading providers:`,e),A(!1)}}},[d,h,_,y,c]);q(()=>{l===`providers`&&D.length===0&&ie()},[l,ie,D.length]);let L=()=>{u(`menu`)};return q(()=>{d&&h&&_&&ie()},[d,h,_,ie]),q(()=>{j&&d&&h&&_&&re()},[j,d,h,_,re]),l===`countries`?Z(Aw,{onBack:L,onSelectCountry:e=>{f(e),O([]),M(null),P(!1),S(``),E(``),u(`menu`)},selectedCountry:d}):l===`payment-methods`?Z(jw,{onBack:L,onSelectPaymentMethod:e=>{m(e),O([]),M(null),P(!1),S(``),E(``),u(`menu`)},selectedPaymentMethod:p,trailsClient:c,onNavigateToFund:()=>{n(`fund-form`)}}):l===`tokens`?Z(Lw,{onBack:L,onSelectToken:e=>{g(e),O([]),M(null),P(!1),S(``),E(``),u(`menu`)},selectedToken:h,trailsClient:c,countryCode:d?.countryCode}):l===`amount`?Z(cT,{onBack:(e,t)=>{e&&(v(e),localStorage.setItem(oT,e)),t&&(b(t),localStorage.setItem(sT,t)),u(`menu`)},onContinue:(e,t)=>{v(e),b(t),O([]),M(null),P(!1),S(``),E(``),u(`providers`)},_selectedCountry:d,_selectedToken:h,_selectedPaymentMethod:p,initialAmount:_,initialCurrency:y}):l===`providers`?Q(`div`,{className:`flex flex-col h-full`,children:[ee.type&&N&&Z(`div`,{className:`p-4 border-b ${ee.type===`success`?`bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-700`:ee.type===`error`?`bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-700`:`bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-700`}`,children:Q(`div`,{className:`flex items-center gap-3`,children:[ee.type===`success`&&Z(`div`,{className:`w-5 h-5 rounded-full bg-green-500 flex items-center justify-center`,children:Z(`span`,{className:`text-white text-xs`,children:`✓`})}),ee.type===`error`&&Z(`div`,{className:`w-5 h-5 rounded-full bg-red-500 flex items-center justify-center`,children:Z(`span`,{className:`text-white text-xs`,children:`✕`})}),ee.type===`pending`&&Z(`div`,{className:`animate-spin rounded-full h-5 w-5 border-b-2 border-blue-500`}),Q(`div`,{children:[Z(`p`,{className:`font-medium ${ee.type===`success`?`text-green-800 dark:text-green-200`:ee.type===`error`?`text-red-800 dark:text-red-200`:`text-blue-800 dark:text-blue-200`}`,children:ee.message}),ee.type===`pending`&&Z(`p`,{className:`text-sm text-blue-600 dark:text-blue-400`,children:`We'll update you when the payment completes.`})]}),(ee.type===`success`||ee.type===`error`)&&Z(`button`,{type:`button`,onClick:()=>te({status:``,message:``,type:null}),className:`ml-auto text-gray-400 hover:text-gray-600 dark:hover:text-gray-300`,children:`✕`})]})}),Z(`div`,{className:`flex-1`,children:Z(Nw,{onBack:()=>{P(!1),u(`menu`)},onSelectProvider:e=>{M(e),P(!1),S(``),E(``),u(`menu`)},selectedProvider:j,providers:D})}),j&&Q(`div`,{className:`p-4 border-t border-gray-200 dark:border-gray-700 space-y-3`,children:[T&&Z(`div`,{className:`p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 rounded-lg`,children:Q(`p`,{className:`text-sm text-red-800 dark:text-red-200`,children:[Z(`strong`,{children:`Error:`}),` `,T]})}),Z(`button`,{type:`button`,onClick:()=>{if(x&&!N){if(!window.open(x,`_blank`,`width=800,height=600,scrollbars=yes,resizable=yes`)){s.console.error(`[MeldStepsFlow] Popup blocked by browser`),E(`Popup blocked. Please allow popups for this site.`);return}if(P(!0),o){s.console.log(`[MeldStepsFlow] Starting transaction search after widget opened`);let e=setInterval(async()=>{try{let t=localStorage.getItem(`meld-current-customer-id-for-search`),n=t?{customerIds:t,limit:5}:{customerIds:o,limit:5};s.console.log(`[MeldStepsFlow] Polling search with params:`,n);let r=await c.searchMeldTransactions(n),i;try{i=typeof r.transactions==`string`?JSON.parse(r.transactions):r.transactions}catch(e){s.console.error(`[MeldStepsFlow] Error parsing search response:`,e);return}if(i?.transactions&&i.transactions.length>0){let t=i.transactions[0],n=t.id||t.transactionId;n&&n!==F&&(s.console.log(`[MeldStepsFlow] Found new transaction:`,n),I(n),clearInterval(e))}}catch(e){s.console.error(`[MeldStepsFlow] Search polling error:`,e)}},5*1e3);setTimeout(()=>{clearInterval(e),s.console.log(`[MeldStepsFlow] Stopped transaction search polling`)},10*6e4)}}},disabled:C||!x||!!T||N,className:`w-full flex items-center justify-center py-3 px-4 font-semibold rounded-lg transition-colors ${C||!x||T||N?`bg-gray-400 text-gray-200 cursor-not-allowed`:`bg-blue-600 hover:bg-blue-700 text-white cursor-pointer`}`,children:C?Q(hi,{children:[Z(`div`,{className:`animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2`}),Z(`span`,{children:`Preparing Widget...`})]}):Q(hi,{children:[Z(`span`,{children:N?`Provider Opened`:`Continue to Provider`}),Z(Li,{className:`w-4 h-4 ml-2`})]})})]})]}):Z(`div`,{className:`flex flex-col h-full`,children:Z(aT,{trailsApiKey:t.trailsApiKey,onBack:e,onTransactionStatus:e=>{te({status:e.message,message:e.message,type:e.type})},onNavigateToCountries:()=>u(`countries`),onNavigateToPaymentMethods:()=>u(`payment-methods`),onNavigateToTokens:()=>u(`tokens`),onNavigateToProviders:()=>u(`providers`),onNavigateToHistory:()=>n(`meld-history`),onSelectProvider:M,onProvidersLoaded:O,selectedCountry:d,selectedPaymentMethod:p,selectedToken:h,selectedProvider:j})})};function uT(e){switch(e){case`COMPLETED`:case`SETTLED`:return`text-green-600 bg-green-50`;case`DECLINED`:return`text-red-600 bg-red-50`;case`FAILED`:return`text-red-600 bg-red-50`;case`ERROR`:return`text-red-600 bg-red-50`;case`CANCELLED`:return`text-orange-600 bg-orange-50`;case`PENDING`:return`text-yellow-600 bg-yellow-50`;case`PROCESSING`:return`text-blue-600 bg-blue-50`;case`REFUNDED`:return`text-purple-600 bg-purple-50`;default:return`text-gray-600 bg-gray-50`}}function dT(e){if(!e)return`-`;let t=parseFloat(e);return _s(t)?t.toLocaleString(`en-US`,{minimumFractionDigits:2,maximumFractionDigits:6}):e}function fT(e){return e?je(e).relative||e:`-`}const pT=({transaction:e,meldProviders:t,onClick:n})=>{let[r,i]=X(!1),a=dC(t,e.serviceProvider),o=!!n,s=()=>{n&&n(e)},c=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s())},l=async t=>{if(t.stopPropagation(),e.id)try{await de(e.id),i(!0),setTimeout(()=>i(!1),2*Ee)}catch{}};return Q(`div`,{className:`p-3 trails-border-radius-container border trails-border-primary transition-all duration-200 ${o?`cursor-pointer hover:bg-gray-50`:``}`,...o&&{onClick:s,onKeyDown:c,role:`button`,tabIndex:0},children:[Q(`div`,{className:`flex items-center justify-between mb-2`,children:[Q(`div`,{className:`flex items-center gap-2`,children:[Z(`div`,{className:`flex-shrink-0 w-6 h-6 rounded-full bg-gray-100 flex items-center justify-center overflow-hidden`,title:`Provider: ${e.serviceProvider||`Unknown`}`,children:a?Z(`img`,{src:a,alt:e.serviceProvider,className:`w-4 h-4`}):Z(wi,{className:`w-3 h-3 text-gray-500`})}),Z(`span`,{className:`text-sm font-medium trails-text-primary`,title:e.serviceProvider||`Unknown Provider`,children:(e.serviceProvider||`UNKNOWN`).toUpperCase()}),e.currencyFlag&&Z(`span`,{className:`text-sm`,title:`Country: ${e.countryCode}`,children:e.currencyFlag})]}),Q(`div`,{className:`flex items-center gap-2`,children:[Z(`span`,{className:`px-2 py-0.5 rounded text-xs font-medium ${uT(e.status)}`,title:`Status: ${fC(e.status)}`,children:fC(e.status)}),Z(`span`,{className:`text-xs trails-text-tertiary`,children:fT(e.createdAt||e.updatedAt)})]})]}),Q(`div`,{className:`flex items-center justify-between mb-2`,children:[Q(`div`,{className:`flex items-center gap-2`,children:[Z(`span`,{className:`text-xs trails-text-tertiary font-medium`,children:`Bought`}),Q(`div`,{className:`flex items-center gap-1.5`,children:[Z(Jy,{symbol:e.destinationTokenSymbol,chainId:e.destinationTokenChainId,contractAddress:e.destinationTokenAddress,size:16}),Q(`span`,{className:`text-sm font-semibold trails-text-primary`,children:[dT(e.destinationAmount),` `,e.destinationTokenSymbol]})]})]}),Q(`div`,{className:`flex items-center gap-2`,children:[Z(`span`,{className:`text-xs trails-text-tertiary font-medium`,children:`Paid`}),Q(`span`,{className:`text-sm font-medium trails-text-secondary`,children:[e.sourceCurrencySymbol,dT(e.sourceAmount),` `,e.sourceCurrencyCode]})]})]}),e.destinationTokenChainId&&Q(`div`,{className:`text-xs trails-text-tertiary mb-1`,children:[`on `,Ja(e.destinationTokenChainId)]}),Q(`div`,{className:`flex items-center justify-between text-xs`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[e.paymentMethod&&Q(`div`,{className:`flex items-center gap-1.5 trails-text-tertiary`,title:`Payment Method: ${e.paymentMethod}`,children:[e.paymentMethodLogo?Z(`div`,{className:`w-4 h-4 rounded flex items-center justify-center bg-white`,children:Z(`img`,{src:e.paymentMethodLogo,alt:`${e.paymentMethod} logo`,className:`max-w-full max-h-full object-cover`})}):Z(Pi,{className:`w-3 h-3`}),Z(`span`,{children:e.paymentMethod})]}),e.totalFee&&Q(`span`,{className:`trails-text-tertiary`,title:`Total Fee`,children:[`Fee: `,e.sourceCurrencySymbol,e.totalFee]}),e.exchangeRate&&Q(`span`,{className:`trails-text-tertiary`,title:`Exchange Rate: ${e.exchangeRate.toFixed(4)}`,children:[`Rate: `,e.exchangeRate.toFixed(4)]})]}),e.id&&Q(`button`,{type:`button`,onClick:l,className:`font-mono text-xs bg-gray-100 hover:bg-gray-200 px-1.5 py-0.5 rounded flex items-center gap-1 transition-colors`,title:`Copy transaction ID: ${e.id}`,children:[Z(`span`,{children:e.id.slice(0,6)}),r?Z(Ti,{className:`w-2.5 h-2.5 text-green-600`}):Z(Ni,{className:`w-2.5 h-2.5 text-gray-500`})]})]}),(e.institutionName||e.lowKyc)&&Q(`div`,{className:`flex items-center gap-2 mt-2 pt-1 border-t border-gray-100`,children:[e.institutionName&&Z(`span`,{className:`text-xs bg-blue-50 text-blue-700 px-1.5 py-0.5 rounded`,title:`Institution: ${e.institutionName}`,children:e.institutionName}),e.lowKyc&&Z(`span`,{className:`text-xs bg-green-50 text-green-700 px-1.5 py-0.5 rounded`,title:`Low KYC verification`,children:`Low KYC`})]})]})},mT=()=>Z(`div`,{className:`animate-pulse`,children:[1,2,3].map(e=>Z(`div`,{className:`p-4 trails-border-radius-container border trails-border-primary mb-2`,children:Q(`div`,{className:`flex justify-between items-center`,children:[Q(`div`,{className:`flex flex-col gap-2`,children:[Z(`div`,{className:`h-4 bg-gray-200 rounded w-24`}),Z(`div`,{className:`h-3 bg-gray-200 rounded w-16`}),Z(`div`,{className:`h-3 bg-gray-200 rounded w-20`})]}),Z(`div`,{className:`h-6 bg-gray-200 rounded w-16`})]})},e))}),hT=({limit:e=20,autoRefetch:t=!1,refetchInterval:n=10*Ee,onTransactionClick:r,onBack:i,className:a})=>{let{address:o}=Kr(),{transactions:s,loading:c,error:l,refetch:u}=QS({enabled:!!o,limit:e,autoRefetch:t,refetchInterval:n}),{data:d=[]}=IS();return o?l?Q(`div`,{className:`flex flex-col h-full trails-bg-primary`,children:[Z(M_,{headerContent:`Onramp History`,onBack:i}),Q(`div`,{className:`flex-1 p-4`,children:[Z(XC,{error:l}),Z(`button`,{type:`button`,onClick:()=>u(),className:`mt-4 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors`,children:`Retry`})]})]}):Q(`div`,{className:`flex flex-col h-full trails-bg-primary ${a||``}`,children:[Z(M_,{headerContent:`Onramp History`,onBack:i,rightSideContent:c?Q(`div`,{className:`flex items-center gap-1`,children:[Z(Gi,{className:`h-4 w-4 animate-spin trails-text-secondary`}),Z(`span`,{className:`text-xs trails-text-secondary`,children:`Updating...`})]}):t?null:Z(`button`,{type:`button`,onClick:()=>u(),className:`p-1 rounded hover:bg-gray-100 transition-colors`,disabled:c,children:Z(Gi,{className:`h-4 w-4 trails-text-secondary`})})}),Z(`div`,{className:`flex-1 overflow-y-auto p-4`,children:c&&s.length===0?Z(mT,{}):s.length===0?Z(`div`,{className:`flex items-center justify-center h-full`,children:Q(`div`,{className:`text-center`,children:[Z(`p`,{className:`trails-text-secondary text-sm mb-2`,children:`No transactions found`}),Z(`p`,{className:`trails-text-tertiary text-xs`,children:`Your Meld transaction history will appear here`})]})}):Z(`div`,{className:`space-y-2 max-h-[500px] overflow-y-auto trails-scrollbar`,children:s.map(e=>Z(pT,{transaction:e,meldProviders:d,onClick:r},e.id||Math.random()))})})]}):Q(`div`,{className:`flex flex-col h-full trails-bg-primary`,children:[Z(M_,{headerContent:`Onramp History`,onBack:i}),Z(`div`,{className:`flex-1 flex items-center justify-center p-8`,children:Z(`div`,{className:`text-center`,children:Z(`p`,{className:`trails-text-secondary text-sm`,children:`Connect your wallet to view transaction history`})})})]})},gT=({onBack:e,disconnectHandler:t})=>{let n=Y(!1),r=Y(t);return q(()=>{r.current=t},[t]),q(()=>{n.current||(async()=>{n.current=!0;try{s.console.log(`[trails-sdk] Disconnecting user...`),await Promise.all([r.current(),new Promise(e=>setTimeout(e,Ee))])}catch(e){await new Promise(e=>setTimeout(e,Ee)),s.console.error(`[trails-sdk] Failed to disconnect:`,e)}})()},[]),Q(`div`,{className:`space-y-6`,children:[Z(M_,{onBack:e,headerContent:`Disconnecting...`,headerContentAlign:`left`}),Q(`div`,{className:`flex flex-col items-center justify-center space-y-4 py-8`,children:[Z(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500`}),Z(`p`,{className:`text-sm text-gray-600 dark:text-gray-400`,children:`Disconnecting your wallet...`})]})]})};function _T({amount:e,token:t,chainId:n}){let r=W(Number(n)),i=J(()=>{if(!r||!t)return null;let e=t.trim();return Be(e)??Ze().find(t=>t.symbol.toLowerCase()===e.toLowerCase())??null},[r,t]),a=t?.startsWith(`0x`),o=zc({chainId:n,tokenSymbol:a||r?void 0:t}),s=r?i?.contractAddress??(t&&ut(t.trim())?t.trim():null):a?t:o,c=r?i?.symbol??t:t,{tokenPrice:l}=sv(c&&s&&n?{tokenSymbol:c,tokenAddress:s,chainId:Number(n)}:null),u=e&&l?.priceUsd?Number(e)*l.priceUsd:null;return{amountUsd:u??null,amountUsdFormatted:Ks(u||0),amountUsdFormattedLocale:qs(u||0)}}const vT=({userBalance:e,userBalanceRaw:t,decimals:n,isNativeToken:r,gasCostFormatted:i,chainId:a,onAmountSelect:o,className:s=``})=>{let{trackClick:c}=k_();if(!e)return null;let l=t=>{c({component:`PercentageMaxButtons`,action:`select_percentage`,label:`${t}%`,value:t,metadata:{percentage:t.toString(),userBalance:e,isNativeToken:r.toString(),chainId:a?.toString()}});let n=parseFloat(e);_s(n)&&o((n*t/100).toFixed(6))};return Q(`div`,{className:`flex space-x-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200 ${s}`,children:[Z(`button`,{type:`button`,onClick:()=>l(20),className:`py-0.5 px-1.5 text-xs font-medium rounded-full transition-colors cursor-pointer trails-bg-percentage-button trails-text-percentage-button trails-hover-percentage-button`,children:`20%`}),Z(`button`,{type:`button`,onClick:()=>l(50),className:`py-0.5 px-1.5 text-xs font-medium rounded-full transition-colors cursor-pointer trails-bg-percentage-button trails-text-percentage-button trails-hover-percentage-button`,children:`50%`}),Z(`button`,{type:`button`,onClick:async()=>{c({component:`PercentageMaxButtons`,action:`select_max`,metadata:{userBalance:e,isNativeToken:r.toString(),chainId:a?.toString(),gasCostFormatted:i}}),o(r?Np(e,i&&i!==`0`?i:await Pp(e,a)):vn(BigInt(t),n))},className:`py-0.5 px-1.5 text-xs font-medium rounded-full transition-colors cursor-pointer trails-bg-percentage-button trails-text-percentage-button trails-hover-percentage-button`,children:`Max`})]})},yT=({symbol:e,imageUrl:t,chainId:n,contractAddress:r,chainName:i})=>Z(`div`,{className:`relative max-w-[120px]`,children:Q(`div`,{className:`flex items-center space-x-1.5 trails-bg-card trails-border-radius-input px-2.5 py-1.5 border trails-border-primary`,children:[Z(`div`,{className:`flex items-center flex-shrink-0`,children:Z(Jy,{symbol:e,imageUrl:t,chainId:n,contractAddress:r,size:28})}),Q(`div`,{className:`flex flex-col items-start min-w-0 overflow-hidden`,children:[Z(`span`,{className:`font-bold trails-text-primary text-sm leading-tight truncate max-w-full text-left`,children:e}),i&&Z(`span`,{className:`text-xs trails-text-muted leading-tight truncate max-w-full text-left`,children:i})]})]})});function bT(e){if(!e.chainId)return;let t=Number(e.chainId);return Number.isFinite(t)?t:void 0}function xT(e){return e.inputTokens[0]??e.token}function ST(e){return e.mechanics.type===`lending`?`lend`:`deposit`}function CT(e,t){let n=xT(e),r=n?.address??n?.symbol,i=n?.network??e.network;return ST(e)===`lend`?lt({marketId:e.id,amount:t,inputToken:r,inputTokenNetwork:i}):yt({marketId:e.id,amount:t,inputToken:r,inputTokenNetwork:i})}function wT(e){let t=e.rewardRate.total;return Number.isFinite(t)?t*100:0}function TT(e){let t=e.statistics?.tvlUsd;if(t==null)return null;let n=Number(t);return Number.isFinite(n)?n:null}function ET(e,t){let n=Number(e);return!Number.isFinite(n)||n<=0?null:t/100*n/12}const DT=[`arbitrum`,`avalanche-c`,`base`,`binance`,`ethereum`,`gnosis`,`hyperevm`,`katana`,`monad`,`optimism`,`polygon`],OT=new Set(DT.map(kT).filter(e=>e!==void 0));function kT(e){return tt[e.toLowerCase()]?.id}function AT(e){return e!==void 0&&OT.has(e)}function jT(){return Array.from(OT).map(e=>({chainId:e,name:$(e)?.name??``})).filter(e=>e.name).sort((e,t)=>e.name.localeCompare(t.name))}function MT(e){try{return BigInt(e.amountRaw)>0n}catch{let t=Number(e.amount);return Number.isFinite(t)&&t>0}}function NT(e){return e.outputTokenBalance&&MT(e.outputTokenBalance)?e.outputTokenBalance:e.balances.find(MT)}function PT(e){return Gs(e.amount,{maxFractionDigits:6,minFractionDigits:0})||Us(e.amount,{maxFractionDigits:6,minFractionDigits:0})}function FT(e){return e.balances.yieldId}function IT(e){return e.market?.metadata.name??e.balance.shareToken?.name??`${e.balance.token.symbol} position`}function LT(e){return e.market?.providerId??e.balance.shareToken?.symbol??e.balances.yieldId}function RT(e){return e.market?.network??e.balance.token.network}function zT(e){return e.market?bT(e.market):kT(RT(e))}function BT(e){if(e.market)return wT(e.market);let t=e.balances.rewardRate?.total;return Number.isFinite(t)?t:0}function VT(e){return[IT(e),LT(e),FT(e),RT(e),e.balance.token.symbol,e.balance.token.name,e.balance.token.address,e.balance.shareToken?.symbol,e.balance.shareToken?.name,e.balance.shareToken?.address,e.market?.metadata.description].filter(Boolean).join(` `).toLowerCase()}function HT(e){let t=Number(e.balance.amountUsd);if(Number.isFinite(t))return t;let n=Number(e.balance.amount);return Number.isFinite(n)?n:0}function UT(e){let t=typeof e==`string`?JSON.parse(e):e;if(!t.to||!t.data||t.chainId===void 0)throw Error(`Yield exit action returned an incomplete transaction`);let n=e=>e===void 0?void 0:BigInt(e);return{to:t.to,data:t.data,value:t.value===null?0n:BigInt(t.value??0),chainId:Number(t.chainId),gasLimit:n(t.gasLimit??t.gas),maxFeePerGas:n(t.maxFeePerGas),maxPriorityFeePerGas:n(t.maxPriorityFeePerGas)}}const WT=({account:e,walletClient:t,onTransactionStateChange:n,onError:r,onComplete:i,onPoolSelectorStateChange:a})=>{let o=gs(),c=ri(t),{isBalanceVisible:l}=vu(),{selectedChainId:u,setSelectedChainId:d}=mu(),f=u!==null&&AT(u)?u:null,p=J(()=>jT(),[]),m=Y(null),[h,g]=X(``),[_,v]=X(``),[y,b]=X(!1),[x,S]=X(!1),[C,w]=X(null),[T,E]=X(!1),{data:D,isLoading:O}=Qx({limit:100}),{data:k,isLoading:A,error:j}=nS({walletAddress:e?.address??``,chains:[...DT],enabled:!!e?.address}),M=J(()=>{if(!k?.length)return[];let e=new Map((D??[]).map(e=>[e.id,e]));return k.map(t=>{let n=e.get(t.yieldId),r=NT(t);return!r||n?.status.exit===!1?null:{market:n,balances:t,balance:r}}).filter(e=>!!e)},[k,D]),N=J(()=>{let e=new Set(M.map(zT).filter(e=>e!==void 0));return Array.from(e).map(e=>({chainId:e,name:$(e)?.name??``})).filter(e=>e.name).sort((e,t)=>e.name.localeCompare(t.name))},[M]),P=J(()=>{let e=_.trim().toLowerCase().split(/\s+/).filter(Boolean);return M.filter(t=>{let n=zT(t);if(f!==null&&(n===void 0||n!==f))return!1;if(e.length===0)return!0;let r=VT(t);return e.every(e=>r.includes(e))}).sort((e,t)=>HT(t)-HT(e))},[_,f,M]),F=J(()=>{if(C){let e=M.find(e=>FT(e)===C);if(e)return e}return M[0]??null},[C,M]);q(()=>{let e=F?FT(F):null;!C&&e&&w(e)},[F,C]),q(()=>{m.current?.focus()},[]),q(()=>{a?.(y)},[y,a]),q(()=>{u!==null&&!AT(u)&&d(null)},[u,d]);let I=F?zT(F):void 0,ee=I?$(I):null,te=F?.balance.token,ne=F?PT(F.balance):void 0,re=F?.balance.amount,ie=te?.address??F?.market?.token.address,{amountUsdFormatted:L,amountUsdFormattedLocale:R}=_T({amount:h,token:ie,chainId:I}),ae=e=>{g(e)},z=e=>{s.console.log(`[earn-withdraw] selected market for withdrawal:`,{marketId:FT(e),network:RT(e)}),w(FT(e)),g(``),b(!1)};return y?x?Z(cb,{onBack:()=>S(!1),chains:p}):Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:()=>b(!1),headerContent:`Select Position`,headerContentAlign:`left`}),Z(Xy,{value:_,onChange:e=>v(e||``),placeholder:`Filter positions`,autoFocus:!0,className:`mb-4`,rightAlignedComponent:Z(Oy,{chains:N,selectedChainId:f,onChainSelect:d,chainListScreen:!0,onNavigateToChainList:()=>S(!0)})}),Z(`div`,{className:`px-2 py-1`,children:Z(`p`,{className:`text-xs font-semibold text-gray-600 dark:text-gray-400 tracking-wider`,children:`Available Positions`})}),Z(`div`,{className:`flex-1 overflow-y-auto overflow-x-hidden space-y-2 max-h-[320px] trails-scrollbar`,children:P.length===0?Z(`div`,{className:`py-8 text-center trails-text-secondary text-sm`,children:O||A?`Loading balances...`:M.length===0?`No withdrawable Earn balances found.`:`No positions match your filters.`}):P.map(e=>{let t=zT(e),n=e.balance.token,r=t?$(t):null;return Z(`button`,{type:`button`,onClick:()=>z(e),className:`w-full p-3 trails-list-item trails-border-radius-container transition-all duration-200 cursor-pointer text-left`,children:Q(`div`,{className:`flex items-center justify-between gap-3`,children:[Q(`div`,{className:`flex items-center gap-3 min-w-0`,children:[Z(Jy,{symbol:n.symbol,imageUrl:n.logoURI,chainId:t,contractAddress:n.address,size:32}),Q(`div`,{className:`min-w-0`,children:[Z(`div`,{className:`font-medium text-gray-900 dark:text-white text-sm truncate`,children:IT(e)}),Q(`div`,{className:`text-xs trails-text-secondary`,children:[LT(e),r?` • ${r.name}`:``]})]})]}),Q(`div`,{className:`text-right flex-shrink-0`,children:[Z(`div`,{className:`text-sm font-medium text-gray-900 dark:text-white`,children:l?`${PT(e.balance)} ${n.symbol}`:`••••••`}),e.balance.amountUsd?Q(`div`,{className:`text-xs trails-text-secondary`,children:[`≈`,` `,qs(e.balance.amountUsd)]}):null]})]})},FT(e))})})]}):Q(`div`,{className:`space-y-2`,children:[Z(`div`,{className:`trails-bg-secondary trails-border-radius-container transition-all duration-200 border border-transparent hover:bg-white! dark:hover:bg-white! hover:border-gray-400 dark:hover:border-gray-500`,children:F?Q(`div`,{className:`p-3 trails-border-radius-container trails-bg-secondary transition-all overflow-hidden`,children:[Z(`div`,{className:`flex justify-between items-center mb-2`,children:Z(`div`,{className:`text-sm font-semibold trails-text-secondary text-left`,children:`From`})}),Z(`div`,{className:`px-1`,children:Q(`div`,{className:`flex items-center justify-between`,children:[Q(`div`,{className:`flex items-center space-x-3 min-w-0`,children:[Z(`a`,{href:ie&&I?Za({address:ie,chainId:I}):void 0,target:`_blank`,rel:`noopener noreferrer`,className:`cursor-pointer`,children:Z(Jy,{symbol:te?.symbol??F.market?.token.symbol,imageUrl:te?.logoURI??F.market?.token.logoURI,chainId:I,contractAddress:ie,size:32})}),Q(`div`,{className:`min-w-0`,children:[Z(`h3`,{className:`font-medium text-gray-900 dark:text-white text-sm truncate`,children:IT(F)}),Q(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:[LT(F),ee?` • ${ee.name}`:``]})]})]}),Q(`button`,{type:`button`,title:`Select Vault`,onClick:()=>b(!0),className:`text-right flex items-center space-x-3 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 rounded p-2 transition-colors`,children:[Q(`div`,{children:[Q(`div`,{className:`flex items-center justify-end space-x-1 text-green-600 dark:text-green-400 mb-1 whitespace-nowrap`,children:[Z($i,{className:`w-3 h-3`}),Q(`span`,{className:`font-semibold text-sm`,children:[BT(F).toFixed(1),`% APY`]})]}),F.market?Q(`p`,{className:`text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap`,children:[`TVL:`,` `,rc(TT(F.market)??0)]}):null]}),Z(ki,{className:`w-4 h-4 text-gray-400`})]})]})})]}):Z(`button`,{type:`button`,onClick:()=>b(!0),className:`w-full py-6 px-4 trails-list-item trails-border-radius-container transition-all duration-200 cursor-pointer`,children:Q(`div`,{className:`flex items-center justify-between`,children:[Q(`div`,{className:`flex items-center space-x-3 flex-1`,children:[Z(`div`,{className:`w-8 h-8 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center`,children:Z(qi,{className:`w-4 h-4 text-gray-400`})}),Q(`div`,{className:`text-left flex-1`,children:[Z(`div`,{className:`font-semibold text-gray-900 dark:text-white text-sm`,children:O||A?`Loading withdrawable balances...`:`Select vault to withdraw from`}),j?Z(`div`,{className:`text-xs text-red-500 mt-1`,children:`Failed to load Earn balances`}):null]})]}),Z(ki,{className:`w-4 h-4 trails-text-muted flex-shrink-0`})]})})}),F&&te?Q(`div`,{className:`pt-4 pb-4 mb-4 trails-bg-secondary trails-bg-secondary-hover trails-border-radius-container p-3 group transition-all duration-200 border border-transparent focus-within:bg-white! dark:focus-within:bg-gray-800! trails-focus-border-secondary min-h-[120px] flex flex-col`,children:[Z(`div`,{className:`mb-4 flex justify-between items-center`,children:Z(`div`,{className:`text-sm font-medium trails-text-secondary text-left m-0`,children:`Amount`})}),Q(`div`,{className:`flex items-center space-x-2 flex-1`,children:[Z(`div`,{className:`flex-1`,children:Z(pb,{ref:m,value:h,onChange:e=>g(e.target.value),isLoading:T,variant:`default`})}),I&&te.address?Z(yT,{symbol:te.symbol,imageUrl:te.logoURI,chainId:I,contractAddress:te.address,chainName:ee?.name}):null]}),Q(`div`,{className:`mt-4 flex justify-between items-center`,children:[Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,title:h&&L?L:void 0,children:h?Q(`span`,{className:`notranslate`,translate:`no`,children:[`≈`,` `,R||L||qs(0)]}):Z(`span`,{children:`\xA0`})}),Q(`div`,{className:`flex items-center space-x-2`,children:[Z(`button`,{type:`button`,className:`text-xs text-gray-500 dark:text-gray-400 cursor-pointer hover:text-gray-700 dark:hover:text-gray-200 transition-colors bg-transparent border-none p-0`,onClick:()=>ae(re||`0`),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),ae(re||`0`))},title:`Click to withdraw full balance`,children:Q(`span`,{className:`notranslate`,translate:`no`,children:[`Balance: `,l?ne:`••••••`]})}),Z(vT,{userBalance:re,userBalanceRaw:F.balance.amountRaw,decimals:te.decimals??18,isNativeToken:!1,chainId:I,onAmountSelect:ae,className:`opacity-100`})]})]})]}):null,F?Z(`form`,{onSubmit:async t=>{if(t.preventDefault(),!e||!c){r(`No account or wallet client found`);return}if(!F||!h){r(`Select a market and enter an amount to withdraw`);return}try{E(!0),r(null);let t=(await o.yieldCreateExitAction({earnMarketId:FT(F),userWalletAddress:e.address,args:{amount:h,outputToken:te?.address??te?.symbol,outputTokenNetwork:te?.network??RT(F)}})).action.transactions.filter(e=>!e.isMessage).map(e=>UT(e.unsignedTransaction));if(t.length===0)throw Error(`Yield exit action did not return a transaction`);n(t.map((e,n)=>({transactionHash:``,explorerUrl:``,chainId:e.chainId,state:`pending`,label:t.length===1?`Withdraw`:`Withdraw ${n+1}`})));let a=[];for(let[r,i]of t.entries()){let o=$(i.chainId);if(!o)throw Error(`Chain ${i.chainId} not found`);let s=await Fm(e,c,{to:i.to,data:i.data,value:i.value,chain:o,gasLimit:i.gasLimit,maxFeePerGas:i.maxFeePerGas,maxPriorityFeePerGas:i.maxPriorityFeePerGas}),l=await Va(i.chainId).waitForTransactionReceipt({hash:s});a.push(Gp(l,i.chainId,t.length===1?`Withdraw`:`Withdraw ${r+1}`)),n([...a])}i({transactionStates:a})}catch(e){s.console.error(`[earn-withdraw] error submitting withdrawal:`,e),r(e instanceof Error?e.message:`Failed to withdraw from market`)}finally{E(!1)}},children:Z(`button`,{type:`submit`,disabled:!h||T,className:`w-full font-semibold py-4 px-4 trails-border-radius-button transition-colors bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white disabled:text-gray-500 disabled:cursor-not-allowed cursor-pointer relative`,children:T?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:`Processing...`})]}):`Withdraw`})}):null]})};function GT(e){let{account:t,destinationChainId:n}=e,r=wo(),{address:i}=Kr(),a=(r.toAddress??``).trim(),o=t?.address??i??null,s=J(()=>a?bn(a)?{recipient:a.toLowerCase(),source:`prop`,invalidProp:!1}:{recipient:null,source:`prop`,invalidProp:!0}:o&&bn(o)?{recipient:o.toLowerCase(),source:`account`,invalidProp:!1}:{recipient:null,source:null,invalidProp:!1},[a,o]),c=s.source===`prop`&&s.recipient!==null&&n!=null&&Number.isFinite(n),{data:l,isLoading:u,error:d}=Or({queryKey:[`earnRecipientIsContract`,s.recipient,n],queryFn:()=>eo(s.recipient,n),enabled:c,staleTime:6e4,gcTime:5*6e4,retry:1}),f=c&&l===!0,p=c&&u,m=J(()=>s.invalidProp?"Invalid `to.recipient`: must be a valid EVM address (0x…).":f?"`to.recipient` cannot be a contract address — vault shares would mint to a non-signer and would be unrecoverable. Provide an EOA the user controls.":d&&c?"Could not verify that `to.recipient` is an EOA. Please try again.":null,[s.invalidProp,f,d,c]),h=!a&&!o&&s.recipient===null;return{recipient:m?null:s.recipient,source:s.source,isInvalidProp:s.invalidProp,isContractRecipient:f,isCheckingContract:p,error:m,needsRecipient:h}}function KT(){let{toAmount:e,toToken:t,toChainId:n}=wo(),{amountUsd:r,amountUsdFormatted:i,amountUsdFormattedLocale:a}=_T({amount:e,token:t,chainId:Number(n)});return{targetAmountUsd:r,targetAmountUsdFormatted:i,targetAmountUsdFormattedLocale:a}}const qT=1e6;function JT(e){return 0}function YT(e,t,n){return Ie([e],t,n)===e}function XT(){let{toToken:e,toChainId:t,fromToken:n,fromChainId:r}=wo(),{targetAmountUsd:i}=KT(),{address:a}=Kr(),o=E_(a),c=Zu(Hu()),l=qu()?.publicKey?.toBase58(),{sortedTokens:u,isLoadingSortedTokens:d}=Q_(o??null,void 0,{refetchInterval:!1}),{tokens:f,isLoading:p}=q_(l,{disabled:!l||!c&&!!o}),m=J(()=>c?f:f.length===0?u:[...u,...f],[u,c,f]),h=c?p:d,g=Y(null),_=Y(``);return{defaultOriginToken:J(()=>{if(!m?.length)return g.current=null,null;let a=m.map(e=>`${e.symbol}-${e.chainId}-${e.contractAddress||`native`}`).join(`,`);if(!(a!==_.current||!g.current)&&g.current)return g.current;_.current=a;let o=e=>{let t=e.isNativeToken??!1,n=$(e.chainId||0);if(t){let t=W(e.chainId??0),r=n?.nativeCurrency.decimals??(t?9:18),i=Ct(e.chainId??0);return{...e,name:e.name||n?.nativeCurrency.name||`Unknown`,symbol:e.symbol||n?.nativeCurrency.symbol||`Unknown`,balance:e.balance??`0`,imageUrl:e.imageUrl||``,chainId:e.chainId??0,contractAddress:i,balanceUsdFormatted:e.balanceUsdFormatted??`0`,priceUsd:e.priceUsd??0,decimals:r,isNativeToken:!0}}else return e.decimals?{...e,name:e.name??`Unknown Token`,symbol:e.symbol??`???`,balance:e.balance??`0`,imageUrl:e.imageUrl||``,chainId:e.chainId??0,balanceUsdFormatted:e.balanceUsdFormatted??`0`,priceUsd:e.priceUsd??0}:(s.console.warn(`[trails-sdk] Missing decimals for token:`,{symbol:e.symbol,chainId:e.chainId}),null)};if(n&&r){let e=typeof r==`string`?Number(r):r,t=m.find(t=>YT(t,n,e));if(t){s.console.log(`[trails-sdk] Found matching fromToken for default origin selection`,{symbol:t.symbol,chainId:t.chainId});let e=o(t);if(e)return g.current=e,e}}let c=m.filter(e=>(e.balanceUsd??0)>0);if(c.length===0)return s.console.log(`[trails-sdk] No tokens with balance found for default origin selection`),null;let l=(e,t)=>{let n=[...e].sort((e,t)=>{let n=JT(e),r=JT(t),i=n>=qT,a=r>=qT;if(i&&!a)return-1;if(!i&&a)return 1;let o=e.balanceUsd??0;return(t.balanceUsd??0)-o}),r=t??1,i=[],a=[];for(let e of n){let t=e.balanceUsd??0,n=e.isNativeToken??!1;(!n&&e.symbol?.toUpperCase()===`USDC`||n)&&t>=r?i.push(e):a.push(e)}return i.sort((e,t)=>{let n=e.isNativeToken??!1,r=t.isNativeToken??!1,i=!n&&e.symbol?.toUpperCase()===`USDC`,a=!r&&t.symbol?.toUpperCase()===`USDC`;if(i&&!a)return-1;if(!i&&a)return 1;if(n&&!r)return-1;if(!n&&r)return 1;let o=e.balanceUsd??0;return(t.balanceUsd??0)-o}),[...i,...a]},u=null;if(e&&t){let n=Number(t),r=i??.01,a=c.filter(e=>(e.balanceUsd??0)>=r),o=a.find(t=>YT(t,e,n));o&&(u=o,s.console.log(`[trails-sdk] Selected same-chain, same-token (fastest)`)),u||(u=l(a.filter(e=>e.chainId===n),r)[0]??null,u&&s.console.log(`[trails-sdk] Selected same-chain, different-token (fast)`)),u||(u=l(a.filter(t=>YT(t,e)&&t.chainId!==n),r)[0]??null,u&&s.console.log(`[trails-sdk] Selected different-chain, same-token (slower)`)),u||(u=l(a.filter(e=>e.chainId!==n),r)[0]??null,u&&s.console.log(`[trails-sdk] Selected different-chain, different-token (slowest)`)),u||(u=l(c,r)[0]??null,s.console.log(`[trails-sdk] Fallback: No token can cover target amount, using highest balance token`))}else u=l(c,1)[0]??null,s.console.log(`[trails-sdk] No destination specified, selected highest value token with best liquidity`);if(!u)return null;let d=o(u);return s.console.log(`[trails-sdk] Default origin token selection:`,{origin:d?{symbol:d.symbol,chainId:d.chainId,balanceUsd:d.balanceUsdFormatted,volume24h:JT(u)}:null,toToken:e,toChainId:t,targetAmountUsd:i,effectiveTargetAmount:e&&t?i??.01:null}),g.current=d,d},[e,t,m,i,n,r]),isLoading:h}}function ZT(e,t){let n=qu(),r=E_(t),i=n?.publicKey?.toBase58?.()??null;return J(()=>e?.chainId&&W(e.chainId)?i:r??null,[e?.chainId,r,i])}const QT=`Use a Solana wallet for Solana tokens, or choose an EVM token.`,$T=`Origin chain and wallet do not match. ${QT}`;function eE({originChainId:e,fundMethod:t,selectedFundingWallet:n,evmAccountAddress:r,connectedWallets:i,svmWallet:a,session:o}){return t&&t!==`wallet`||!W(e??0)||Zu(n)||wd(n,bd({connectedWallets:i??[],svmWallet:a??null,session:o??null,selectedFundingWallet:n,activeEvmAddress:r}))?!1:!!(Xu(n)||!n&&r)}function tE(e,t){return e===`earn`?nn.v1_5:t}function nE({account:e,toAmount:t,toRecipient:n,toChainId:r,toToken:i,toApprove:o,toCalldata:c,actions:l,walletClient:u,onTransactionStateChange:d,onError:f,onWaitingForWalletConfirm:p,selectedToken:h,onSend:g,onConfirm:_,onComplete:v,setWalletConfirmRetryHandler:y,tradeType:b=ln.EXACT_OUTPUT,swapProvider:x,bridgeProvider:S,swapProviderFallback:C,bridgeProviderFallback:w,fundMethod:T,mode:E,checkoutOnHandlers:D,fromAmount:O,onrampTrackingData:A,skipFeeBalanceFetch:j=!1,onNavigateToOnrampMesh:M,onNavigateToOnrampBluvo:N}){let{isSmartWallet:P,intentProtocolVersion:F}=wo(),I=tE(E,F),te=qu(),ne=Jr(),re=ni(),ie=E_(e?.address),L=Hu(),R=!!e?.address,[ae,z]=X(b===ln.EXACT_INPUT?O??``:t??``),[B,V]=X(n??``),[oe,H]=X(null),{data:ce=[]}=Hx(),{ensAddress:U}=Py({textInput:B}),le=U||B;q(()=>{f&&f(oe)},[oe,f]);let ue=e=>{V(e.target.value.trim())},[de,fe]=X(()=>{let e=ce.find(e=>e.id===r);if(e)return e;if(r){let e=$(r);if(e)return e}return ce[0]}),{supportedTokens:pe,isLoadingTokens:me}=Rc(),he=J(()=>de?.id?pe.filter(e=>e.chainId===de.id):pe,[pe,de?.id]),ge=i?.startsWith(`0x`)??!1,{addCustomToken:_e}=rs(),{tokenInfo:ve,isLoading:ye,error:be}=Uc({address:ge?i:``,chainId:r}),xe=J(()=>ge?!!(ge&&!be&&!ye&&ve):!0,[ge,be,ye,ve]);q(()=>{if(ve&&!be&&ge&&r&&i&&ve.symbol&&ve.name&&ve.decimals!==void 0)if(pe.some(e=>e.chainId===r&&Pe(e.contractAddress,i)))s.console.log(`[trails-sdk] Token from toToken prop already exists in supported tokens, skipping custom token addition:`,{toToken:i,toChainId:r});else{let e=$(r)?.name||`Chain ${r}`,t={tokenId:`${r}-${i.toLowerCase()}`,chainId:r,contractAddress:i,symbol:ve.symbol,name:ve.name,decimals:ve.decimals,chainName:e,imageUrl:ve.imageUrl||``,isCustomToken:!0};_e(t),s.console.log(`[trails-sdk] Added custom token from toToken prop to storage:`,t)}},[ve,be,ge,r,i,_e,pe]),q(()=>{ge&&ve&&!ye&&Oe(ve)},[ve,ge,ye]),q(()=>{ge&&be&&!ye&&(s.console.error(`[trails-sdk] errorCustomToken`,be),se(be)?H(`Failed to verify token address. Please check your network connection and try again.`):H(`Invalid custom toToken address (${i}). The address may not be a valid token on this chain.`))},[be,ge,ye,i]);let Se=J(()=>de?qg(he,de.id)||null:he?.[0]||null,[he,de]),[Ce,we]=X(!1),[Te,Ee]=X(!1),[De,Oe]=X(()=>{let e=Se;return i&&!ge&&(e=Kg(he,i,r||de?.id)||null),e});q(()=>{!De&&Se&&Oe(Se)},[De,Se]),q(()=>{if(De?.chainId){let e=$(De.chainId);e&&fe(e)}},[De]);let ke=J(()=>{if(me||ge&&ye)return!1;if(b===ln.EXACT_OUTPUT){let e=De?.contractAddress!==void 0&&De?.decimals!==void 0&&De?.chainId===de?.id;return ge&&i&&e?De?.contractAddress?.toLowerCase()===i.toLowerCase():e}return h?.decimals!==void 0},[me,ge,ye,i,De?.contractAddress,De?.decimals,De?.chainId,de?.id,h?.decimals,b]),{trailsApiKey:Ae,sequenceIndexerUrl:je}=Vx(),{sortedTokens:Me}=Q_(j?null:ie??null,void 0,{refetchInterval:!1}),Ne=zc({chainId:de?.id,tokenSymbol:De?.symbol}),{tokenPrices:Fe}=ov(J(()=>{if(T===`onramp-meld`)return[];let e=[],t=De?.contractAddress??Ne;return De&&t&&de?.id&&e.push({tokenSymbol:De.symbol,tokenAddress:t,chainId:de.id}),h&&(De&&t&&ft(h.contractAddress,t,de?.id)&&h.chainId===de?.id||e.push({tokenSymbol:h.symbol,tokenAddress:h.contractAddress,chainId:h.chainId||69})),e},[T,De,Ne,de?.id,h])),Ie=J(()=>{if(!Fe||!de?.id)return null;let e=de.id,t=[De?.contractAddress,Ne].filter(e=>!!e);return t.length===0?null:Fe.filter(n=>n.token?.chainId!==e||!n.token?.tokenAddress?!1:t.some(t=>ft(n.token?.tokenAddress,t,e))?!0:W(e)&&bt(n.token?.tokenAddress,e))},[Fe,Ne,De?.contractAddress,de?.id]),Le=J(()=>!Fe||!h?null:Fe.filter(e=>ft(e.token?.tokenAddress,h.contractAddress,h.chainId)&&e.token?.chainId===h.chainId),[Fe,h]);q(()=>{if(!r)return;let e=ce.find(e=>e.id===r)??$(r);e&&fe(e)},[r,ce]),q(()=>{if(i&&!ge&&de?.id){let e=Kg(he,i,r||de.id);e&&Oe(e)}},[i,he,r,de?.id,ge]),q(()=>{b===ln.EXACT_INPUT&&O!==void 0?z(O):b===ln.EXACT_OUTPUT&&z(t??``)},[O,t,b]);let Re=J(()=>Us(t||0),[t]),[ze,Be]=X(n);n!==ze&&(Be(n),V(n??``));let Ve=$(h?.chainId),[He,Ue]=X(!1),[We,Ge]=X(!1),Ke=K(e=>{try{d(e)}catch(e){let t=k(e,{boundary:`sdk`,code:`send.transaction-state-change`});s.console.error(`[trails-sdk] Error calling onTransactionStateChange:`,t)}},[d]),qe=T&&T!==`wallet`,{token:Je,isLoadingBalance:Ye}=ev(h,ZT(h??null,e?.address),{disabled:qe,withPrices:!0}),Xe=Je?.balance&&Je?.decimals?Xs(Je.balance||`0`,Je.decimals||18):void 0,Ze=Je?.balanceUsdFormatted||``,Qe=Je?.balanceLocaleDisplay||``,$e=Je?.balanceUsdLocaleDisplay||``,et={mode:E,destinationChainId:de?.id,originChainId:h?.chainId},tt=Zl(le??``,et),nt=Ql(le??``,et),rt=tu(le??``,et),it=eE({originChainId:h?.chainId,fundMethod:T,selectedFundingWallet:L,evmAccountAddress:ie??e?.address,connectedWallets:ne,svmWallet:te,session:re}),at=J(()=>{let e=b===ln.EXACT_INPUT?Le?.[0]?.priceUsd??0:Ie?.[0]?.priceUsd??0;return Ks(Number(ae)*e)},[ae,Ie,Le,b]),ot=J(()=>{let e=b===ln.EXACT_INPUT?Le?.[0]?.priceUsd??0:Ie?.[0]?.priceUsd??0;return qs(Number(ae)*e)},[ae,Ie,Le,b]),st=zc({chainId:de?.id,tokenSymbol:De?.symbol}),ct=J(()=>{if(ge)return s.console.log(`[trails-sdk] [CUSTOM-TOKEN] Using toToken prop as destinationTokenAddress:`,i),i??null;if(De?.contractAddress)return s.console.log(`[trails-sdk] [CUSTOM-TOKEN] Using contractAddress from selectedDestToken:`,{contractAddress:De.contractAddress,symbol:De.symbol}),De.contractAddress;let e=st??null;return s.console.log(`[trails-sdk] [CUSTOM-TOKEN] Using address from symbol lookup:`,{addressFromSymbol:e,symbol:De?.symbol}),e},[ge,i,De?.contractAddress,De?.symbol,st]),lt=J(()=>{if(!h&&!De||!ke)return`0`;if(!ae&&!(h?.decimals||De?.decimals))return s.console.warn(`[trails-sdk] Missing token decimals for quote`,{amount:ae,selectedToken:h,selectedDestToken:De,tradeType:b}),`0`;if(b===ln.EXACT_INPUT){if(!h?.decimals)return s.console.warn(`[trails-sdk] Missing source token decimals for quote`,{selectedToken:h,tradeType:b}),`0`}else if(!De?.decimals)return s.console.warn(`[trails-sdk] Missing destination token decimals for quote`,{selectedDestToken:De,tradeType:b}),`0`;let e=b===ln.EXACT_INPUT?h?.decimals:De?.decimals;if(!e)return s.console.warn(`[trails-sdk] Missing token decimals for quote`,{decimals:e,selectedToken:h,selectedDestToken:De,tradeType:b}),`0`;try{return Sn(ae,e).toString()}catch{return`0`}},[ae,ke,De,h,De?.decimals,h?.decimals,b]),ut=J(()=>{if(!h||!De||!e?.address||!le)return!1;let t=h.contractAddress?.toLowerCase()===De.contractAddress?.toLowerCase()&&h.chainId===De.chainId,n=h.chainId===De.chainId;if(T&&T!==`wallet`)return!1;let r=Pe(le,e.address);return t&&n&&r},[h,De,e?.address,le,T]),dt=l?.length||ut?null:rt?le:null,{quote:G,send:pt,isLoadingQuote:mt,quoteError:ht,quoteErrorPrettified:gt,feeOptions:_t,refetchQuote:vt,isRecipientContract:yt,isSenderContractOnOrigin:xt,isSenderContractOnDestination:St}=a_({walletClient:u,walletAddress:e?.address??null,from:{token:h?.contractAddress??``,chain:h?.chainId??0,...h?.decimals!==void 0&&{decimals:h.decimals},...b===ln.EXACT_INPUT&&lt!==`0`?{amount:ae}:{}},to:{token:ct??``,chain:de?.id??0,...De?.decimals!==void 0&&{decimals:De.decimals},recipient:dt,approve:o,calldata:c,...b===ln.EXACT_OUTPUT&&lt!==`0`?{amount:ae}:{}},onStatusUpdate:Ke,swapProvider:x,bridgeProvider:S,swapProviderFallback:C,bridgeProviderFallback:w,checkoutOnHandlers:D,isSmartWallet:P,fundMethod:T,onramp:A,mode:E,intentProtocolVersion:I,actions:l,disabled:tt||nt||it}),Ct=mt,wt=it?$T:ht?a(ht):null,Tt=it?$T:gt||null,Et=!!pt,Dt=J(()=>!G||!Et?null:{quote:G,feeOptions:{feeOptions:_t}},[G,Et,_t]),Ot=J(()=>{let e=Dt?.quote?.destinationAmountFormatted;return e&&e!==`0`?e:Re},[Dt,Re]),kt=J(()=>{let e=Us(Ot||0);return Number(e)===0?`0`:e},[Ot]),At=J(()=>{if(Dt?.quote){let e=b===ln.EXACT_INPUT?Dt.quote.originAmountUsdDisplay:Dt.quote.destinationAmountUsdDisplay;if(e&&e!==`$0.00`)return e}return at},[Dt,b,at]),jt=J(()=>Ol(Dt?.feeOptions?.feeOptions??[],h?.chainId,Me),[Dt?.feeOptions?.feeOptions,h?.chainId,Me]),{selectedFeeOption:Mt,setSelectedFeeOption:Nt}=Yl(jt);q(()=>{let e=Dt?.quote?.expiresAt;if(!e||He||We)return;let t=()=>{s.console.log(`[trails-sdk] [auto-refresh] Quote expired, waiting for user activity to refetch`,{expiresAt:e});let t=()=>{s.console.log(`[trails-sdk] [auto-refresh] User activity detected, refetching quote`,{expiresAt:e}),window.removeEventListener(`mousemove`,t),window.removeEventListener(`keydown`,t),vt()};return window.addEventListener(`mousemove`,t,{once:!0}),window.addEventListener(`keydown`,t,{once:!0}),()=>{window.removeEventListener(`mousemove`,t),window.removeEventListener(`keydown`,t)}},n=new Date(e).getTime()-Date.now();if(n<=0)return t();let r,i=setTimeout(()=>{r=t()},n);return()=>{clearTimeout(i),r?.()}},[Dt?.quote?.expiresAt,He,We,vt]);let Pt=K(async()=>{s.console.log(`[trails-sdk] processSend called`,{fundMethod:T,hasQuote:!!Dt,hasSend:!!pt}),s.console.log(`[trails-sdk] Called processSend with fund method: ${T}`);try{if(!Dt||!pt){H(`No quote available. Please wait for quote to load.`);return}H(null),Ue(!0);let e=Dt.quote;s.console.log(`[trails-sdk] Using quote from useQuote:`,e);function t(){s.console.log(`[trails-sdk] onOriginSend called`),_(),Ge(!1),g(ae,le)}Ge(!0),T!==`onramp-meld`&&p(Dt.quote,T===`direct-transfer`?pt:void 0);async function n(){s.console.log(`[trails-sdk] [fee-select] [gasless-flow] handleSend called, about to call sendFn()`),s.console.log(`[trails-sdk] [fee-select] [gasless-flow] selectedFeeOption value at swap() call time:`,{selectedFeeOption:Mt,isNull:Mt===null,isUndefined:Mt===void 0,type:typeof Mt,stringified:an(Mt)});let n=await pt({selectedFeeOption:Mt??null,onOriginSend:t});s.console.log(`[trails-sdk] sendFn() completed:`,n),v({transactionStates:e.transactionStates??[]})}if(_p(T)){if(T===`direct-transfer`){s.console.log(`[trails-sdk] Direct-transfer fund method detected, deferring send until deposit confirmed`,{fundMethod:T,quote:!!e}),Ue(!1),Ge(!1);return}s.console.log(`[trails-sdk] Exchange or Meld fund method detected, navigating to onramp`,{fundMethod:T,quote:!!e});let t=e?.originChain?.id,n=e?.destinationChain?.id,r=e?.originToken?.symbol,i=tc(e.originAmountFormatted??`0`).toString(),a=e?.originChain?.id,o=e.originDepositAddress,c=e?.originAmountUsdFormatted?parseFloat(e.originAmountUsdFormatted):void 0;if(s.console.log(`[trails-sdk] Navigating to onramp with props:`,{toTokenSymbol:r,toTokenAmount:i,toChainId:a,toRecipientAddress:o,toAmountUsd:c,originChainId:t,destinationChainId:n}),!r||!i||!a||!o)throw Error(`[trails-sdk] Missing required props for onramp`);T===`onramp-mesh`?(s.console.log(`[trails-sdk] Preparing Mesh onramp intent before navigation`,{hasSendFn:!!pt,intentId:e?.intentId}),await pt({selectedFeeOption:Mt??null}),s.console.log(`[trails-sdk] Mesh onramp intent prepared successfully`,{intentId:e?.intentId}),M&&M({toTokenSymbol:r,toTokenAmount:i,toChainId:a,toRecipientAddress:o,toAmountUsd:c})):T===`onramp-bluvo`&&(s.console.log(`[trails-sdk] Preparing Bluvo onramp intent before navigation`,{hasSendFn:!!pt,intentId:e?.intentId}),await pt({selectedFeeOption:Mt??null}),N&&N({toTokenSymbol:r,toTokenAmount:i,toChainId:a,toRecipientAddress:o,toAmountUsd:c})),Ue(!1),Ge(!1);return}async function r(){s.console.log(`[trails-sdk] walletConfirmRetryHandler called`);try{s.console.log(`[trails-sdk] About to call handleRetry`),await n(),s.console.log(`[trails-sdk] handleRetry completed successfully`)}catch(e){if(e instanceof m)s.console.log(`[trails-sdk] Wallet-confirm retry cancelled (superseded); suppressing error state`);else{let t=ee(e,{boundary:`sdk`,code:`send.wallet-confirm-retry`,apiBoundary:`trails-api`});s.console.error(`[trails-sdk] Error in prepareSend walletConfirmRetryHandler:`,t);let n=a(t);H(n),f&&f(n)}}}y(()=>r),await n()}catch(e){if(e instanceof m)s.console.log(`[trails-sdk] Send cancelled (superseded); suppressing error state`);else{let t=ee(e,{boundary:`sdk`,code:`send.process`,apiBoundary:`trails-api`});s.console.error(`[trails-sdk] Error in prepareSend:`,t);let n=a(t);H(n),f&&f(n)}}Ue(!1),Ge(!1)},[Dt,pt,ae,g,_,v,y,p,le,f,T,Mt,M,N]),Ft=async e=>{e.preventDefault(),Pt().catch(e=>{let t=k(e,{boundary:`sdk`,code:`send.submit`});s.console.error(`[trails-sdk] Error in processSend:`,t),H(t.message)})},It=J(()=>{if(!R)return`Connect your wallet`;if(!h)return`Select a token`;if(!ae)return`Enter an amount`;if(!De?.symbol)return E===`earn`?`Select a vault`:`Select a token`;if(We)return`Waiting for wallet...`;if(He)return`Processing...`;if(tt)return`Chain pair not supported`;if(it)return`Origin chain and wallet do not match`;if(!rt)return E===`earn`?`Connect EVM wallet`:`Enter a recipient`;if(Ct)return`Getting quote...`;if(Tt||wt||!Dt)return T===`onramp-mesh`||T===`onramp-bluvo`?`Continue to Exchange`:T===`onramp-meld`||T===`direct-transfer`?`Continue`:E===`pay`?`Pay`:E===`fund`?`Fund`:E===`swap`?`Swap`:E===`earn`?`Deposit`:E===`withdraw`?`Withdraw`:`Continue`;let t=Dt?.quote?.originAmountFormatted??Us(ae),n=Dt?.quote?.destinationAmountFormatted??Us(ae),r=h.symbol,i=De?.symbol,a=Ws(t),o=Ws(n);try{let t=h.chainId===de?.id,n=h.symbol===De.symbol,c=e?.address?yn(e.address):null,l=le&&bn(le)?yn(le):null;return s.console.log(`[trails-sdk] buttonText:`,{mode:E,fundMethod:T,isSameChain:t,isSameToken:n,checksummedRecipient:l}),T===`onramp-mesh`||T===`onramp-bluvo`?`Continue to Exchange`:T===`onramp-meld`||T===`direct-transfer`?`Continue`:!T||T===`wallet`?E===`pay`?`Pay`:E===`fund`?`Fund`:E===`swap`?`Swap`:E===`earn`?`Deposit`:E===`withdraw`?`Withdraw`:`Continue on wallet`:E===`swap`?`Swap ${a} ${r}`:E===`earn`?`Deposit ${o} ${i}`:b===ln.EXACT_INPUT?`Fund with ${a} ${r}`:t&&n?`Execute`:t&&!n?`Swap ${a} ${r}`:c&&l===c?`Receive ${o} ${i}`:`Pay with ${a} ${r}`}catch{return`Pay with ${a} ${r}`}},[ae,rt,le,e?.address,R,De?.symbol,We,He,Ct,Tt,wt,Dt,h,b,Dt?.quote?.originAmountFormatted,de?.id,E,T,tt,it]);return{amount:ae,amountRaw:lt,amountUsdDisplay:At,amountUsdLocaleDisplay:ot,balanceUsdDisplay:Ze,balanceLocaleDisplay:Qe,balanceUsdLocaleDisplay:$e,chainInfo:Ve,toChainId:r,error:oe,balanceFormatted:Xe,balanceRaw:Je?.balance??`0`,tokenDecimals:Je?.decimals??18,handleRecipientInputChange:ue,handleSubmit:Ft,isChainDropdownOpen:Ce,isSubmitting:He,isLoadingQuote:Ct,isTokenDropdownOpen:Te,recipient:le,recipientInput:B,selectedDestinationChain:de,selectedDestToken:De,setAmount:z,setRecipientInput:V,setSelectedDestinationChain:fe,setSelectedDestToken:Oe,setSelectedFeeOption:Nt,processedFeeOptions:jt,supportedTokens:he,supportedChains:ce,ensAddress:U??null,isWaitingForWalletConfirm:We,buttonText:It,sendFn:pt,isValidRecipient:rt,destTokenPrices:Ie??null,sourceTokenPrices:Le??null,selectedToken:h,selectedFeeOption:Mt??null,setIsChainDropdownOpen:we,setIsTokenDropdownOpen:Ee,toAmountFormatted:Ot,toAmountDisplay:kt,destinationTokenAddress:ct,isValidCustomToken:xe,prepareSendQuote:Dt?.quote??null,quoteError:wt,quoteErrorPrettified:Tt,isOriginFundingWalletMismatch:it,isRecipientContract:yt??!1,isSenderContractOnOrigin:xt??!1,isSenderContractOnDestination:St??!1,isLoadingBalance:Ye}}const rE=({title:e,titleId:t,...n})=>Q(`svg`,{xmlns:`http://www.w3.org/2000/svg`,xmlSpace:`preserve`,viewBox:`0 0 190.5 190.5`,"aria-labelledby":t,...n,children:[e?Z(`title`,{id:t,children:e}):null,Z(`path`,{fill:`#9391F7`,d:`M190.5 95.3C190.5 42.6 147.9 0 95.3 0S0 42.6 0 95.3s42.6 95.3 95.3 95.3 95.2-42.7 95.2-95.3`}),Z(`path`,{fill:`#FFFFFF`,d:`M77.5 99.9c8.2-1.3 13.7-9 12.4-17.2s-9-13.7-17.2-12.4-13.7 9-12.4 17.2c1.4 8.2 9.1 13.7 17.2 12.4m39.2 0c8.2-1.3 13.7-9 12.4-17.2s-9-13.7-17.2-12.4-13.7 9-12.4 17.2 9 13.7 17.2 12.4`}),Z(`path`,{fill:`#FFFFFF`,d:`M94.7 23.3C54 23.3 21 56.9 21 98.3h18.8c0-31.1 24.4-56.2 54.8-56.2 30.5 0 54.8 25.2 54.8 56.2h18.8c.2-41.4-32.8-75-73.5-75`})]}),iE=({title:e,titleId:t,...n})=>Q(`svg`,{xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 78 24`,"aria-labelledby":t,...n,children:[e?Z(`title`,{id:t,children:e}):null,Z(`rect`,{width:42,height:23,x:.5,y:.5,fill:`#FFFFFF`,stroke:`#E5E7EB`,rx:11.5}),Z(`image`,{width:30,height:14,x:6,y:5,href:`data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iODAwIiB3aWR0aD0iMTIwMCIgdmlld0JveD0iLTc0LjcgLTQwLjIwNCA2NDcuNCAyNDEuMjI0Ij48ZGVmcz48bGluZWFyR3JhZGllbnQgeDE9IjAiIHkxPSIwIiB4Mj0iMSIgeTI9IjAiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiBncmFkaWVudFRyYW5zZm9ybT0ic2NhbGUoODkuNzI3OTMgLTg5LjcyNzkzKSByb3RhdGUoLTIwLjIxOCAuOTY2IC0uNDU3KSIgc3ByZWFkTWV0aG9kPSJwYWQiIGlkPSJiIj48c3RvcCBvZmZzZXQ9IjAiIHN0b3AtY29sb3I9IiMyMjIzNTciLz48c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMyNTRhYTUiLz48L2xpbmVhckdyYWRpZW50PjxjbGlwUGF0aCBjbGlwUGF0aFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgaWQ9ImEiPjxwYXRoIGQ9Ik00MTMuNzQyIDkwLjQzNWMtLjA1Ny00LjQ5NCA0LjAwNS03LjAwMiA3LjA2NS04LjQ5MyAzLjE0NC0xLjUzIDQuMi0yLjUxMSA0LjE4OC0zLjg3OS0uMDI0LTIuMDk0LTIuNTA4LTMuMDE4LTQuODMzLTMuMDU0LTQuMDU2LS4wNjMtNi40MTQgMS4wOTUtOC4yODkgMS45NzFsLTEuNDYxLTYuODM3YzEuODgxLS44NjcgNS4zNjQtMS42MjMgOC45NzYtMS42NTYgOC40NzggMCAxNC4wMjUgNC4xODUgMTQuMDU1IDEwLjY3NC4wMzMgOC4yMzUtMTEuMzkxIDguNjkxLTExLjMxMyAxMi4zNzIuMDI3IDEuMTE2IDEuMDkyIDIuMzA3IDMuNDI2IDIuNjEgMS4xNTUuMTUzIDQuMzQ0LjI3IDcuOTU5LTEuMzk1bDEuNDE5IDYuNjE1Yy0xLjk0NC43MDgtNC40NDMgMS4zODYtNy41NTQgMS4zODYtNy45OCAwLTEzLjU5My00LjI0Mi0xMy42MzgtMTAuMzE0bTM0LjgyNyA5Ljc0NGMtMS41NDggMC0yLjg1My0uOTAzLTMuNDM1LTIuMjg5bC0xMi4xMTEtMjguOTE3aDguNDcybDEuNjg2IDQuNjU5aDEwLjM1M2wuOTc4LTQuNjU5aDcuNDY3bC02LjUxNiAzMS4yMDZoLTYuODk0bTEuMTg1LTguNDNsMi40NDUtMTEuNzE4aC02LjY5Nmw0LjI1MSAxMS43MThtLTQ2LjI4NCA4LjQzbC02LjY3OC0zMS4yMDZoOC4wNzNsNi42NzUgMzEuMjA2aC04LjA3bS0xMS45NDMgMGwtOC40MDMtMjEuMjQtMy4zOTkgMTguMDZjLS4zOTkgMi4wMTYtMS45NzQgMy4xOC0zLjcyMyAzLjE4aC0xMy43MzdsLS4xOTItLjkwNmMyLjgyLS42MTIgNi4wMjQtMS41OTkgNy45NjUtMi42NTUgMS4xODgtLjY0NSAxLjUyNy0xLjIwOSAxLjkxNy0yLjc0Mmw2LjQzOC0yNC45MDNoOC41MzJsMTMuMDggMzEuMjA2aC04LjQ3OCIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNhKSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODQ2OSAwIDAgLTQuOTg0NjkgLTE4MDQuODIgNTAyLjIwMikiPjxwYXRoIGQ9Ik0wIDBsOTguNDM3IDM2LjI1MiAyMi4zOTQtNjAuODA5LTk4LjQzNi0zNi4yNTIiIGZpbGw9InVybCgjYikiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDM1MS42MTEgOTYuODk2KSIvPjwvZz48L3N2Zz4=`}),Z(`rect`,{width:30,height:23,x:47.5,y:.5,fill:`#FFFFFF`,stroke:`#E5E7EB`,rx:11.5}),Z(`image`,{width:21,height:16,x:52,y:4,href:`data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iODAwIiB3aWR0aD0iMTIwMCIgaWQ9InN2Zzg5NSIgdmVyc2lvbj0iMS4xIiB2aWV3Qm94PSItOTYgLTk4LjkwOCA4MzIgNTkzLjQ0OCI+PGRlZnMgaWQ9ImRlZnM4NzkiPjxzdHlsZSBpZD0ic3R5bGU4NzciIHR5cGU9InRleHQvY3NzIj4uZXtmaWxsOiNmNzllMWJ9PC9zdHlsZT48L2RlZnM+PHBhdGggaWQ9InJlY3Q4ODciIGRpc3BsYXk9ImlubGluZSIgZmlsbD0iI2ZmNWYwMCIgc3Ryb2tlLXdpZHRoPSI1LjQ5NCIgZD0iTTIyNC44MzMgNDIuMjk4aDE5MC40MTZ2MzExLjAwNUgyMjQuODMzeiIvPjxwYXRoIGlkPSJwYXRoODg5IiBkPSJNMjQ0LjQ0NiAxOTcuODI4YTE5Ny40NDggMTk3LjQ0OCAwIDAxNzUuNTQtMTU1LjQ3NSAxOTcuNzc3IDE5Ny43NzcgMCAxMDAgMzExLjAwNCAxOTcuNDQ4IDE5Ny40NDggMCAwMS03NS41NC0xNTUuNTN6IiBmaWxsPSIjZWIwMDFiIiBzdHJva2Utd2lkdGg9IjUuNDk0Ii8+PHBhdGggaWQ9InBhdGg4OTEiIGQ9Ik02MjEuMTAxIDMyMC4zOTR2LTYuMzcyaDIuNzQ3di0xLjMxOWgtNi41Mzd2MS4zMTloMi41ODJ2Ni4zNzN6bTEyLjY5MSAwdi03LjY5aC0xLjk3OGwtMi4zMDcgNS40OTMtMi4zMDgtNS40OTRoLTEuOTc3djcuNjkxaDEuNDI4di01LjgyM2wyLjE0MyA1aDEuNDgzbDIuMTQzLTV2NS44MjN6IiBjbGFzcz0iZSIgZmlsbD0iI2Y3OWUxYiIgc3Ryb2tlLXdpZHRoPSI1LjQ5NCIvPjxwYXRoIGlkPSJwYXRoODkzIiBkPSJNNjQwIDE5Ny44MjhhMTk3Ljc3NyAxOTcuNzc3IDAgMDEtMzIwLjAxNSAxNTUuNDc0IDE5Ny43NzcgMTk3Ljc3NyAwIDAwMC0zMTEuMDA0QTE5Ny43NzcgMTk3Ljc3NyAwIDAxNjQwIDE5Ny43NzN6IiBjbGFzcz0iZSIgZmlsbD0iI2Y3OWUxYiIgc3Ryb2tlLXdpZHRoPSI1LjQ5NCIvPjwvc3ZnPg==`})]}),aE=({title:e,titleId:t,...n})=>Q(`svg`,{xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 60 24`,"aria-labelledby":t,...n,children:[e?Z(`title`,{id:t,children:e}):null,Z(`image`,{width:20,height:20,y:2,href:`data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IS0tIFVwbG9hZGVkIHRvOiBTVkcgUmVwbywgd3d3LnN2Z3JlcG8uY29tLCBHZW5lcmF0b3I6IFNWRyBSZXBvIE1peGVyIFRvb2xzIC0tPgo8c3ZnIHdpZHRoPSI4MDBweCIgaGVpZ2h0PSI4MDBweCIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICAgPGNpcmNsZSBjeD0iNTEyIiBjeT0iNTEyIiByPSI1MTIiIHN0eWxlPSJmaWxsOiMwMDUyZmYiLz4KICAgPHBhdGggZD0iTTUxNi4zIDM2MS44M2M2MC4yOCAwIDEwOC4xIDM3LjE4IDEyNi4yNiA5Mi40N0g3NjRDNzQyIDMzNi4wOSA2NDQuNDcgMjU2IDUxNy4yNyAyNTYgMzcyLjgyIDI1NiAyNjAgMzY1LjY1IDI2MCA1MTIuNDlTMzcwIDc2OCA1MTcuMjcgNzY4YzEyNC4zNSAwIDIyMy44Mi04MC4wOSAyNDUuODQtMTk5LjI4SDY0Mi41NWMtMTcuMjIgNTUuMy02NSA5My40NS0xMjUuMzIgOTMuNDUtODMuMjMgMC0xNDEuNTYtNjMuODktMTQxLjU2LTE0OS42OC4wNC04Ni43NyA1Ny40My0xNTAuNjYgMTQwLjYzLTE1MC42NnoiIHN0eWxlPSJmaWxsOiNmZmYiLz4KPC9zdmc+`}),Z(`image`,{width:20,height:20,x:20,y:2,href:`data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IS0tIFVwbG9hZGVkIHRvOiBTVkcgUmVwbywgd3d3LnN2Z3JlcG8uY29tLCBHZW5lcmF0b3I6IFNWRyBSZXBvIE1peGVyIFRvb2xzIC0tPgo8c3ZnIHdpZHRoPSI4MDBweCIgaGVpZ2h0PSI4MDBweCIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICAgPHN0eWxlPgogICAgICAuc3Qxe2ZpbGw6I2ZmZn0KICAgPC9zdHlsZT4KICAgPGcgaWQ9Ikljb24iPgogICAgICA8Y2lyY2xlIGN4PSI1MTIiIGN5PSI1MTIiIHI9IjUxMiIgc3R5bGU9ImZpbGw6I2YzYmEyZiIvPgogICAgICA8cGF0aCBjbGFzcz0ic3QxIiBkPSJNNDA0LjkgNDY4IDUxMiAzNjAuOWwxMDcuMSAxMDcuMiA2Mi4zLTYyLjNMNTEyIDIzNi4zIDM0Mi42IDQwNS43eiIvPgogICAgICA8cGF0aCB0cmFuc2Zvcm09InJvdGF0ZSgtNDUuMDAxIDI5OC42MjkgNTExLjk5OCkiIGNsYXNzPSJzdDEiIGQ9Ik0yNTQuNiA0NjcuOWg4OC4xVjU1NmgtODguMXoiLz4KICAgICAgPHBhdGggY2xhc3M9InN0MSIgZD0iTTQwNC45IDU1NiA1MTIgNjYzLjFsMTA3LjEtMTA3LjIgNjIuNCA2Mi4zaC0uMUw1MTIgNzg3LjcgMzQyLjYgNjE4LjNsLS4xLS4xeiIvPgogICAgICA8cGF0aCB0cmFuc2Zvcm09InJvdGF0ZSgtNDUuMDAxIDcyNS4zNjQgNTEyLjAzMikiIGNsYXNzPSJzdDEiIGQ9Ik02ODEuMyA0NjhoODguMXY4OC4xaC04OC4xeiIvPgogICAgICA8cGF0aCBjbGFzcz0ic3QxIiBkPSJNNTc1LjIgNTEyIDUxMiA0NDguN2wtNDYuNyA0Ni44LTUuNCA1LjMtMTEuMSAxMS4xLS4xLjEuMS4xIDYzLjIgNjMuMiA2My4yLTYzLjN6Ii8+CiAgIDwvZz4KPC9zdmc+`}),Z(`image`,{width:20,height:20,x:40,y:2,href:`data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IS0tIFVwbG9hZGVkIHRvOiBTVkcgUmVwbywgd3d3LnN2Z3JlcG8uY29tLCBHZW5lcmF0b3I6IFNWRyBSZXBvIE1peGVyIFRvb2xzIC0tPgo8c3ZnIHdpZHRoPSI4MDBweCIgaGVpZ2h0PSI4MDBweCIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICAgPGNpcmNsZSBjeD0iNTEyIiBjeT0iNTEyIiByPSI1MTIiIHN0eWxlPSJmaWxsOiMwM2NhOWIiLz4KICAgPHBhdGggZD0iTTczMi44MSAyNzVjLTEuNjctLjczLTE3My41MS0yNC42LTM0My4zOSA4Ni44OEMyODQgNDMxLjIyIDI3MCA1MzIuNjggMjc0LjgxIDYwMC4zNmMyNDcuMDgtMjcuODkgNDUyLjQxLTMxNy4yOSA0NTgtMzI1LjM2ek0yOTEuNTcgNjc1LjUzYzIxLjI0IDM4LjE0IDE4MS43NyAxMjQuNiAzMjMuODcgNS4zNVM3NDUuNjIgMzQ0LjY2IDczMi44MSAyNzVjLTQuNDcgMTAuMTEtMTU5LjYyIDM1Ni44OS00NDEuMjQgNDAwLjUxIiBzdHlsZT0iZmlsbDojZmZmIi8+Cjwvc3ZnPg==`})]}),oE=({title:e,titleId:t,...n})=>Q(`svg`,{xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 300 300`,"aria-labelledby":t,...n,children:[e?Z(`title`,{id:t,children:e}):null,Q(`g`,{clipPath:`url(#a)`,children:[Z(`path`,{fill:`#2470FF`,d:`M150 300c82.843 0 150-67.157 150-150S232.843 0 150 0 0 67.157 0 150s67.157 150 150 150`}),Z(`path`,{fill:`white`,d:`M87.432 177.299v44.675c0 2.751 2.328 3.892 3.052 4.151a4.97 4.97 0 0 0 5.327-1.037l33.797-32.479c2.878-2.766 5.656-5.673 7.744-9.074.982-1.599 1.389-2.5 1.389-2.5 2.07-4.203 2.07-8.25.052-12.298-2.999-6.019-10.655-12.142-22.189-17.953l-19.707 11c-5.844 3.321-9.465 9.185-9.465 15.515`,opacity:.8}),Z(`path`,{fill:`white`,d:`M68 77.933v46.855c0 5.863 3.931 11.052 9.517 12.712 19.034 5.5 52.188 17.331 60.206 34.713 1.033 2.283 1.654 4.515 1.862 6.849 5.328-9.703 7.758-20.859 6.621-32.17a55.24 55.24 0 0 0-23.276-39.902L75.707 73.937a4.64 4.64 0 0 0-2.793-.934c-.828 0-1.552.156-2.328.571-1.552.882-2.586 2.49-2.586 4.359`}),Z(`path`,{fill:`white`,d:`M213.136 177.299v44.675c0 2.751-2.327 3.892-3.052 4.151a4.97 4.97 0 0 1-5.327-1.037l-34.584-33.234c-2.354-2.263-4.602-4.656-6.375-7.398-1.405-2.171-1.971-3.421-1.971-3.421-2.069-4.203-2.069-8.25-.053-12.298 3.001-6.019 10.656-12.142 22.189-17.953l19.707 11c5.897 3.321 9.466 9.185 9.466 15.515`,opacity:.8}),Z(`path`,{fill:`white`,d:`M232.6 77.93v46.854c0 5.864-3.932 11.052-9.518 12.713-19.034 5.5-52.187 17.331-60.205 34.713-1.035 2.283-1.656 4.514-1.862 6.849-5.328-9.703-7.758-20.859-6.621-32.17a55.23 55.23 0 0 1 23.276-39.902l47.223-33.053a4.64 4.64 0 0 1 2.793-.934c.827 0 1.552.156 2.326.57 1.553.883 2.588 2.491 2.588 4.36`})]}),Z(`defs`,{children:Z(`clipPath`,{id:`a`,children:Z(`path`,{fill:`white`,d:`M0 0h300v300H0z`})})})]}),sE=({protocols:e,selectedProtocol:t,onProtocolChange:n,sortBy:r,onSortChange:i,showSort:a=!0})=>{let[o,s]=X(!1),[c,l]=X(!1),u=Y(null),d=Y(null),f=e=>typeof e==`string`?e:e.id,p=e=>f(e)===`all`?`All Protocols`:typeof e==`string`?e:e.name,m=e=>{if(typeof e!=`string`)return e.logoURI;if(e===`Aave`)return rE;if(e===`Morpho`)return oE},h=e.find(e=>f(e)===t)??t,g=t===`all`?e.flatMap(e=>{let t=m(e);return t?[t]:[]}).slice(0,3):(()=>{let e=m(h);return e?[e]:[]})(),_=(e,t)=>typeof e==`string`?Z(`img`,{src:e,alt:t,className:`w-2.5 h-2.5 rounded-full object-contain`,loading:`lazy`},e):Z(e,{"aria-label":t,className:`w-2.5 h-2.5 rounded-full object-contain`},t),v=e=>{let t=m(e);return t?_(t,p(e)):null};return Q(`div`,{className:`flex items-center space-x-2 mb-3`,children:[Q(`div`,{className:`relative`,ref:u,children:[Q(`button`,{type:`button`,onClick:e=>{e.preventDefault(),e.stopPropagation(),s(!o)},className:`flex items-center justify-between px-2 py-1.5 trails-bg-secondary text-gray-700 dark:text-gray-300 rounded-xl hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors cursor-pointer text-xs min-w-[100px]`,children:[Q(`div`,{className:`flex items-center space-x-1`,children:[g.map(e=>_(e,p(h))),Z(`span`,{className:`text-xs font-medium`,children:p(h)})]}),Z(Di,{className:`w-4 h-4 ml-1`})]}),o&&Z(`div`,{className:`absolute top-full left-0 mt-0.5 w-full trails-bg-secondary border border-gray-200 dark:border-gray-700 rounded-xl shadow-lg z-20`,children:e.map(e=>{let r=f(e);return Q(`button`,{type:`button`,onClick:e=>{e.preventDefault(),e.stopPropagation(),n(r),s(!1)},className:`w-full flex items-center space-x-1 px-2 py-1.5 text-left hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer first:rounded-t-xl last:rounded-b-xl ${t===r?`bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400`:`text-gray-700 dark:text-gray-300`}`,children:[v(e),Z(`span`,{className:`text-xs`,children:p(e)})]},r)})})]}),a&&Q(`div`,{className:`relative`,ref:d,children:[Q(`button`,{type:`button`,onClick:e=>{e.preventDefault(),e.stopPropagation(),l(!c)},className:`flex items-center justify-between px-2 py-1.5 trails-bg-secondary text-gray-700 dark:text-gray-300 rounded-xl hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors cursor-pointer text-xs min-w-[90px]`,children:[Z(`span`,{className:`text-xs font-medium`,children:(e=>e===`tvl`?`Sort by TVL`:`Sort by APY`)(r)}),Z(Di,{className:`w-4 h-4 ml-1`})]}),c&&Q(`div`,{className:`absolute top-full left-0 mt-0.5 w-full trails-bg-secondary border border-gray-200 dark:border-gray-700 rounded-xl shadow-lg z-20`,children:[Z(`button`,{type:`button`,onClick:e=>{e.preventDefault(),e.stopPropagation(),i(`tvl`),l(!1)},className:`w-full px-2 py-1.5 text-left hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer rounded-t-xl ${r===`tvl`?`bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400`:`text-gray-700 dark:text-gray-300`}`,children:Z(`span`,{className:`text-xs`,children:`Sort by TVL`})}),Z(`button`,{type:`button`,onClick:e=>{e.preventDefault(),e.stopPropagation(),i(`apy`),l(!1)},className:`w-full px-2 py-1.5 text-left hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer rounded-b-xl ${r===`apy`?`bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400`:`text-gray-700 dark:text-gray-300`}`,children:Z(`span`,{className:`text-xs`,children:`Sort by APY`})})]})]})]})},cE=[`aave`,`morpho`,`curve`,`fluid`,`gearbox`,`yearn`,`summer-fi`,`spark`,`sky`],lE=new Set(cE);function uE(e){return e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function dE(e){let t=xT(e);return[e.metadata.name,e.metadata.description,e.providerId,e.network,e.chainId,t?.symbol,t?.name,t?.address,e.token.symbol,e.token.name,...e.tags??[]].filter(Boolean).join(` `).toLowerCase()}function fE(e,t,n){if(!t)return!0;let r=xT(e),i=bT(e);return i==null?!1:n&&!n.has(i)?!0:t.some(t=>t.chainId===i?r?.address?Pe(t.contractAddress,r.address):t.symbol.toLowerCase()===e.token.symbol.toLowerCase():!1)}const pE=({onBack:e,onMarketSelect:t})=>{let n=gs(),{selectedChainId:r,setSelectedChainId:i}=mu(),{availableDestinationChainIds:a,availableDestinationTokens:o,availableDestinationTokenRestrictedChainIds:s}=xl(),c=J(()=>a?new Set(a):null,[a]),l=J(()=>s?new Set(s):null,[s]),u=r!==null&&AT(r)&&(!c||c.has(r))?r:null,d=J(()=>jT().filter(e=>!c||c.has(e.chainId)),[c]),[f,p]=X(``),[m,h]=X(`aave`),[g,_]=X(0),[v,y]=X(!1),[b,x]=X(``),S=f.trim(),C=b.trim(),w=S!==C,T=`${u??`all`}:${m}:${S}`,E=Y(T),{data:D,isLoading:O,error:k}=Or({queryKey:[`earnProviders`,`widget`],queryFn:()=>Dt({limit:50},n)}),{data:A,isLoading:j,isFetching:M,isFetchingNextPage:N,error:P,fetchNextPage:F,hasNextPage:I}=Er({queryKey:[`earnMarkets`,`widget-provider`,m,u,`rewardRateDesc`,C||void 0],queryFn:({pageParam:e})=>Tt({provider:m===`all`?void 0:m,chain:u??void 0,sortBy:`rewardRateDesc`,search:C||void 0,limit:100,offset:e},n),initialPageParam:0,getNextPageParam:(e,t)=>{if(e.items.length===0||e.items.length<100)return;let n=t.reduce((e,t)=>e+t.items.length,0),r=e.total??0;if(!(r>0&&n>=r))return n},staleTime:6e4}),ee=J(()=>A?.pages.flatMap(e=>e.items)??[],[A]),te=j||O,ne=P||k,re=J(()=>{let e=new Map;for(let t of D?.items??[])e.set(t.id,t);return e},[D]),ie=J(()=>[`all`,...cE.map(e=>{let t=re.get(e);return{id:e,name:t?.name??uE(e),logoURI:t?.logoURI}})],[re]),L=J(()=>{let e=S.toLowerCase().split(/\s+/).filter(Boolean);return ee.filter(t=>{if(!lE.has(t.providerId)||!t.status.enter||t.metadata.deprecated||t.metadata.underMaintenance)return!1;let n=wT(t);if(n<1||n>1e3)return!1;let r=TT(t);if(r===null||r<5e5)return!1;let i=bT(t);if(!AT(i)||c&&!c.has(i)||o&&!fE(t,o,l)||u!==null&&i!==u||m!==`all`&&t.providerId!==m)return!1;if(e.length===0)return!0;let a=dE(t);return e.every(e=>a.includes(e))}).sort((e,t)=>wT(t)-wT(e))},[ee,S,u,m,c,o,l]),R=J(()=>L.slice(g*20,(g+1)*20),[L,g]),ae=g>0,z=L.length>(g+1)*20||I;return q(()=>{let e=setTimeout(()=>{x(f)},300);return()=>clearTimeout(e)},[f]),q(()=>{E.current!==T&&(E.current=T,_(0))},[T]),q(()=>{r!==null&&(!AT(r)||c&&!c.has(r))&&i(null)},[c,r,i]),q(()=>{if(I||L.length===0)return;let e=Math.max(0,Math.ceil(L.length/20)-1);g>e&&_(e)},[L.length,I,g]),q(()=>{if(w||j||N||!I)return;let e=(g+1)*20;L.length<e&&F()},[g,L.length,I,w,N,j,F]),v?Z(cb,{onBack:()=>y(!1),chains:d}):Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:e,headerContent:`Select Market`,headerContentAlign:`left`}),Z(Xy,{value:f,onChange:e=>{p(e||``),_(0)},placeholder:`Filter markets`,autoFocus:!0,className:`mb-4`,rightAlignedComponent:Z(Oy,{chains:d,selectedChainId:u,onChainSelect:e=>{i(e),_(0)},chainListScreen:!0,onNavigateToChainList:()=>y(!0)})}),!te&&Z(sE,{protocols:ie,selectedProtocol:m,onProtocolChange:e=>{(e===`all`||lE.has(e))&&(h(e),_(0))},sortBy:`apy`,onSortChange:()=>void 0,showSort:!1}),Z(`div`,{className:`px-2 py-1`,children:Z(`p`,{className:`text-xs font-semibold text-gray-600 dark:text-gray-400 tracking-wider`,children:`Available Markets`})}),Z(`div`,{className:`flex-1 overflow-y-auto overflow-x-hidden space-y-2 max-h-[320px] trails-scrollbar`,children:te?Q(`div`,{className:`flex flex-col items-center justify-center py-8 space-y-4`,children:[Z(`div`,{className:`animate-spin rounded-full h-8 w-8 border-solid border-b-2 border-blue-500`}),Z(`p`,{className:`text-gray-600 dark:text-gray-400`,children:`Loading markets...`})]}):ne?Q(`div`,{className:`flex flex-col items-center justify-center py-8 space-y-2`,children:[Z(`p`,{className:`text-sm text-red-500`,children:`Failed to load markets`}),Z(`p`,{className:`text-xs text-gray-500`,children:`Please try again later`})]}):R.length===0?M||w?Q(`div`,{className:`flex flex-col items-center justify-center py-8 space-y-4`,children:[Z(`div`,{className:`animate-spin rounded-full h-6 w-6 border-solid border-b-2 border-blue-500`}),Z(`p`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`Searching for markets...`})]}):Q(`div`,{className:`text-center py-8`,children:[Z(qi,{className:`mx-auto mb-2 h-5 w-5 text-gray-400`}),Z(`p`,{className:`text-gray-500 dark:text-gray-400 text-sm`,children:`No markets match your filters`})]}):Q(hi,{children:[R.map(e=>{let n=xT(e),r=bT(e),i=wT(e),a=TT(e),o=re.get(e.providerId),s=o?.logoURI;return Z(`button`,{type:`button`,onClick:()=>t(e),className:`w-full p-3 rounded-2xl cursor-pointer transition-all text-left hover:bg-gray-50 dark:hover:bg-gray-800 active:scale-[0.99]`,children:Q(`div`,{className:`flex items-center justify-between gap-2.5`,children:[Q(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[Z(Jy,{symbol:n?.symbol,imageUrl:n?.logoURI,chainId:r,contractAddress:n?.address,size:32}),Q(`div`,{className:`min-w-0`,children:[Z(`h3`,{title:e.metadata.name,className:`font-semibold text-gray-950 dark:text-white text-xs truncate`,children:e.metadata.name}),Q(`div`,{className:`mt-0.5 flex items-center gap-1 text-[10px] text-gray-500 dark:text-gray-400`,children:[s?Z(`img`,{src:s,alt:``,className:`h-2.5 w-2.5 rounded-full object-contain bg-white`,loading:`lazy`}):Z(`span`,{className:`h-2.5 w-2.5 rounded-full bg-indigo-100 text-indigo-500 flex items-center justify-center text-[7px] font-bold`,children:uE(e.providerId).charAt(0)}),Z(`span`,{className:`truncate`,children:o?.name??uE(e.providerId)})]})]})]}),Q(`div`,{className:`text-right flex-shrink-0`,children:[Q(`div`,{className:`flex items-center justify-end gap-1 text-green-600 dark:text-green-400`,children:[Z($i,{className:`w-3 h-3`}),Q(`span`,{className:`font-semibold text-sm`,children:[i.toFixed(1),`% APY`]})]}),Q(`p`,{className:`text-[10px] text-gray-500 dark:text-gray-400 whitespace-nowrap`,children:[`TVL: `,a===null?`-`:rc(a)]})]})]})},e.id)}),N&&R.length<20&&Z(`div`,{className:`flex items-center justify-center py-3`,children:Z(`div`,{className:`animate-spin rounded-full h-4 w-4 border-solid border-b-2 border-blue-500`})})]})}),!te&&!ne&&(ae||z)&&Q(`div`,{className:`mt-3 flex items-center justify-between px-2 text-xs text-gray-500 dark:text-gray-400`,children:[Z(`span`,{children:R.length>0?`Showing ${R.length} ${R.length===1?`market`:`markets`} · Page ${g+1}`:`Page ${g+1}`}),Q(`div`,{className:`flex items-center gap-2`,children:[Z(`button`,{type:`button`,onClick:()=>_(e=>Math.max(0,e-1)),disabled:!ae||N,className:`rounded-lg px-2 py-1 font-medium text-gray-700 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40 dark:text-gray-300 dark:hover:bg-gray-800`,children:`Previous`}),Z(`button`,{type:`button`,onClick:()=>_(e=>e+1),disabled:!z||N,className:`rounded-lg px-2 py-1 font-medium text-gray-700 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40 dark:text-gray-300 dark:hover:bg-gray-800`,children:N?`Loading...`:`Next`})]})]})]})},mE=({processedFeeOptions:e,selectedFeeOption:t,setSelectedFeeOption:n,chainId:r,isRefetching:i,originTokenInfo:a})=>{let[o,s]=X(!1),{trackClick:c}=k_();if(!Tl(r)||i||e.length===0||!Fl(e))return null;let{selectedOption:l,displayOption:u}=Vl({feeOptions:e,selectedFeeOption:t,originTokenInfo:a}),d=e=>{let t=jl(e),i=t===null;c({component:`FeeOptions`,action:`select_fee_option`,label:i?`native_gas`:e.tokenSymbol,metadata:{tokenSymbol:e.tokenSymbol,tokenAddress:e.tokenAddress,chainId:(e.chainId||r)?.toString(),isNativeToken:i.toString(),amountFormatted:e.amountFormatted,amountUsd:e.amountUsdDisplay}}),n(t),s(!1)};return e.length===1&&l?Z(`div`,{className:`space-y-1`,children:Q(`div`,{className:`p-2`,children:[Z(`div`,{className:`flex justify-between items-center mb-2`,children:Z(`div`,{className:`text-xs font-medium trails-text-primary`,children:`Gas Fee Option`})}),Z(`div`,{className:`mt-2 space-y-1`,children:Z(_b,{option:l,isSelected:Ml(l,t),chainId:l.chainId||r,originTokenInfo:a})})]})}):Z(`div`,{children:Q(`div`,{className:`p-2`,children:[Q(`button`,{className:`w-full flex justify-between items-center mb-2 cursor-pointer`,type:`button`,onClick:()=>s(!o),children:[Z(`div`,{className:`text-sm font-semibold text-gray-900 dark:text-white`,children:`Gas Fee Options`}),Q(`div`,{className:`flex items-center gap-1`,children:[u&&Z(Jy,{imageUrl:u.tokenImageUrl,symbol:u.tokenSymbol,chainId:u.chainId||r,size:16}),u&&Z(`div`,{className:`text-sm font-medium text-gray-600 dark:text-gray-400`,title:u.amountUsdDisplay,children:u.amountUsdLocaleDisplay||u.amountUsdDisplay}),Z(Di,{className:`w-3 h-3 transition-transform text-gray-600 dark:text-gray-400 ${o?`transform rotate-180`:``}`})]})]}),o&&Z(`div`,{className:`mt-2 space-y-1`,children:e.map(e=>Z(_b,{option:e,isSelected:Ml(e,t),onClick:()=>d(e),chainId:e.chainId||r,originTokenInfo:a},e.tokenAddress))})]})})},hE=({showWalletConnectorIcon:e,sendToScreen:t={screen:`fund-methods`}})=>{let{address:n,isConnected:r}=Kr(),i=Jr(),a=ni(),{navigate:o,mode:s}=y_(),{selectedToken:c}=ul(),{selectedFundMethod:l,paymentMethod:u}=Vu(),d=Hu(),f=qu(),{fundMethod:p}=wo(),m=!!p&&s!==`swap`,h=n&&bn(n)?n:null,g=!!h,_=l===`wallet`&&(Td({connectedWallets:i,svmWallet:f,selectedFundingWallet:d,hasActiveEvmConnection:r&&i.length>0})||!!c?.chainId&&W(c.chainId)),v=J(()=>bd({connectedWallets:i,svmWallet:f,session:a,selectedFundingWallet:d,activeEvmAddress:h}),[h,i,d,f,a]),y=J(()=>v?xd(v,{preferSolanaAddress:_}):_?f?.publicKey?.toBase58?.()??``:h??``,[h,_,v,f]),b=v?.walletId??v?.evmWallet?.walletId??(_?f?.walletId:void 0),x=J(()=>{if(v)return md(v,f,{preferSolanaIcon:_});if(_&&f)return pd(f)},[_,v,f]),{ensName:S,ensAvatar:C}=Iy({address:!(Zu(v?.selection)||y&&!bn(y))&&bn(y)?y:``}),w=!!(S||C);return Q(`button`,{type:`button`,onClick:()=>{m||(g?o(t.screen,{backTarget:t.backScreen}):o(`connect`))},disabled:m,className:`flex items-center space-x-2 transition-colors bg-transparent border-none p-0 ${m?`trails-text-secondary cursor-default`:`text-polygon-500 hover:text-polygon-600 cursor-pointer`}`,children:[g?l===`direct-transfer`?Q(hi,{children:[Z(aa,{className:`w-4 h-4 mr-1`}),Z(`span`,{className:`text-sm font-medium m-0`,children:`Crypto Transfer`})]}):l===`onramp-mesh`||l===`onramp-bluvo`?Q(hi,{children:[Z(Ji,{className:`w-4 h-4 mr-1`}),Z(`span`,{className:`text-sm font-medium m-0`,children:`Exchange`})]}):l===`onramp-meld`?Z(`span`,{className:`text-sm font-medium m-0`,children:u.name||`Onramp`}):Q(hi,{children:[Z(`div`,{className:`flex items-center mr-1`,children:b||x?Z(Na,{walletId:b,icon:x,label:v?.name??`Wallet`,size:20,className:`shrink-0`,imageClassName:`shrink-0 rounded-full object-cover`,decorative:!0}):y&&bn(y)?Z(Wy,{size:20,walletAddress:y,showWalletConnectorIcon:e}):Z(`div`,{className:`shrink-0 rounded-full bg-gray-200 dark:bg-gray-700`,style:{width:20,height:20}})}),Z(`span`,{className:`text-sm font-medium m-0 truncate`,children:w&&S||wt(y,4,4)})]}):Z(`span`,{className:`text-sm font-medium mr-1`,children:`Connect Wallet`}),!m&&Z(ki,{className:`w-4 h-4 m-0`})]})},gE=({token:e,chainId:t,onSelect:n,className:r=`flex items-center justify-between trails-border-radius-input px-2.5 py-2 border transition-all duration-200`,unselectable:i=!1,fullWidth:a=!1})=>{let{isConnected:o}=Yr(),{navigate:s}=y_(),{selectedFundMethod:c}=Vu(),l=e?.chainId||t,u=J(()=>l?$(l):null,[l]),{trackClick:d}=k_();return Z(`button`,{type:`button`,onClick:()=>{if(!i){if(d({component:`TokenSelectorButton`,action:`select_token`,label:e?.symbol||`unselected`,metadata:{chainId:l?.toString(),tokenSymbol:e?.symbol,contractAddress:e?.contractAddress,fundMethod:c}}),!o&&c===`wallet`){s(`connect`);return}n()}},disabled:i,className:`flex h-[52px] my-0 min-h-[52px] shrink-0 items-center ${r} ${!a&&e?`max-w-[145px]`:``} ${a?`w-full`:``} ${i?e?`bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-700 cursor-default`:`bg-blue-500 border-blue-500 text-white cursor-default`:e?`bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 hover:border-gray-300 dark:hover:border-gray-600 cursor-pointer`:`bg-blue-500 hover:bg-blue-600 border-blue-500 text-white cursor-pointer`}`,children:e?Q(hi,{children:[Q(`div`,{className:`flex items-center flex-1 min-w-0 overflow-hidden`,children:[Z(`div`,{className:`flex items-center shrink-0`,children:Z(Jy,{symbol:e.symbol,imageUrl:e.imageUrl,chainId:l,contractAddress:e.contractAddress,size:28})}),Q(`div`,{className:`flex flex-col items-start flex-1 min-w-0 overflow-hidden ml-1.5`,children:[Z(`span`,{className:`font-bold trails-text-primary text-sm leading-tight truncate w-full text-left`,children:e.symbol}),u&&Z(`span`,{className:`text-xs trails-text-muted leading-tight truncate w-full text-left`,children:u.name})]})]}),!i&&Z(ki,{className:`w-3.5 h-3.5 shrink-0 trails-text-muted ml-1`})]}):Q(hi,{children:[Z(`span`,{className:`font-medium text-sm text-white flex-1`,children:`Select Token`}),!i&&Z(ki,{className:`w-3.5 h-3.5 shrink-0 text-white ml-1`})]})})};function _E(e){let t=e>=1?2:e>=.01?4:6;return e.toLocaleString(void 0,{maximumFractionDigits:t,minimumFractionDigits:0})}const vE=({account:e,walletClient:t,onTransactionStateChange:n,onError:r,onWaitingForWalletConfirm:i,onConfirm:a,onComplete:o,onSend:s,setWalletConfirmRetryHandler:c,swapProvider:l,bridgeProvider:u,swapProviderFallback:d,bridgeProviderFallback:f,fundMethod:p,checkoutOnHandlers:m,recentTokens:h,onRecentTokenSelect:g,onTrackToken:_,onPoolSelectorStateChange:v})=>{let y=gs(),{mode:b}=y_(),x=wo(),{address:S}=Kr(),C=To(x),{isBalanceVisible:w}=vu(),{selectedToken:T,setSelectedToken:E}=ul(),{token:D,isLoadingBalance:O}=ev(T,ZT(T,e?.address)),{defaultOriginToken:k,isLoading:A}=XT(),[j,M]=X(null),[N,P]=X(!1),[F,I]=X(!1),[ee,te]=X(!1),[ne,re]=X(``),ie=Y(null),L=qu(),R=Nt(101),ae=J(()=>L&&(!p||p===`wallet`)?[Ra]:void 0,[p,L]),{handleChainSelect:z}=D_(p??`wallet`),B=j?xT(j):void 0,V=j?bT(j):void 0,oe=j?wT(j):0,H=j?TT(j):null,{data:se}=Or({queryKey:[`earnProviders`,`widget`],queryFn:()=>Dt({limit:100},y),enabled:!!j}),ce=J(()=>{let e=new Map;for(let t of se?.items??[])e.set(t.id,t);return e},[se]),U=j?ce.get(j.providerId):void 0,le=B?.address&&V?Za({address:B.address,chainId:V}):void 0,ue=U?.website||j?.metadata.documentation,de=J(()=>{if(j)return CT(j,Et())},[j]),fe=J(()=>de?[de]:void 0,[de]),pe=GT({account:e,destinationChainId:V??null}),me=pe.recipient,he=pe.error,ge=pe.isCheckingContract,_e=J(()=>{if(e)return e;if(S)return{address:S,type:`json-rpc`}},[e,S]),ve=!_e?.address,ye=pe.needsRecipient,be=ve?`Connect an EVM wallet to receive your vault shares.`:ye?`Set an EVM recipient address to receive your vault shares.`:null,{balanceFormatted:xe,balanceRaw:Se,balanceLocaleDisplay:Ce,tokenDecimals:we,isLoadingQuote:Te,prepareSendQuote:Ee,setAmount:De,handleSubmit:Oe,isSubmitting:ke,buttonText:Ae,isValidRecipient:je,processedFeeOptions:Me,selectedFeeOption:Ne,setSelectedFeeOption:Pe,quoteError:Fe,quoteErrorPrettified:Ie}=nE({account:_e,fromAmount:j?ne:``,toRecipient:j&&me?me:void 0,toChainId:V,toToken:B?.address??B?.symbol,actions:fe,walletClient:t,onTransactionStateChange:n,onError:r,onWaitingForWalletConfirm:i,onSend:s,onConfirm:a,onComplete:o,selectedToken:T,setWalletConfirmRetryHandler:c,tradeType:ln.EXACT_INPUT,swapProvider:l,bridgeProvider:u,swapProviderFallback:d,bridgeProviderFallback:f,fundMethod:p,mode:b,checkoutOnHandlers:m,skipFeeBalanceFetch:p===`onramp-meld`||p===`direct-transfer`||p===`onramp-mesh`}),Le=J(()=>ET(Ee?.destinationAmountFormatted??``,oe),[Ee?.destinationAmountFormatted,oe]),Re=j&&(Fe||Ie)?`Something went wrong. Please try again.`:null;q(()=>{C||!T&&!A&&k&&E(k)},[T,A,k,E,C]),q(()=>{ie.current&&ie.current.focus()},[]),q(()=>{v?.(N||F||ee)},[N,F,ee,v]);let ze=e=>{re(e),j&&De(e)},Be=e=>{M(e),P(!1)},Ve=e=>{re(e),j&&De(e)},He=e=>{E(e),I(!1),_?.(e)};if(ee)return Z(cb,{extraChains:ae,onChainSelect:z,onBack:()=>{te(!1),I(!0)}});if(N)return Z(pE,{amount:ne,onBack:()=>P(!1),onMarketSelect:Be});if(F)return Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>I(!1),headerContent:`Select Token`,headerContentAlign:`left`,customActions:Z(lb,{onError:r,fundMethod:p})}),Z(ib,{onTokenSelect:He,onError:r,fundMethod:p,showContinueButton:!1,compactMode:!1,recentTokens:h,onRecentTokenSelect:g,allSupportedTokens:!1,includeSolanaChainFilter:!!R||!!L,chainListScreen:!0,onNavigateToChainList:()=>{I(!1),te(!0)}})]});let Ue=Rl({originToken:D??T,originTokenBalance:D?.balance??T?.balance,originTokenAmount:ne,isLoadingBalance:O}),We=!!Ne&&!!Ue&&Bl(Ne,Ue);return Q(`div`,{className:`space-y-2`,children:[Q(`div`,{className:`pt-4 pb-4 trails-bg-secondary trails-bg-secondary-hover trails-border-radius-container p-3 group transition-all duration-200 border border-transparent focus-within:bg-white! dark:focus-within:bg-gray-800! trails-focus-border-secondary min-h-[120px] flex flex-col`,children:[Q(`div`,{className:`mb-4 flex justify-between items-center`,children:[Z(`div`,{className:`text-sm font-medium trails-text-secondary text-left m-0`,children:`You pay with`}),Z(hE,{})]}),Q(`div`,{className:`flex items-center space-x-2 flex-1`,children:[Z(`div`,{className:`flex-1`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Z(pb,{ref:ie,value:ne,onChange:e=>ze(e.target.value),isLoading:Te,variant:`default`}),Te&&Z(Tw,{})]})}),Z(`div`,{className:`relative`,children:Z(gE,{token:T,chainId:T?.chainId,onSelect:()=>I(!0)})})]}),Q(`div`,{className:`mt-4 flex justify-between items-center`,children:[T?.symbol&&Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,title:Ee?.originAmountUsdDisplay||void 0,children:Q(`span`,{className:`notranslate`,translate:`no`,children:[`≈`,` `,Ee?.originAmountUsdLocaleDisplay||Ee?.originAmountUsdDisplay||qs(0)]})}),T&&p!==`direct-transfer`&&p!==`onramp-mesh`&&Q(`div`,{className:`flex items-center space-x-2`,children:[Z(`button`,{type:`button`,className:`text-xs text-gray-500 dark:text-gray-400 cursor-pointer hover:text-gray-700 dark:hover:text-gray-200 transition-colors bg-transparent border-none p-0`,onClick:()=>Ve(xe||`0`),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),Ve(xe||`0`))},title:`Click to use full balance`,disabled:!xe,children:Q(`span`,{className:`notranslate`,translate:`no`,children:[`Balance:`,` `,w?D?.balanceLocaleDisplay||T?.balanceLocaleDisplay||Ce||xe||`0.00`:`••••••`]})}),xe&&Z(vT,{userBalance:xe,userBalanceRaw:Se,decimals:we,isNativeToken:T.isNativeToken??!1,gasCostFormatted:Ee?.gasCostFormatted,chainId:T.chainId,onAmountSelect:Ve,className:`opacity-100`})]})]})]}),Z(`div`,{className:`relative z-10 pointer-events-none`,children:Z(`button`,{type:`button`,className:`absolute left-1/2 top-1/2 z-20 transform -translate-x-1/2 -translate-y-1/2 p-1.5 trails-border-radius-button trails-bg-tertiary hover:trails-hover-bg transition-colors cursor-pointer border-2 border-white dark:border-gray-800 pointer-events-auto`,children:Z(yi,{className:`w-5 h-5 text-gray-900 dark:text-white`,strokeWidth:2.5})})}),Z(`div`,{className:`mb-4 trails-bg-secondary trails-border-radius-container transition-all duration-200 border border-gray-300 dark:border-gray-600 hover:bg-white! dark:hover:bg-white! hover:border-gray-400 dark:hover:border-gray-500`,children:j&&B?Z(`div`,{title:`Select Market`,className:`w-full overflow-hidden px-4 py-4 text-left trails-border-radius-container trails-bg-secondary transition-all`,children:Q(`div`,{children:[Z(`div`,{className:`flex justify-between items-center mb-4`,children:Z(`div`,{className:`text-sm font-semibold trails-text-secondary text-left`,children:`Market`})}),Q(`div`,{className:`flex items-center justify-between gap-4`,children:[Q(`div`,{className:`flex items-center gap-5 min-w-0`,children:[le?Z(`a`,{href:le,target:`_blank`,rel:`noopener noreferrer`,title:`View ${B.symbol} on explorer`,onClick:e=>e.stopPropagation(),className:`flex-shrink-0 rounded-full transition-transform hover:scale-105`,children:Z(Jy,{symbol:B.symbol,imageUrl:B.logoURI,chainId:V,contractAddress:B.address,size:34})}):Z(Jy,{symbol:B.symbol,imageUrl:B.logoURI,chainId:V,contractAddress:B.address,size:34}),Q(`div`,{className:`min-w-0`,children:[ue?Z(`a`,{href:ue,target:`_blank`,rel:`noopener noreferrer`,onClick:e=>e.stopPropagation(),className:`block font-semibold text-gray-900 dark:text-white text-sm truncate transition-colors hover:text-blue-600 dark:hover:text-blue-400`,children:j.metadata.name}):Z(`h3`,{className:`font-semibold text-gray-900 dark:text-white text-sm truncate`,children:j.metadata.name}),Q(`div`,{className:`mt-1 flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400 truncate`,children:[U?.logoURI&&Z(`img`,{src:U.logoURI,alt:``,className:`h-3.5 w-3.5 rounded-full object-contain`,loading:`lazy`}),ue?Z(`a`,{href:ue,target:`_blank`,rel:`noopener noreferrer`,onClick:e=>e.stopPropagation(),className:`truncate transition-colors hover:text-blue-600 dark:hover:text-blue-400`,children:U?.name??j.providerId}):Z(`span`,{className:`truncate`,children:U?.name??j.providerId})]})]})]}),Q(`button`,{type:`button`,title:`Select Market`,onClick:()=>P(!0),className:`flex items-center space-x-3 flex-shrink-0 rounded-lg p-1 transition-colors hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer`,children:[Q(`div`,{className:`text-right`,children:[Z(`div`,{className:`flex items-center justify-end space-x-1 text-green-600 dark:text-green-400 mb-1 whitespace-nowrap`,children:Q(`span`,{className:`font-semibold text-sm`,children:[oe.toFixed(2),`% APY`]})}),Q(`p`,{className:`text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap`,children:[`TVL:`,` `,H===null?`-`:rc(H)]})]}),Z(ki,{className:`w-4 h-4 text-gray-400`})]})]}),Ee&&Le!==null&&Q(`div`,{className:`mt-4 flex items-center justify-between border-t border-gray-200 pt-3 dark:border-gray-700 trails-fade-slide-in-fast`,children:[Z(`span`,{className:`text-xs font-medium text-gray-500 dark:text-gray-400`,children:`To earn`}),Q(`span`,{className:`text-sm font-semibold text-green-600 dark:text-green-400 trails-fade-slide-in-fast`,children:[`+`,_E(Le),`/mo`]},Le)]})]})}):Z(`button`,{type:`button`,onClick:()=>P(!0),className:`w-full py-6 px-4 trails-list-item trails-border-radius-container transition-all duration-200 cursor-pointer`,children:Q(`div`,{className:`flex items-center justify-between`,children:[Q(`div`,{className:`flex items-center space-x-3 flex-1`,children:[Z(`div`,{className:`w-8 h-8 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center`,children:Z(qi,{className:`w-4 h-4 text-gray-400`})}),Z(`div`,{className:`text-left flex-1`,children:Z(`div`,{className:`font-semibold text-gray-900 dark:text-white text-sm`,children:`Select market to earn yield with`})})]}),Z(ki,{className:`w-4 h-4 trails-text-muted flex-shrink-0`})]})})}),p!==`direct-transfer`&&p!==`onramp-mesh`&&Z(mE,{processedFeeOptions:Me,selectedFeeOption:Ne,setSelectedFeeOption:Pe,chainId:T?.chainId,isRefetching:Te,originTokenInfo:Ue}),Ee&&Z(`div`,{className:`mb-4`,children:Z(wb,{quote:Ee,showContent:!0,isRefetching:Te})}),he?Z(`div`,{className:`mb-4 rounded-2xl border border-solid border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm font-medium text-amber-600 dark:text-amber-400`,children:he}):be?Z(`div`,{className:`mb-4 rounded-2xl border border-solid border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm font-medium text-amber-600 dark:text-amber-400`,children:be}):Re?Z(`div`,{className:`mb-4 rounded-2xl bg-gray-200 px-4 py-3 text-center text-sm font-semibold text-gray-600 dark:bg-gray-700 dark:text-gray-300`,children:Re}):null,Z(`form`,{onSubmit:Oe,children:Z(`button`,{type:`submit`,disabled:!ne||!je||!!he||ve||ye||ge||ke||!T||!j||!B||!de||Te||!Ee||p!==`direct-transfer`&&Ee?.noSufficientBalance||p!==`direct-transfer`&&We,className:`w-full font-semibold py-4 px-4 trails-border-radius-button transition-colors bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white disabled:text-gray-500 disabled:cursor-not-allowed cursor-pointer relative`,children:ke?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:Ae})]}):j?he?`Invalid recipient`:ge?`Checking recipient...`:ve?`Connect EVM wallet`:ye?`Set recipient`:p!==`direct-transfer`&&Ee?.noSufficientBalance?`Insufficient Balance`:Ae||`Deposit`:`Select Market`})})]})},yE=({onBack:e,account:t,walletClient:n,onTransactionStateChange:r,onError:i,onWaitingForWalletConfirm:a,onConfirm:o,onComplete:s,onSend:c,setWalletConfirmRetryHandler:l,swapProvider:u,bridgeProvider:d,swapProviderFallback:f,bridgeProviderFallback:p,fundMethod:m,checkoutOnHandlers:h,recentTokens:g,onRecentTokenSelect:_,onTrackToken:v})=>{let[y,b]=X(`deposit`),[x,S]=X(!1),{navigate:C}=y_(),{enterFormMode:w}=d_();return q(()=>{w(`earn`)},[]),Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:e,headerContent:`Earn`,headerContentAlign:`left`,showAccountActions:!0,customActions:Q(`button`,{type:`button`,onClick:()=>C(`swap`,{backTarget:`earn`}),className:`flex h-8 px-3 justify-center items-center gap-1.5 rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600`,title:`Swap`,children:[Z(xi,{className:`h-4 w-4`}),Z(`span`,{className:`text-sm font-medium`,children:`Swap`})]})}),!x&&Q(`div`,{className:`flex justify-start space-x-2`,children:[Q(`button`,{type:`button`,onClick:()=>b(`deposit`),className:`flex items-center space-x-2 py-2 px-4 text-xs font-bold cursor-pointer trails-border-radius-input ${y===`deposit`?`trails-bg-secondary text-blue-500`:`trails-text-secondary`}`,children:[Z(bi,{className:`w-4 h-4`}),Z(`span`,{children:`Deposit`})]}),Q(`button`,{type:`button`,onClick:()=>b(`withdraw`),className:`flex items-center space-x-2 py-2 px-4 text-xs font-bold cursor-pointer trails-border-radius-input ${y===`withdraw`?`trails-bg-secondary text-blue-500`:`trails-text-secondary`}`,children:[Z(Ci,{className:`w-4 h-4`}),Z(`span`,{children:`Withdraw`})]})]}),y===`deposit`?Z(vE,{account:t,walletClient:n,onTransactionStateChange:r,onError:i,onWaitingForWalletConfirm:a,onConfirm:o,onComplete:s,onSend:c,setWalletConfirmRetryHandler:l,swapProvider:u,bridgeProvider:d,swapProviderFallback:f,bridgeProviderFallback:p,fundMethod:m,checkoutOnHandlers:h,recentTokens:g,onRecentTokenSelect:_,onTrackToken:v,onPoolSelectorStateChange:S}):Z(WT,{account:t,walletClient:n,onTransactionStateChange:r,onError:i,onComplete:s,onPoolSelectorStateChange:S})]})};function bE(e,t,n){return!t||n&&!n.has(e.chainId)?!0:t.some(t=>t.chainId===e.chainId?e.token?.address?St(t.contractAddress)===St(e.token.address):t.symbol.toLowerCase()===e.token?.symbol?.toLowerCase():!1)}const xE=({onBack:e,onPoolSelect:t})=>{let{data:n,loading:r,error:i}=qS(),{address:a}=Kr(),{sortedTokens:o}=Q_(a&&bn(a)?a:null,void 0,{refetchInterval:J_}),[c,l]=X(`all`),[u,d]=X(``),[f,p]=X(null),[m,h]=X(`tvl`),[g,_]=X(!1),{selectedChainId:v,setSelectedChainId:y}=mu(),{availableDestinationChainIds:b,availableDestinationTokens:x,availableDestinationTokenRestrictedChainIds:S}=xl(),C=J(()=>b?new Set(b):null,[b]),w=J(()=>S?new Set(S):null,[S]);q(()=>{if(v!==null&&C&&!C.has(v)){y(null),p(null);return}v!==f&&p(v)},[C,f,v,y]);let T=e=>{p(e),y(e)},E=J(()=>{if(!n||!Array.isArray(n))return[`all`];try{let e=new Set(n.map(e=>e.protocol).filter(Boolean));return[`all`,...Array.from(e).sort((e,t)=>e.localeCompare(t))]}catch(e){return s.console.error(`[trails-sdk] Error computing protocols:`,e),[`all`]}},[n]),D=J(()=>{if(!n||!Array.isArray(n))return[];try{let e=new Set(n.map(e=>e.chainId).filter(e=>!!e&&(!C||C.has(e))));return Array.from(e).map(e=>({chainId:e,name:$(e)?.name??``})).sort((e,t)=>e.name.localeCompare(t.name)).filter(e=>e.name)}catch(e){return s.console.error(`[trails-sdk] Error computing unique chains:`,e),[]}},[C,n]),O=J(()=>{let e=new Map;return o&&Array.isArray(o)&&o.forEach(t=>{let n=`${St(t.contractAddress)}-${t.chainId}`;e.set(n,t)}),e},[o]),k=J(()=>!n||!Array.isArray(n)?[]:n.filter(e=>{try{if(!e.isActive)return!1;let t=c===`all`||e.protocol?.toLowerCase()===c?.toLowerCase();if(C&&!C.has(e.chainId)||x&&!bE(e,x,w))return!1;let n=f===null||e.chainId===f,r=u.trim().toLowerCase().split(/\s+/).filter(e=>e.length>0),i=!u.trim()||r.every(t=>e.token?.symbol?.toLowerCase().includes(t)||e.token?.name?.toLowerCase().includes(t)||e.protocol?.toLowerCase().includes(t)||$(e.chainId)?.name?.toLowerCase().includes(t));return t&&n&&i}catch(t){return s.console.error(`[trails-sdk] Error filtering pool:`,e,t),!1}}).map(e=>{let t=`${St(e.depositAddress)}-${e.chainId}`,n=O.get(t),r=n?.balanceUsd||0;return n?.balanceFormatted&&n?.priceUsd&&(r=parseFloat(n.balanceFormatted)*n.priceUsd),{...e,userBalance:n?.balance,userBalanceUsd:r,userBalanceFormatted:n?.balanceFormatted,userBalanceDisplay:n?.balanceDisplay,userTokenSymbol:n?.symbol}}).sort((e,t)=>{try{let n=e.userBalanceFormatted&&parseFloat(e.userBalanceFormatted)>0,r=t.userBalanceFormatted&&parseFloat(t.userBalanceFormatted)>0;if(n&&!r)return-1;if(!n&&r)return 1;if(n&&r){if(e.userBalanceUsd>0&&t.userBalanceUsd>0)return t.userBalanceUsd-e.userBalanceUsd;let n=parseFloat(e.userBalanceFormatted||`0`);return parseFloat(t.userBalanceFormatted||`0`)-n}return m===`tvl`?(t.tvl||0)-(e.tvl||0):m===`apy`?(t.apy||0)-(e.apy||0):0}catch(e){return s.console.error(`[trails-sdk] Error sorting pools:`,e),0}}),[n,c,f,u,m,O,C,x,w]),A=J(()=>k.filter(e=>e.userBalanceFormatted&&parseFloat(e.userBalanceFormatted)>0),[k]),j=J(()=>k.filter(e=>!e.userBalanceFormatted||parseFloat(e.userBalanceFormatted)===0),[k]),M=e=>Z(`button`,{type:`button`,onClick:()=>t(e),className:`w-full p-4 trails-border-radius-container trails-list-item cursor-pointer transition-all overflow-hidden active:scale-[0.99] text-left`,children:Q(`div`,{className:`flex items-center justify-between`,children:[Q(`div`,{className:`flex items-center space-x-3`,children:[Z(`div`,{style:{width:`32px`,height:`32px`},children:Z(Jy,{symbol:e.token.symbol,imageUrl:e.token.logoUrl,chainId:e.chainId,size:32})}),Q(`div`,{children:[Z(`h3`,{className:`font-medium text-gray-900 dark:text-white text-sm`,children:e.name}),Z(`div`,{className:`flex items-center space-x-1`,children:Q(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 flex items-center`,children:[e.protocol===`Aave`&&Z(rE,{"aria-label":`Aave`,className:`w-3 h-3 mr-1`}),e.protocol===`Morpho`&&Z(oE,{"aria-label":`Morpho`,className:`w-3 h-3 mr-1`}),e.protocol]})})]})]}),Q(`div`,{className:`text-right`,children:[Q(`div`,{className:`flex items-center justify-end space-x-1 text-green-600 dark:text-green-400 mb-1 whitespace-nowrap`,children:[Z($i,{className:`w-3 h-3`}),Q(`span`,{className:`font-semibold text-sm`,children:[e.apy.toFixed(1),`% APY`]})]}),Q(`p`,{className:`text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap`,children:[`TVL: `,rc(e.tvl)]}),e.userBalanceFormatted&&parseFloat(e.userBalanceFormatted)>0&&Q(`p`,{className:`text-xs font-bold mt-1 whitespace-nowrap notranslate`,style:{color:`#71717A`},translate:`no`,children:[`Balance:`,` `,e.userBalanceUsd>0?qs(e.userBalanceUsd):e.userBalanceDisplay||e.userBalanceFormatted]})]})]})},e.id);return g?Z(cb,{onBack:()=>_(!1),chains:D}):Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:e,headerContent:`Select Vault`,headerContentAlign:`left`}),Z(Xy,{value:u,onChange:e=>{try{d(e||``)}catch(e){s.console.error(`[trails-sdk] Error updating search filter:`,e),d(``)}},placeholder:`Filter vaults`,autoFocus:!0,className:`mb-4`,rightAlignedComponent:Z(Oy,{chains:D,selectedChainId:f,onChainSelect:T,chainListScreen:!0,onNavigateToChainList:()=>_(!0)})}),!r&&Z(sE,{protocols:E,selectedProtocol:c,onProtocolChange:l,sortBy:m,onSortChange:h}),Z(`div`,{className:`flex-1 overflow-y-auto overflow-x-hidden space-y-3 max-h-[250px] trails-scrollbar`,children:r?Q(`div`,{className:`flex flex-col items-center justify-center py-8 space-y-4`,children:[Z(`div`,{className:`animate-spin rounded-full h-8 w-8 border-solid border-b-2 border-blue-500`}),Z(`p`,{className:`text-gray-600 dark:text-gray-400`,children:`Loading vaults...`})]}):i?Z(`div`,{className:`flex flex-col items-center justify-center py-8 space-y-4`,children:Q(`div`,{className:`text-red-500 text-center`,children:[Z(`p`,{className:`text-sm`,children:`Failed to load pools`}),Z(`p`,{className:`text-xs text-gray-500 mt-1`,children:`Please try again later`})]})}):k.length===0?Z(`div`,{className:`text-center py-8`,children:Z(`p`,{className:`text-gray-500 dark:text-gray-400 text-sm`,children:`No pools available for the selected protocol`})}):Q(hi,{children:[A.length>0&&Q(hi,{children:[Z(`div`,{className:`px-2 py-1`,children:Z(`p`,{className:`text-xs font-semibold text-gray-600 dark:text-gray-400 tracking-wider`,children:`My Vaults`})}),A.map(M)]}),j.length>0&&Q(hi,{children:[Z(`div`,{className:`px-2 py-1 ${A.length>0?`mt-4`:``}`,children:Z(`p`,{className:`text-xs font-semibold text-gray-600 dark:text-gray-400 tracking-wider`,children:A.length>0?`Other Vaults`:`Available Vaults`})}),j.map(M)]})]})})]})},SE=({className:e=``})=>{let{toast:t=!1,toAddress:n,toAmount:r,toToken:i,toCalldata:a}=wo(),{targetAmountUsdFormatted:o}=KT(),c=Vx(),{selectedCurrency:l}=Ru(),u=Rs.getRate();s.console.log(`[trails-sdk] Config from context:`,c);let d=c.debug||pe(`debug`)===`true`,f=$(Kn.id)?.rpcUrls?.default?.http?.[0]||`N/A`,p=(e,t=30)=>e.length<=t?e:`${e.substring(0,t)}...`,m=[{label:`SDK Version`,value:b,display:b},{label:`API URL`,value:c.trailsApiUrl,display:p(c.trailsApiUrl||`N/A`)},{label:`App URL`,value:c.trailsAppUrl,display:p(c.trailsAppUrl||`N/A`)},{label:`Indexer URL`,value:c.sequenceIndexerUrl,display:p(c.sequenceIndexerUrl||`N/A`)},{label:`RPC Node URL (1)`,value:f,display:p(f)},{label:`Trails API Key`,value:c.trailsApiKey,display:p(c.trailsApiKey||`N/A`)},{label:`WalletConnect Project ID`,value:p(c.walletConnectProjectId||`N/A`),display:p(c.walletConnectProjectId||`N/A`)},{label:`Slippage Tolerance`,value:`${c.slippageTolerance}%`},{label:`Debug Mode`,value:d?`Enabled`:`Disabled`},{label:`Toast Notifications`,value:t?`Enabled`:`Disabled`},{label:`Display Currency`,value:l||`USD`,display:l||`USD`},{label:`Forex Rate`,value:u?`1 USD = ${u.rate.toFixed(4)} ${u.currency}`:`N/A`,display:u?`1 USD = ${u.rate.toFixed(4)} ${u.currency}`:`N/A`},{label:`Target Amount USD`,value:o||`N/A`,display:o||`N/A`},{label:`To Address`,value:n||`N/A`,display:n?p(n,20):`N/A`},{label:`To Amount`,value:r||`N/A`,display:r||`N/A`},{label:`To Token`,value:i||`N/A`,display:i?p(i,20):`N/A`},{label:`To Calldata`,value:a||`N/A`,display:a?p(a,20):`N/A`}];return Q(`div`,{className:`p-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800 ${e}`,children:[Z(`div`,{className:`text-xs font-medium text-gray-600 dark:text-gray-400 mb-2`,children:`Configuration`}),Z(`div`,{className:`space-y-1`,children:m.map(e=>Q(`div`,{className:`flex justify-between items-center text-xs`,children:[Q(`span`,{className:`text-gray-500 dark:text-gray-500 font-medium`,children:[e.label,`:`]}),Z(`span`,{className:`text-gray-700 dark:text-gray-300 font-mono ml-2 truncate max-w-[150px]`,title:e.value,children:e.display||e.value})]},e.label))})]})},CE=`Connect.Fund Methods.Meld Onramp.Mesh Connect.Wallet Connect.Wallet List.Wallet Connection Pending.Wallet Connection Pending Retry.Tokens.Chain List.Send Form.Fund Form.Recipients.Earn.Earn Pools.Swap.Wallet Confirmation.Wallet Confirmation Retry.Pending 1-item-0-confirmed.Pending 1-item-1-confirmed.Pending 2-item-0-confirmed.Pending 2-item-1-confirmed.Pending 2-item-2-confirmed.Pending 3-item-0-confirmed.Pending 3-item-1-confirmed.Pending 3-item-2-confirmed.Pending 3-item-3-confirmed.Pending 3-item-2-confirmed-with-error.Receipt.Receipt Failed.Receipt Refunded.Account History.Account Settings.User Preferences`.split(`.`),wE=({onScreenSelect:e})=>Q(`div`,{children:[Z(`div`,{className:`px-3 py-2 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800`,children:Z(`div`,{className:`text-xs font-medium text-gray-600 dark:text-gray-400 mb-1`,children:`Debug Screens`})}),Z(`div`,{className:`max-h-[200px] overflow-y-auto`,children:CE.map(t=>Z(`button`,{type:`button`,onClick:()=>{e(t?.toLowerCase().replaceAll(` `,`-`))},className:`w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 dark:text-gray-200 dark:hover:bg-gray-700 cursor-pointer`,children:t},t))})]}),TE=()=>{let{showToast:e}=Go();return Z(`div`,{className:`p-3 border-b border-gray-200 dark:border-gray-700`,children:Q(`div`,{className:`flex items-center gap-2`,children:[Z(`div`,{className:`text-xs font-semibold text-gray-600 dark:text-gray-400`,children:`Toast`}),Q(`div`,{className:`flex gap-1 flex-1`,children:[Z(`button`,{type:`button`,onClick:()=>{e(`Info Toast`,`This is an info message for testing purposes`,`info`)},className:`px-2 py-1 text-xs font-medium rounded bg-blue-100 text-blue-700 hover:bg-blue-200 dark:bg-blue-900/30 dark:text-blue-400 dark:hover:bg-blue-900/50 transition-colors cursor-pointer`,children:`info`}),Z(`button`,{type:`button`,onClick:()=>{e(`Transaction Complete`,`Your transaction has been successfully processed`,`success`)},className:`px-2 py-1 text-xs font-medium rounded bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50 transition-colors cursor-pointer`,children:`success`}),Z(`button`,{type:`button`,onClick:()=>{e(`Transaction Failed`,`An error occurred while processing your transaction`,`error`)},className:`px-2 py-1 text-xs font-medium rounded bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50 transition-colors cursor-pointer`,children:`error`})]})]})})},EE=({onScreenSelect:e})=>{let[t,n]=X(!1),r=Y(null),{debug:i}=Vx();return i?Q(`div`,{className:`relative z-50`,ref:r,children:[Z(`button`,{type:`button`,onClick:()=>n(!t),className:`p-1 rounded-full hover:bg-opacity-10 hover:bg-gray-50 text-gray-900 dark:hover:bg-gray-800 dark:text-gray-200`,title:`Open debug menu`,children:Z(Di,{className:`w-4 h-4`})}),t&&Q(`div`,{className:`absolute bottom-full right-0 mb-1 w-80 border border-solid rounded-lg shadow-lg overflow-hidden max-h-[400px] overflow-y-auto custom-scrollbar bg-white border-gray-200 text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-200 z-50`,children:[Z(wE,{onScreenSelect:t=>{e?.(t),n(!1)}}),Z(TE,{}),Z(SE,{})]})]}):null},DE=({onDebugScreenSelect:e})=>{let{trackClick:n}=k_();return Q(`div`,{className:`mt-auto pt-2 text-center text-xs relative flex items-center justify-center text-gray-400 dark:text-gray-500 trails-fade-slide-in-fast`,children:[Q(`div`,{className:`absolute right-0 flex items-center h-full`,children:[Q(`span`,{className:`text-[9px] opacity-15 mr-1.5 select-none`,children:[`v`,b]}),Z(EE,{onScreenSelect:e})]}),Q(`span`,{className:`inline-flex items-center gap-1`,children:[Z(`span`,{className:`inline-flex h-[12px] items-center text-[12px] leading-none`,children:`Powered by`}),Z(`span`,{className:`text-black inline-flex h-[12px] items-center text-[12px] leading-none font-medium dark:text-white`,children:`Polygon`}),Q(`a`,{href:t,target:`_blank`,rel:`noopener noreferrer`,title:`Visit the Trails website`,onClick:()=>{n({component:`Footer`,action:`click_trails_logo`,label:`powered_by_trails`,metadata:{destination:t,version:b}})},className:`inline-flex h-[12px] items-center font-medium leading-none text-gray-400 transition-colors hover:opacity-80 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300`,children:[Z(A,{"aria-label":`Trails`,className:`h-[12px] w-auto dark:hidden`}),Z(I,{"aria-label":`Trails`,className:`h-[12px] w-auto hidden dark:inline-block`})]})]})]})};function OE(e){let{address:t}=Kr(),{supportedTokens:n,isLoadingTokens:r}=Rc({disabled:!e}),{sortedTokens:i,isLoadingSortedTokens:a}=Q_(e?t:null,void 0,{refetchInterval:!1}),o=r||a,c=Y(null),l=Y(``);return{defaultDestinationToken:J(()=>{if(!e||!n?.length||!i?.length)return c.current=null,null;let t=`${e.symbol}-${e.chainId}-${e.contractAddress||`native`}`;if(!(t!==l.current||!c.current)&&c.current)return c.current;l.current=t;let r=e.chainId===Mn.id?Tn.id:Mn.id,a=n.find(e=>e.chainId===r&&e.symbol===`USDC`),o=null;if(a)o=a,s.console.log(`[trails-sdk] Selected USDC as destination token on chain:`,r);else{let t=n.filter(e=>e.chainId===r),i=t.find(t=>t.symbol.toUpperCase()===e.symbol.toUpperCase());i?(o=i,s.console.log(`[trails-sdk] Selected same symbol token on destination chain:`,i.symbol)):(o=t.find(e=>e.symbol===`ETH`)||t[0]||null,o&&s.console.log(`[trails-sdk] Selected fallback token on destination chain:`,o.symbol))}if(!o)return s.console.log(`[trails-sdk] No suitable destination token found on chain:`,r),null;let u=o.decimals;if(!u)return s.console.warn(`[trails-sdk] Missing decimals for destination token, skipping:`,o),null;let d=i.find(e=>{if(e.chainId!==o.chainId)return!1;let t=o.isNativeToken??!1,n=e.isNativeToken??!1;return t&&n?!0:t||n?!1:e.contractAddress?.toLowerCase()===o.contractAddress?.toLowerCase()}),f={...o,balance:d?.balance??`0`,balanceUsdFormatted:d?.balanceUsdFormatted??`0`,priceUsd:d?.priceUsd??0,decimals:u};return s.console.log(`[trails-sdk] Default destination token selection:`,{destination:{symbol:f.symbol,chainId:f.chainId,hasUserBalance:!!d,userBalanceUsd:d?.balanceUsdFormatted??`0`},originChain:e.chainId,destinationChain:r}),c.current=f,f},[e,n,i]),isLoading:o}}function kE(e){let{trailsClient:t,countryCode:n,enabled:r=!0}=e,i=gv(),a=!r||!n||t!==void 0&&!t?null:n,o=t===void 0?i:t,{data:s=[],isLoading:c,error:l}=Or(PS.fiatCurrencyList(o,a));return{fiatCurrencies:s,isLoading:c,error:l}}function AE(){let e=gv(),t=Dr({mutationFn:async t=>{let{trailsClient:n,depositAddress:r,userAddress:i,countryCode:a,sourceCurrencyCode:o,sourceAmount:c,destinationCurrencyCode:l,serviceProvider:u,redirectUrl:d,paymentMethodType:f,lockFields:p}=t,m=Date.now(),h=Math.random().toString(36).substring(2,8),g=St(i),_={sessionData:{walletAddress:r,countryCode:a,sourceCurrencyCode:o,sourceAmount:c,destinationCurrencyCode:l,serviceProvider:u,paymentMethodType:f,...d&&{redirectUrl:d},...p&&{lockFields:p}},sessionType:`BUY`,externalCustomerId:St(g),externalSessionId:`meld-${m}-${h}`};s.console.log(`[useOnRampProviderWidget] Creating widget session`,_);let v=await(n||e).createMeldWidgetSession(_);s.console.log(`[useOnRampProviderWidget] Raw response`,v),s.console.log(`[useOnRampProviderWidget] Request externalSessionId:`,_.externalSessionId);let y;if(v.widgetSession&&typeof v.widgetSession==`string`){if(v.widgetSession===`undefined`)throw Error(`No widget session response received from server`);try{let e=JSON.parse(v.widgetSession);y=e.WidgetSession||e.widgetSession||e}catch(e){throw s.console.error(`[useOnRampProviderWidget] Failed to parse widget session JSON:`,e,`Raw response:`,v.widgetSession),Error(`Invalid widget session format`,{cause:e})}}else if(v.WidgetSession)y=v.WidgetSession;else if(v.widgetSession&&typeof v.widgetSession==`object`)y=v.widgetSession;else throw Error(`No valid widget session found in server response`);let b=y,{selectedWidgetUrl:x,meldWidgetUrl:S,serviceProviderWidgetUrl:C,fallbackUrl:w,isTransakProvider:T}=Bw({serviceProvider:u,widgetUrl:b?.widgetUrl,serviceProviderWidgetUrl:b?.serviceProviderWidgetUrl,fallbackUrl:b?.url});if(!b||!x)throw Error(`Invalid response: widgetSession.widgetUrl or serviceProviderWidgetUrl not found in response`);return s.console.log(`[useOnRampProviderWidget] Widget session created`,{id:b.id,externalSessionId:b.externalSessionId,externalCustomerId:b.externalCustomerId,customerId:b.customerId,token:b.token,widgetUrl:S,serviceProviderWidgetUrl:C,fallbackUrl:w,isTransakProvider:T,selectedWidgetUrl:x}),s.console.log(`[useOnRampProviderWidget] Response externalSessionId:`,b.externalSessionId),{id:b.id,externalSessionId:b.externalSessionId,externalCustomerId:b.externalCustomerId,customerId:b.customerId,token:b.token,widgetUrl:x}},onError:e=>{s.console.error(`[useOnRampProviderWidget] Error creating widget session`,e)},retry:1});return{createWidgetSession:t.mutateAsync,isLoading:t.isPending,error:t.error}}function jE(e){let{trailsClient:t,amount:n,sourceCurrencyCode:r,destinationCurrencyCode:i,countryCode:o,walletAddress:c,paymentMethodType:l,enabled:u=!0}=e,d=gv({}),f=J(()=>Ss(n??``)&&!!r&&!!i&&!!o&&!!c,[n,r,i,o,c]),{data:p=[],isLoading:m,error:h,refetch:g}=Or({queryKey:[`meldQuote`,n,r,i,o,c,`onrampClient`],queryFn:async()=>{if(!f)throw Error(`All required parameters must be provided`);let e=Date.now();xf({sourceAmount:n,sourceCurrencyCode:r,destinationCurrencyCode:i,countryCode:o,walletAddress:c}),s.console.log(`[useOnRampQuote] Fetching onramp quotes`,{amount:n,sourceCurrencyCode:r,destinationCurrencyCode:i,countryCode:o,walletAddress:c});let u=t||d,p;try{p=await u.getMeldQuote({sourceAmount:n,sourceCurrencyCode:r,destinationCurrencyCode:i,countryCode:o,walletAddress:c,paymentMethodType:l})}catch(t){let s=Date.now()-e;throw Cf({error:a(t),sourceAmount:n,sourceCurrencyCode:r,destinationCurrencyCode:i,countryCode:o,walletAddress:c,responseTime:s}),t}s.console.log(`[useOnRampQuote] GetMeldQuote response`,p),s.console.log(`[useOnRampQuote] Response structure analysis:`,{hasQuoteResponse:!!p.quoteResponse,quoteResponseType:typeof p.quoteResponse,hasQuoteResponseCap:!!p.QuoteResponse,quoteResponseCapType:typeof p.QuoteResponse,dataKeys:Object.keys(p)});let m;if(p.quoteResponse&&typeof p.quoteResponse==`string`){if(p.quoteResponse===`undefined`)throw Error(`No quote response received from server`);try{let e=JSON.parse(p.quoteResponse);m=e.QuoteResponse||e}catch(e){throw s.console.error(`[useOnRampQuote] Failed to parse quote response JSON:`,e,`Raw response:`,p.quoteResponse),Error(`Invalid quote response format`,{cause:e})}}else if(p.QuoteResponse)m=p.QuoteResponse;else if(p.quoteResponse&&typeof p.quoteResponse==`object`)m=p.quoteResponse;else throw Error(`No valid quote response found in server response`);s.console.log(`[useOnRampQuote] Final quoteResponse:`,m);let h=[];m&&typeof m==`object`&&m&&`quotes`in m&&Array.isArray(m.quotes)?(h=m.quotes,s.console.log(`[useOnRampQuote] Found quotes array with length:`,h.length)):s.console.log(`[useOnRampQuote] No quotes array found. quoteResponse structure:`,m),s.console.log(`[useOnRampQuote] Quotes received`,{count:h.length,selectedQuote:h[0]?{destinationAmount:h[0].destinationAmount,serviceProvider:h[0].serviceProvider,exchangeRate:h[0].exchangeRate}:null});let g=Date.now()-e;return h.length>0&&h.forEach((e,t)=>{e&&Sf({provider:e.serviceProvider||`Meld`,sourceAmount:n,sourceCurrencyCode:r,destinationAmount:String(e.destinationAmount||``),destinationCurrencyCode:i,exchangeRate:String(e.exchangeRate||``),networkFees:String(e.networkFee||``),transactionFee:String(e.transactionFee||``),totalFees:String(e.totalFee||``),countryCode:o,paymentMethod:e.paymentMethodType||``,quotesCount:h.length,responseTime:g,walletAddress:c,institutionName:e.institutionName||void 0,customerScore:String(e.customerScore||``),quoteIndex:String(t),isSelectedQuote:String(t===0)})}),h=h.filter(e=>e.serviceProvider?.toLowerCase()!==`kryptonim`),h},enabled:!u||t!==void 0&&!t?!1:f,staleTime:30*Ee,gcTime:2*ge,retry:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}),_=p[0]??null;return{quotes:p,selectedQuote:_,isLoading:m,error:h,refetch:async()=>{await g()},onrampTrackingData:J(()=>!_||!n||!c?null:{provider:_.serviceProvider||`Meld`,sourceAmount:n,sourceCurrencyCode:r||``,destinationAmount:String(_.destinationAmount||``),destinationCurrencyCode:i||``,exchangeRate:String(_.exchangeRate||``),networkFees:String(_.networkFee||``),transactionFee:String(_.transactionFee||``),totalFees:String(_.totalFee||``),countryCode:o||``,paymentMethod:_.paymentMethodType||``,walletAddress:c,timestamp:new Date().toISOString()},[_,n,r,i,o,c])}}function ME(e){let{enabled:t,environment:n,activeMeshExchangeKeys:r,activeMeshIntegrationIds:i,selectedMeshAccessTokens:a,originToken:o,trailsApiUrl:s,apiKey:c}=e,l=gv(),{data:u}=Or({queryKey:[`mesh-selected-token-balance`,n,r,i,a,o?.chainId,o?.symbol,s,c],queryFn:async()=>{let e=await l.getMeshSupportedTokens({environment:n,accessTokens:a.length>0?a:void 0}),t=_v(r?.length?(e.tokens||[]).filter(e=>(e.exchangeKeys||[]).some(e=>r.includes(e))):i?.length?(e.tokens||[]).filter(e=>(e.integrationIds||[]).some(e=>i.includes(e))):e.tokens||[],o?.chainId,o?.symbol),s=t.find(e=>Number(e.balance||`0`)>0)||t[0];return s?{balance:String(s.balance||``),balanceUsd:Number(s.balanceUsd||`0`)}:{balance:``,balanceUsd:0}},enabled:t&&!!c&&!!s&&!!o?.chainId&&!!o?.symbol,staleTime:3e4,gcTime:300*1e3,refetchOnMount:!0,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),d=o?.decimals??18,f=u?.balance||``;return{tokenDecimals:d,balanceFormatted:f,balanceRaw:J(()=>{if(!f)return`0`;try{return Sn(f,d).toString()}catch{return`0`}},[f,d]),balanceUsdDisplay:Ks(u?.balanceUsd||0),balanceUsdLocaleDisplay:qs(u?.balanceUsd||0)}}function NE(e){let{fundMethod:t,meshEnabled:n,meshEnvironment:r,activeMeshExchangeKeys:i,activeMeshIntegrationIds:a,selectedMeshAccessTokens:o,originToken:s,trailsApiUrl:c,apiKey:l,balanceFormatted:u,balanceRaw:d,tokenDecimals:f,balanceLocaleDisplay:p,balanceUsdDisplay:m,balanceUsdLocaleDisplay:h}=e,g=t===`onramp-mesh`,{tokenDecimals:_,balanceFormatted:v,balanceRaw:y,balanceUsdDisplay:b,balanceUsdLocaleDisplay:x}=ME({enabled:g&&n,environment:r,activeMeshExchangeKeys:i,activeMeshIntegrationIds:a,selectedMeshAccessTokens:o,originToken:s||void 0,trailsApiUrl:c,apiKey:l});return{effectiveBalanceFormatted:g?v||void 0:u,effectiveBalanceRaw:g?y:d,effectiveTokenDecimals:g?_:f,effectiveBalanceLocaleDisplay:g?v:p,effectiveBalanceUsdDisplay:g?b:m,effectiveBalanceUsdLocaleDisplay:g?x:h}}const PE=({countries:e,selectedCountryCode:t,onCountrySelect:n,className:r=``,buttonClassName:i=``,dropdownClassName:a=``,compactMode:o=!1,nestedMode:s=!1})=>{let c=Y(null),l=Y(null),[u,d]=X(!1),[f,p]=X(``),m=J(()=>{if(!f.trim())return e;let t=f.trim().toLowerCase();return e.filter(e=>e.name.toLowerCase().includes(t)||e.countryCode.toLowerCase().includes(t))},[e,f]);q(()=>{u&&l.current&&setTimeout(()=>{l.current?.focus()},100)},[u]),q(()=>{let e=e=>{c.current&&!c.current.contains(e.target)&&(d(!1),p(``))};return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[]);let h=e=>{n(e),d(!1),p(``)},g=J(()=>t===null?null:e.find(e=>e.countryCode===t)||null,[e,t]);return Q(`div`,{className:`relative ${r}`,ref:c,children:[Q(`button`,{type:`button`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),d(!u)},className:`h-full px-3 flex items-center gap-2 cursor-pointer transition-colors ${i}`,title:`Select a country`,children:[g?Z(`img`,{src:g.flagImageUrl,alt:g.name,className:`w-5 h-5 rounded object-cover`}):Z(`div`,{className:`w-5 h-5 flex items-center justify-center`,children:Z(`span`,{className:`text-white text-xs font-bold`,children:`🌍`})}),Z(Di,{className:`h-5 w-5 text-gray-400 transition-all duration-200 ${u?`rotate-180`:``}`})]}),u&&Q(`div`,{className:`absolute right-0 top-full mt-1 min-w-[280px] trails-bg-secondary trails-border trails-border-radius-list token-list-border shadow-lg z-50 ${s?`max-h-80`:o?`max-h-48`:`max-h-[400px]`} ${a}`,children:[Z(`div`,{className:`p-2 border-b border-gray-200 dark:border-gray-700`,children:Z(`input`,{ref:l,type:`text`,value:f,onChange:e=>p(e.target.value),placeholder:`Select your country`,className:`w-full px-3 py-2 text-sm border border-solid trails-border-radius-input focus:ring-2 focus:ring-blue-500 focus:border-blue-500 trails-input`,onMouseDown:e=>e.stopPropagation()})}),Q(`div`,{className:`p-2 ${s?`max-h-52`:o?`max-h-32`:`max-h-[320px]`} overflow-y-auto trails-scrollbar`,children:[m.map(e=>Q(`button`,{type:`button`,onMouseDown:t=>{t.preventDefault(),t.stopPropagation(),h(e.countryCode)},className:`w-full flex items-center gap-3 px-3 py-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors rounded text-left ${t===e.countryCode?`bg-blue-50 dark:bg-blue-900/20`:``}`,title:e.name,children:[Z(`img`,{src:e.flagImageUrl,alt:e.name,className:`w-6 h-6 rounded object-cover flex-shrink-0`}),Z(`span`,{className:`text-sm font-medium`,children:e.name})]},e.countryCode)),m.length===0&&f.trim()&&Z(`div`,{className:`text-center py-4`,children:Q(`p`,{className:`text-sm text-gray-500 dark:text-gray-400`,children:[`No countries found matching "`,f,`"`]})})]})]})]})},FE=({onCurrencySelect:e,onError:t,selectedCurrency:n,onNavigateToFundMethods:r,showContinueButton:i=!1,onContinue:a,compactMode:o=!1,trailsClient:c,onAutoSelect:l,onSelectCountry:u})=>{let[d,f]=X(``),[p,m]=X(null),{data:h=[]}=Xx(),g=e=>{m(e),u?.(e)},{countryCode:_,defaultCurrencyCode:v,isLoading:y,error:b}=Vw({enabled:!0}),x=p||_,{fiatCurrencies:S,isLoading:C,error:w}=kE({countryCode:x||`US`,trailsClient:c,enabled:!0}),T=or.useRef(!1);q(()=>{if(!n&&S.length>0&&!C&&!y&&!T.current){let t=v||`USD`,n=S.find(e=>e.currencyCode===t);n&&(s.console.log(`[FiatSelector] Auto-selecting default currency:`,n,v?`(detected)`:`(fallback to USD)`),T.current=!0,l?l(n):e(n))}},[n,v,S,C,y,e,l]),q(()=>{n&&(T.current=!0)},[n]),q(()=>{T.current=!1},[]);let E=J(()=>{if(!d.trim())return S;let e=d.trim().toLowerCase();return S.filter(t=>t.currencyCode.toLowerCase().includes(e)||t.name.toLowerCase().includes(e))},[S,d]),D=e=>n?.currencyCode===e.currencyCode,O=t=>{e(t)},k=``;return w||b?k=`Failed to load currencies`:!x&&y?k=`Detecting your location...`:d.trim()&&E.length===0?k=`No currencies found matching your search.`:S.length===0&&!C&&(k=`No currencies available for your location`),q(()=>{w&&t(w)},[w,t]),Q(`div`,{className:`space-y-2`,children:[Z(Xy,{value:d,onChange:f,placeholder:`Search currencies`,autoFocus:!0,className:`mb-2`,rightAlignedComponent:Z(PE,{countries:h,selectedCountryCode:p,onCountrySelect:g,compactMode:o,nestedMode:!0})}),C&&E.length===0&&Q(`div`,{className:`text-center py-4`,children:[Z(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 mx-auto border-solid border-black dark:border-white`}),Z(`p`,{className:`mt-2 text-gray-500 dark:text-gray-400`,children:`Loading currencies...`})]}),!C&&E.length===0&&k&&Z(`div`,{className:`text-center py-4 rounded-lg trails-bg-secondary`,children:Z(`p`,{className:`text-gray-500 dark:text-gray-400`,children:k})}),E.length>0&&Z(`div`,{className:`${o?`max-h-48`:`max-h-[400px]`} overflow-y-auto trails-scrollbar space-y-1`,children:E.map(e=>{let{currencyCode:t,name:n,symbolImageUrl:r}=e,i=D(e);return Q(`button`,{type:`button`,onClick:()=>O(e),"aria-label":`Select ${n} currency`,title:`Select ${n} currency`,className:`w-full py-2 px-4 flex items-center space-x-3 transition-all duration-200 trails-list-item trails-border-radius-list-button ${i?`trails-list-item-selected`:``} cursor-pointer`,children:[Z(`div`,{className:`relative flex-shrink-0 mr-2`,children:Z(`div`,{className:`rounded-full flex items-center justify-center bg-gray-100 dark:bg-gray-700`,children:r?Z(`img`,{src:r,alt:t,className:`w-8 h-8 rounded-full object-cover`}):Z(`div`,{className:`w-8 h-8 rounded-full bg-gray-200 dark:bg-gray-600 flex items-center justify-center`,children:Z(`span`,{className:`text-xs font-medium text-gray-600 dark:text-gray-300`,children:t.substring(0,2)})})})}),Q(`div`,{className:`flex-1 min-w-0 text-left`,children:[Z(`h3`,{className:`text-sm font-medium truncate text-gray-900 dark:text-white`,children:n}),Z(`div`,{className:`flex items-center gap-1.5`,children:Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap`,children:t})})]})]},t)})}),i&&a&&n&&Z(`div`,{className:`space-y-4`,children:Z(`button`,{type:`button`,onClick:()=>a(n),disabled:!n,className:`w-full font-semibold py-3 px-4 trails-border-radius-button transition-colors bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white disabled:text-gray-500 disabled:cursor-not-allowed cursor-pointer`,children:`Continue`})}),r&&!C&&Z(`div`,{className:`text-center pt-1`,children:Q(`button`,{type:`button`,onClick:r,className:`inline-flex items-center justify-center space-x-1 px-2 py-1 text-xs font-medium trails-text-secondary trails-bg-secondary trails-hover-bg trails-border trails-border-radius-button transition-all duration-200 cursor-pointer`,children:[Z(Oi,{className:`h-3 w-3`}),Z(`span`,{children:`Pay with another method`})]})})]})},IE=({currency:e,onSelect:t,className:n=`flex items-center space-x-1.5 trails-border-radius-input px-2.5 py-1.5 border transition-all duration-200`,unselectable:r=!1})=>Z(`button`,{type:`button`,onClick:t,disabled:r,className:`${n} ${e?`max-w-[150px]`:``} ${e?`bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 hover:border-gray-300 dark:hover:border-gray-600`:`bg-blue-500 hover:bg-blue-600 border-blue-500 text-white`} ${r?`cursor-default`:`cursor-pointer`}`,children:e?Q(hi,{children:[Z(`div`,{className:`flex items-center shrink-0`,children:e.symbolImageUrl?Z(`img`,{src:e.symbolImageUrl,alt:e.currencyCode,className:`w-6 h-6 rounded-full object-cover`}):Z(`div`,{className:`w-10 h-7 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center`,children:Z(`span`,{className:`text-xs font-medium text-gray-600 dark:text-gray-300`,children:e.currencyCode.substring(0,2)})})}),Q(`div`,{className:`flex flex-col items-start min-w-0 overflow-hidden`,children:[Z(`span`,{className:`font-bold trails-text-primary text-sm leading-tight truncate max-w-full text-left`,children:e.currencyCode}),Z(`span`,{className:`text-xs trails-text-muted leading-tight truncate max-w-full text-left`,children:e.name})]}),!r&&Z(ki,{className:`w-3.5 h-3.5 trails-text-muted flex-shrink-0`})]}):Q(hi,{children:[Z(`span`,{className:`font-medium text-sm text-white`,children:`Select Currency`}),!r&&Z(ki,{className:`w-3.5 h-3.5 text-white`})]})}),LE=({providers:e,selectedProvider:t,trailsQuote:n,setSelectedProvider:r,isRefetching:i})=>{let[a,o]=X(!1),s=Y(null),c=Y(null),l=e?.[0]??null;if(q(()=>{e&&e.length>0&&!t&&r(e[0])},[e,t,r]),i||!e||e.length===0)return null;let u=e=>{r(e),o(!1)},d=t||e[0],f=()=>{if(!t?.destinationAmount||!n?.destinationAmount||!n?.destinationToken?.decimals)return 0;let e=Number(t.destinationAmount),r=Number(vn(BigInt(n.destinationAmount),n.destinationToken.decimals));return e===0?0:r/e},p=e=>{if(!n?.destinationToken?.symbol)return`0`;let t=f();return t===0?`0`:`${(Number(e.destinationAmount)*t).toFixed(6)} ${n.destinationToken.symbol}`},m=e=>`$${Number(e.destinationAmount).toFixed(2)}`,h=()=>{if(n?.destinationToken?.symbol?.toUpperCase()===`USDC`&&n?.destinationAmountFormatted){let e=parseFloat(n.destinationAmountFormatted);if(_s(e))return`$${e.toFixed(2)}`}return n?.destinationAmountUsdDisplay?n.destinationAmountUsdDisplay:`$0`},g=()=>!n?.destinationAmountFormatted||!n?.destinationToken?.symbol?`0`:`${n.destinationAmountDisplay} ${n.destinationToken.symbol}`;return e.length===1&&d?Z(`div`,{className:`space-y-1`,ref:s,children:Q(`div`,{className:`p-2`,children:[Z(`div`,{className:`flex justify-between items-center mb-2`,children:Z(`div`,{className:`text-xs font-medium trails-text-primary`,children:`Onramp Provider`})}),Z(`div`,{className:`mt-2 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700`,children:Q(`div`,{className:`flex items-center justify-between`,children:[Z(`div`,{className:`flex items-center gap-2`,children:Q(`div`,{className:`flex flex-col`,children:[Z(`div`,{className:`text-sm font-medium text-gray-900 dark:text-white`,children:d.serviceProvider}),d===l&&Z(`span`,{className:`ml-2 text-xs text-green-600 dark:text-green-400`,children:`(Recommended)`})]})}),Q(`div`,{className:`text-right`,children:[Z(`div`,{className:`text-sm font-medium text-gray-900 dark:text-white`,children:g()}),Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:h()})]})]})})]})}):Z(`div`,{ref:s,children:Q(`div`,{className:`p-2`,children:[Q(`button`,{className:`w-full flex justify-between items-center mb-2 cursor-pointer`,type:`button`,onClick:()=>o(!a),children:[Z(`div`,{className:`text-sm font-semibold text-gray-900 dark:text-white`,children:`Onramp Provider`}),Q(`div`,{className:`flex items-center gap-2`,children:[d&&Z(`div`,{className:`text-sm font-medium text-gray-600 dark:text-gray-400`,children:d.serviceProvider}),Z(Di,{className:`w-3 h-3 transition-transform duration-300 ease-out text-gray-600 dark:text-gray-400 ${a?`rotate-180`:``}`})]})]}),Z(`div`,{ref:c,className:`overflow-auto transition-all duration-300 ease-out ${a?`max-h-[250px] opacity-100`:`max-h-0 opacity-0`}`,children:Z(`div`,{className:`mt-2 space-y-1`,children:e.map(n=>{let r=t?.serviceProvider===n.serviceProvider;return Z(`button`,{type:`button`,onClick:()=>u(n),className:`w-full p-3 rounded-lg border transition-all cursor-pointer ${r?`bg-blue-50 dark:bg-blue-900/20 border-blue-300 dark:border-blue-700`:`bg-gray-50 dark:bg-gray-800 border-gray-200 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-750`}`,children:Q(`div`,{className:`flex items-center justify-between`,children:[Z(`div`,{className:`flex items-center gap-2`,children:Q(`div`,{className:`text-left`,children:[Z(`div`,{className:`text-sm font-medium text-gray-900 dark:text-white`,children:n.serviceProvider}),e[0]?.serviceProvider===n.serviceProvider&&Z(`span`,{className:`text-xs text-green-600 dark:text-green-400`,children:`(Recommended)`})]})}),r?Q(`div`,{className:`text-right`,children:[Z(`div`,{className:`text-sm font-medium text-gray-900 dark:text-white`,children:g()}),Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:h()})]}):Q(`div`,{className:`text-right`,children:[Z(`div`,{className:`text-sm font-medium text-gray-900 dark:text-white`,children:p(n)}),Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:m(n)})]})]})},n.serviceProvider)})})})]})})},RE=({onClick:e,className:t=``,children:n})=>Q(`div`,{className:`relative`,children:[Z(`span`,{"aria-hidden":`true`,className:`trails-radiate-ring pointer-events-none absolute -inset-1`}),Z(`span`,{"aria-hidden":`true`,className:`trails-radiate-ring trails-radiate-ring-delayed pointer-events-none absolute -inset-1`}),Z(`button`,{type:`button`,onClick:e,className:`relative z-10 ${t}`,children:n})]}),zE=({address:e,size:t=32,className:n})=>{let{ensAvatar:r,ensName:i}=Iy({address:e});return r?Z(`img`,{src:r,alt:i||e,className:`shrink-0 rounded-full object-cover ${n??``}`,style:{width:t,height:t}}):Z(Uy,{value:e,size:t,className:n})};function BE(e){let t=e.trim();return ut(t)?`solana`:bn(t)?`evm`:null}function VE(e){let t=Math.round(e*.38);return{badgeSize:t,rightOffset:Math.round(t*.28),bottomOffset:Math.round(t*.12),reserve:Math.round(t*.3)}}const HE=({chainId:e,size:t=20,className:n})=>W(e)?Z(`img`,{src:lw,alt:`Solana`,className:`shrink-0 rounded-full object-cover ${n??``}`,style:{width:t,height:t}}):Z(Ty,{chainId:e,size:t});function UE({chainId:e,size:t}){let{badgeSize:n,rightOffset:r,bottomOffset:i}=VE(t);return Z(`div`,{className:`absolute flex items-end justify-end pointer-events-none`,style:{right:-r,bottom:-i},children:Z(`div`,{className:`rounded-full border border-white bg-white dark:border-gray-900 dark:bg-gray-900`,children:W(e)?Z(`img`,{src:lw,alt:`Solana`,className:`rounded-full object-cover`,style:{width:n,height:n}}):Z(Ty,{chainId:e,size:n})})})}function WE({network:e,size:t}){let n=e===`solana`?void 0:1;return n==null?Z(UE,{chainId:101,size:t}):Z(UE,{chainId:n,size:t})}const GE=({address:e,chainId:t,size:n=28,className:r,useEnsAvatar:i=!1,avatar:a,showChainBadge:o=!0})=>{let s=o&&t==null?BE(e):null,c=o&&(t!=null||s!=null)?VE(n).reserve:0;return Q(`div`,{className:`relative shrink-0 overflow-visible ${r??``}`,style:{width:n,height:n,marginRight:c},children:[a??(i?Z(zE,{address:e,size:n,className:`shrink-0`}):Z(Wy,{size:n,walletAddress:e})),t==null?s?Z(WE,{network:s,size:n}):null:Z(UE,{chainId:t,size:n})]})},KE=({selectedRecipient:e,pulsating:t=!1,showChainBadge:n=!0})=>{let{navigate:r,screen:i}=y_(),{selectedToken:a}=xl(),o=qu(),s=o?.connected&&o.publicKey?o.publicKey.toBase58():null,c=()=>{r(`recipients`,{backTarget:i})},l=!!e&&ut(e),u=l&&!!s&&e?.trim()===s.trim();return Q(`button`,{type:`button`,onClick:c,className:`relative flex items-center gap-1 transition-colors cursor-pointer border-none p-0 bg-transparent text-polygon-500 hover:text-polygon-600`,title:e?`Selected: ${e}`:`Select recipient`,children:[t&&Q(hi,{children:[Z(`span`,{"aria-hidden":`true`,className:`trails-radiate-ring pointer-events-none absolute -inset-1`}),Z(`span`,{"aria-hidden":`true`,className:`trails-radiate-ring trails-radiate-ring-delayed pointer-events-none absolute -inset-1`})]}),e?Q(hi,{children:[Z(GE,{address:e,chainId:n?a?.chainId:null,showChainBadge:n,size:20,avatar:u&&o?Z(Na,{walletId:o.walletId,icon:o.walletIcon,label:o.walletName??`Solana`,size:20,className:`shrink-0`,imageClassName:`shrink-0 rounded-full object-cover`}):void 0}),l?Z(`span`,{className:`text-sm font-medium m-0`,children:wt(e,4,4)}):Z(cw,{address:e,startChars:4,endChars:4,className:`text-sm font-medium m-0`})]}):Z(`span`,{className:`text-sm ${t?`font-bold`:`font-medium`} m-0`,children:`Select Recipient`}),Z(ki,{className:`w-4 h-4 m-0`,strokeWidth:t?3:2})]})};function qE(e){let t=e.selectedRecipient?.trim();if(t)return t;let n=e.toRecipient?.trim();if(n)return n;if(!W(e.destinationChainId??0))return e.accountAddress??void 0}const JE=({isSenderContractOnOrigin:e,isSenderContractOnDestination:t,isSequenceWallet:n=!1})=>{if(!(e&&!t&&!n))return null;let r=``;return e&&!t&&(r=`The sender is a contract address. Funds may be lost if the transaction fails and the contract cannot accept refunds on the destination chain.`),Z(`div`,{className:`mb-2 px-2 py-3 rounded-lg bg-amber-500/10 border border-solid border-amber-500/30`,children:Q(`div`,{className:`flex items-start space-x-2`,children:[Z(`svg`,{className:`w-4 h-4 text-amber-500 flex-shrink-0 mt-0.5`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})}),Q(`div`,{children:[Z(`p`,{className:`text-sm font-medium text-amber-600 dark:text-amber-400`,children:`Risk of Fund Loss`}),Z(`p`,{className:`text-xs mt-1 text-amber-600 dark:text-amber-400`,children:r})]})]})})};function YE(e,t){return e&&!W(e.chainId??0)?e:t?.find(e=>!W(e.chainId??0))??null}function XE({destinationChainId:e,originChainId:t,selectedRecipient:n,connectedSolanaAddress:r,evmFallbackAddress:i}){let a=W(e??0),o=W(t??0),s=n?.trim()||null;if(a){if(o)return;let e=r?.trim()||null;return e&&ut(e)&&(!s||bn(s))?e:s&&bn(s)?null:void 0}if(s&&ut(s)){let e=i?.trim()||null;return e&&bn(e)?e:null}}function ZE({recipient:e,allowedChainIds:t,disabledChains:n}){let r=e?.trim();if(r&&ut(r)){let e=n?.filter(e=>e!==101);return{allowedChainIds:[101],disabledChains:e?.length?e:void 0}}if(r&&bn(r)){let e=[...n??[]];return e.includes(101)||e.push(101),{allowedChainIds:t,disabledChains:e}}return{allowedChainIds:t,disabledChains:n?.length?[...n]:void 0}}function QE({fundMethod:e,allowedChainIds:t,disabledChains:n}){let{address:r}=Kr(),i=Jr(),a=ni(),o=qu(),s=Hu();return J(()=>{let c={allowedChainIds:t,disabledChains:n?.length?[...n]:void 0};if(e&&e!==`wallet`)return c;if(Zu(s)){let e=n?.filter(e=>e!==101);return{allowedChainIds:[101],disabledChains:e?.length?[...e]:void 0}}if(!(Xu(s)||!s&&r))return c;let l=bd({connectedWallets:i,svmWallet:o,session:a,selectedFundingWallet:s,activeEvmAddress:r});if(wd(s,l))return c;let u=[...n??[]];return u.includes(101)||u.push(101),{allowedChainIds:t,disabledChains:u}},[r,t,i,n,e,s,o,a])}function $E(){let{selectedFundMethod:e,setSelectedFundMethod:t,selectedBluvoExchange:n,selectedBluvoWalletId:r,selectedBluvoBalances:i,setSelectedBluvoExchange:a,setSelectedBluvoWalletId:o,setSelectedBluvoBalances:s,clearSelectedBluvoFunding:c}=Vu();return{selectedFundMethod:e,setSelectedFundMethod:t,selectedBluvoExchange:n,selectedBluvoWalletId:r,selectedBluvoBalances:i,setSelectedBluvoExchange:a,setSelectedBluvoWalletId:o,setSelectedBluvoBalances:s,clearSelectedBluvoFunding:c}}function eD(){let{selectedFundMethod:e,setSelectedFundMethod:t}=Vu(),{selectedMeshExchange:n,setSelectedMeshExchange:r,selectedMeshAccessTokens:i,replaceSelectedMeshAccessTokens:a,clearSelectedMeshAccessTokens:o}=wy(),{selectedBluvoExchange:s,selectedBluvoWalletId:c,selectedBluvoBalances:l,setSelectedBluvoExchange:u,setSelectedBluvoWalletId:d,setSelectedBluvoBalances:f,clearSelectedBluvoFunding:p}=$E();return{selectedFundMethod:e,setSelectedFundMethod:t,selectedMeshExchange:n,setSelectedMeshExchange:r,selectedMeshAccessTokens:i,replaceSelectedMeshAccessTokens:a,clearSelectedMeshAccessTokens:o,selectedBluvoExchange:s,selectedBluvoWalletId:c,selectedBluvoBalances:l,setSelectedBluvoExchange:u,setSelectedBluvoWalletId:d,setSelectedBluvoBalances:f,clearSelectedBluvoFunding:p}}function tD({modeLabel:e,token:t,targetNetwork:n,setDestinationToken:r,setSelectedDestToken:i,setSelectedDestinationChain:a,setHasManualDestinationSelection:o,setDestinationChainFilterId:c}){s.console.log(`[trails-sdk] ${e}: recipient selected, switching destination to ${n}:`,t),r(t),i(t),o?.(!1),c?.(t.chainId??null);let l=$(t.chainId);l&&a(l)}function nD({modeLabel:e,selectedRecipient:t,destinationToken:n,originChainId:r,isDestinationLocked:i=!1,defaultSolanaToken:a,defaultEvmDestinationToken:o,availableDestinationTokens:s,setDestinationToken:c,setSelectedDestToken:l,setSelectedDestinationChain:u,setHasManualDestinationSelection:d,setDestinationChainFilterId:f}){q(()=>{i||!t||!ut(t)||W(n?.chainId??0)||W(r??0)||a&&tD({modeLabel:e,token:a,targetNetwork:`Solana`,setDestinationToken:c,setSelectedDestToken:l,setSelectedDestinationChain:u,setHasManualDestinationSelection:d,setDestinationChainFilterId:f})},[i,t,n?.chainId,r,a,e,c,l,u,d,f]),q(()=>{if(i||!t||!bn(t)||!W(n?.chainId??0))return;let r=YE(o,s);r&&tD({modeLabel:e,token:r,targetNetwork:`EVM`,setDestinationToken:c,setSelectedDestToken:l,setSelectedDestinationChain:u,setHasManualDestinationSelection:d,setDestinationChainFilterId:f})},[i,t,n?.chainId,o,s,e,c,l,u,d,f])}function rD(e){let t=Ft(101),n=e!=null,r=J(()=>e==null?null:[...e],[e]),i=J(()=>nl(e,{disabledChains:[]}),[e]);return{destinationEdgePlugin:t,isEdgeDestinationSupported:!0,destinationChainIds:r,destinationChainList:i,destinationChainListExtras:J(()=>{if(!(n&&!e.includes(101)))return i&&i.some(e=>e.chainId===101)?void 0:[Ra]},[e,i,n]),destinationCatalogSupplementTokens:J(()=>{if(n&&!e.includes(101))return[];let r=t?.getDestinationTokens?.();return r&&r.length>0?r:Ze()},[e,t,n]),destinationDisabledChains:void 0}}const iD=({selectedToken:e,onSend:t,onConfirm:n,onComplete:r,account:i,toRecipient:o,toAmount:l,toChainId:u,toToken:d,toCalldata:f,walletClient:m,onTransactionStateChange:h,onError:g,onWaitingForWalletConfirm:_,onrampPropsCallback:v,screenNavigationCallback:y,onWaitingForOnrampConfirm:b,setWalletConfirmRetryHandler:x,swapProvider:S,bridgeProvider:C,swapProviderFallback:w,bridgeProviderFallback:E,fundMethod:D,onAmountUpdate:O,checkoutOnHandlers:k,recentTokens:A,onTrackToken:j,isSequenceWallet:M=!1,defaultInputMode:N})=>{let{mode:P,navigate:F}=y_(),I=wo(),{fundOptions:ee,onramp:te,apiKey:ne,trailsApiUrl:re}=I,ie=To(I),L=gv(),{selectedToken:R,setSelectedToken:ae,hasManualSelection:z,setHasManualSelection:B}=ul(),{selectedToken:V,setSelectedToken:oe,hasManualSelection:H,setHasManualSelection:se,isControlledByProps:ce,availableDestinationTokens:U,availableDestinationTokenKeys:le,availableDestinationTokenRestrictedChainIds:ue,availableDestinationChainIds:de}=xl(),{destinationChainIds:fe,destinationChainList:pe,destinationChainListExtras:me,destinationCatalogSupplementTokens:he,destinationDisabledChains:ge,isEdgeDestinationSupported:_e}=rD(de),{paymentMethod:ye,setPaymentMethod:be,selectedFundingWallet:xe}=Vu(),Se=Zu(xe),{selectedMeshExchange:Ce,selectedMeshAccessTokens:we,selectedBluvoExchange:Te}=eD(),Ee=uy(te),De=yv(Ee),Oe=!!Ee?.mesh,ke=Ee?.mesh?.exchanges??null,Ae=Ce?[Ce.integrationId]:null,je=Ce?null:ke,Me=D===`onramp-mesh`&&(Ce?.exchangeKey===`coinbase`||Ce?.exchangeKey===`coinbaseRamp`),Ne=Ce?.exchangeName||`Exchange`,Fe=D===`onramp-meld`||D===`direct-transfer`||D===`onramp-mesh`||D===`onramp-bluvo`,{token:Ie,isLoadingBalance:Le}=ev(R,ZT(R,i?.address),{disabled:Fe,withPrices:!0}),{selectedRecipient:Re,setSelectedRecipient:ze}=cu(),{selectedCurrency:Be,setSelectedCurrency:Ve,hasManualSelection:He,setHasManualSelection:Ue,fiatAmount:We,setFiatAmount:Ge}=wl(),[Ke,qe]=X(!1),[Je,Ye]=X(null),[Xe,Ze]=X(!1),[Qe,$e]=X(null),[et,tt]=X(We),nt=Y(null),rt=D===`onramp-meld`,it=rt?c:R,[at,ot]=X(!rt&&N===`fiat`),[st,ct]=X(``),lt=Y(!1),[ut,dt]=X(!1),G=Y(null);q(()=>()=>{G.current&&clearTimeout(G.current)},[]);let{countryCode:ft,defaultCurrencyCode:pt,isLoading:mt}=Vw({enabled:rt}),ht=Je||ft,{fiatCurrencies:gt,isLoading:_t}=kE({countryCode:ht||`US`,enabled:rt&&!!ht});q(()=>{if(rt&&!Be&&gt.length>0&&!mt&&!_t&&!He){let e=pt??`USD`,t=gt.find(t=>t.currencyCode===e);t&&(s.console.log(`[Fund] Auto-selecting default currency:`,t,pt?`(from location)`:`(fallback to USD - location not available)`),Ve(t))}},[rt,Be,pt,gt,mt,_t,He,Ve]);let vt=Y(null);q(()=>{rt||(vt.current=null)},[rt]),q(()=>{if(!rt||_t||gt.length===0)return;let e=ee?.fiatCurrency?.trim()||``,t=ee?.fiatAmount?.trim()||``,n=`${e.toUpperCase()}|${t}`;if(vt.current!==n){if(vt.current=n,e){let t=gt.find(t=>t.currencyCode.toUpperCase()===e.toUpperCase());t&&(Ve(t),Ue(!0),t.currencyCode.toUpperCase()!==`USD`&&at&&(ot(!1),lt.current=!1))}t&&(Ge(t),ct(t))}},[rt,_t,gt,ee?.fiatCurrency,ee?.fiatAmount,Ve,Ue,Ge,at]);let yt=ee?.paymentMethodType||null,bt=Y(null);q(()=>{!rt||!yt||bt.current!==yt&&(bt.current=yt,be({id:yt,name:{CREDIT_DEBIT_CARD:`Credit/Debit Card`,APPLE_PAY:`Apple Pay`,GOOGLE_PAY:`Google Pay`,SEPA:`SEPA`,PAYPAL:`PayPal`,REVOLUT_PAY:`Revolut Pay`}[yt]??yt}))},[rt,yt,be]);let xt=ee?.fiatCurrency?.trim().toUpperCase()||null,St=!!xt&&!!Be&&Be.currencyCode.toUpperCase()===xt,Ct=rt&&St,wt=rt&&!!ee?.fiatAmount,Tt=Y({hasManualDestinationSelection:!1,lastOriginSelectionTime:0,lastDestinationSelectionTime:0}),{defaultOriginToken:Et,isLoading:Dt}=XT(),{defaultDestinationToken:Ot,isLoading:kt}=OE(R),At=it?.chainId??e?.chainId??null,jt=qu(),Mt=J(()=>jt&&D===`wallet`?[Ra]:void 0,[D,jt]),{handleChainSelect:Nt}=D_(D),{tradeType:Pt,setTradeType:Ft,sellAmount:It,setSellAmount:Lt,buyAmount:Rt,setBuyAmount:zt,resetSwapState:Bt,enterFormMode:Vt}=d_(),Ht=J(()=>D===`onramp-meld`?`fund-onramp-meld`:D===`onramp-mesh`?`fund-onramp-mesh`:D===`onramp-bluvo`?`fund-onramp-bluvo`:D===`direct-transfer`?`fund-direct-transfer`:`fund-wallet`,[D]);q(()=>{Vt(Ht)&&(Ge(``),ct(``))},[Ht]),q(()=>{rt&&We?ct(We):!rt&&It&&ct(It)},[]);let Ut=Pt||ln.EXACT_INPUT,[Wt,Gt]=X(!1),[Kt,qt]=X(null),Jt=K(e=>{ct(``),Ge(``),Bt(),r(e)},[r,Bt,Ge]);q(()=>{s.console.log(`[trails-sdk] Fund toRecipient prop effect:`,{toRecipient:o,selectedRecipient:Re,accountAddress:i?.address}),o&&(s.console.log(`[trails-sdk] Fund Setting selectedRecipient to toRecipient:`,o),ze(o))},[o,ze]);let Yt=V?.chainId??u??null,Xt=qE({selectedRecipient:Re,toRecipient:o,accountAddress:i?.address,destinationChainId:Yt}),Zt=W(Yt??0)&&!Xt,Qt=rt?`onramp-meld`:D;q(()=>(nt.current&&clearTimeout(nt.current),nt.current=setTimeout(()=>{tt(We)},500),()=>{nt.current&&clearTimeout(nt.current)}),[We]);let{quotes:$t,selectedQuote:en,isLoading:tn,error:nn,onrampTrackingData:rn}=jE({amount:et,sourceCurrencyCode:Be?.currencyCode,destinationCurrencyCode:`USDC_BASE`,countryCode:ht||void 0,walletAddress:i?.address||``,paymentMethodType:ye?.id,enabled:rt&&!!et&&!!Be&&!!ht&&!!Xt}),{amount:an,amountRaw:on,balanceFormatted:sn,balanceRaw:cn,tokenDecimals:un,balanceLocaleDisplay:dn,balanceUsdDisplay:fn,balanceUsdLocaleDisplay:pn,handleSubmit:mn,isSubmitting:hn,isLoadingQuote:gn,selectedDestToken:_n,setSelectedDestinationChain:vn,setSelectedDestToken:yn,buttonText:xn,destinationTokenAddress:Sn,isValidCustomToken:Cn,prepareSendQuote:wn,processedFeeOptions:Tn,selectedFeeOption:En,setSelectedFeeOption:Dn,sendFn:On,sourceTokenPrices:kn}=nE({account:i,toAmount:Ut===ln.EXACT_OUTPUT?Rt:l,fromAmount:Ut===ln.EXACT_INPUT?It:void 0,toRecipient:Xt,toChainId:u,toToken:d,toCalldata:f,walletClient:m,onTransactionStateChange:h,onError:g,onWaitingForWalletConfirm:_,onWaitingForOnrampConfirm:b,onSend:t,onConfirm:n,onComplete:Jt,selectedToken:it,setWalletConfirmRetryHandler:x,tradeType:Ut,swapProvider:S,bridgeProvider:C,swapProviderFallback:w,bridgeProviderFallback:E,fundMethod:Qt,mode:P,checkoutOnHandlers:k,onrampTrackingData:rt?rn:null,skipFeeBalanceFetch:Qt===`onramp-meld`||Qt===`direct-transfer`||Qt===`onramp-mesh`||Qt===`onramp-bluvo`,onNavigateToOnrampMesh:v&&y?e=>{v(e),y(`onramp-mesh`)}:void 0,onNavigateToOnrampBluvo:v&&y?e=>{v(e),y(`onramp-bluvo`)}:void 0}),An=Rl({originToken:Ie??R,originTokenBalance:Ie?.balance??R?.balance,originTokenAmount:It,isLoadingBalance:Le}),jn=!!En&&!!An&&Bl(En,An),Mn=QE({fundMethod:D,allowedChainIds:null,disabledChains:J(()=>W(Yt??0)?[101]:void 0,[Yt])}),Nn=J(()=>{let e=[...ge??[]];return W(R?.chainId??0)&&!e.includes(101)&&e.push(101),ZE({recipient:Re,allowedChainIds:fe,disabledChains:e.length>0?e:void 0})},[ge,R?.chainId,Re,fe]),[Pn,Fn]=X(null);nD({modeLabel:`Fund`,selectedRecipient:Re,destinationToken:V,originChainId:R?.chainId,isDestinationLocked:ce,defaultSolanaToken:he[0],defaultEvmDestinationToken:Ot,availableDestinationTokens:U,setDestinationToken:oe,setSelectedDestToken:yn,setSelectedDestinationChain:vn,setHasManualDestinationSelection:se,setDestinationChainFilterId:Fn});let In=!!R&&!!_n&&!o&&!Re,{data:Ln=!0,isLoading:Rn}=Or({queryKey:[`mesh-route-support`,De,je,wn?.originChain?.id,wn?.originToken?.symbol,re,ne],queryFn:async()=>{let e=await L.getMeshSupportedTokens({environment:De});return _v(je?.length?(e.tokens||[]).filter(e=>(e.exchangeKeys||[]).some(e=>je.includes(e))):Ae?.length?(e.tokens||[]).filter(e=>(e.integrationIds||[]).some(e=>Ae.includes(e))):e.tokens||[],wn?.originChain?.id,wn?.originToken?.symbol).length>0},enabled:D===`onramp-mesh`&&Oe&&!!wn?.originChain?.id&&!!wn?.originToken?.symbol&&!!ne&&!!re,staleTime:1440*60*1e3,gcTime:1440*60*1e3,refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),zn=Qe||en,Bn=Il(D)&&D!==`onramp-bluvo`,Vn=rt&&!!zn&&!wn,{effectiveBalanceFormatted:Hn,effectiveBalanceRaw:Un,effectiveTokenDecimals:Wn,effectiveBalanceLocaleDisplay:Gn,effectiveBalanceUsdDisplay:Kn,effectiveBalanceUsdLocaleDisplay:qn}=NE({fundMethod:D,meshEnabled:Oe,meshEnvironment:De,activeMeshExchangeKeys:je,activeMeshIntegrationIds:Ae,selectedMeshAccessTokens:we,originToken:R,trailsApiUrl:re,apiKey:ne,balanceFormatted:sn,balanceRaw:cn,tokenDecimals:un,balanceLocaleDisplay:dn,balanceUsdDisplay:fn,balanceUsdLocaleDisplay:pn}),{exchangeRate:Jn,isLoading:Yn}=Pu({fromCurrency:`USD`,toCurrency:rt&&Be?.currencyCode?Be.currencyCode:`USD`,disabled:!rt||!Be||Be?.currencyCode===`USD`}),Xn=Y(rt);q(()=>{Xn.current!==rt&&(Xn.current=rt,ct(rt&&We?We:!rt&&It?It:``))},[rt,We,It]);let Zn=kn?.[0]?.priceUsd??Ie?.priceUsd??R?.priceUsd??0;q(()=>{if(lt.current!==at){if(lt.current=at,ut)return;if(rt&&We){let e=bs(We);if(e>0)if(at&&Jn){let t=e/Jn,n=Number(t.toFixed(2)).toString();ct(n)}else{let t=Number(e.toFixed(2)).toString();ct(t)}}else if(!rt&&It){let e=bs(It);if(e>0)if(at&&Zn>0){let t=e*Zn,n=Rs.getRate(),r=n&&n.currency!==`USD`?t*n.rate:t,i=Number(r.toFixed(2)).toString();s.console.log(`[TRAILS EFFECT] Setting display value in useEffect:`,i,`from USD:`,t,`with rate:`,n?.rate),ct(i)}else{let t=Math.round(e*1e8)/1e8;ct(t.toString())}}}},[at,Jn,We,It,rt,Zn,ut]);let Qn=Y(Be);q(()=>{if(Be&&Qn.current!==Be){let e=N===`fiat`&&!(rt&&Be.currencyCode.toUpperCase()!==`USD`);ot(e),lt.current=e}Qn.current=Be},[Be,N,rt]),q(()=>{Be&&!ut&&!at&&st!==``&&We!==``&&We!=null&&ct(We)},[Be,We,ut,at,st]);let $n=Y(R);q(()=>{R&&!rt&&$n.current!==R&&(ot(N===`fiat`),lt.current=N===`fiat`),$n.current=R},[R,rt,N]),q(()=>{R&&!rt&&!ut&&!at&&st!==``&&It!==``&&It!=null&&ct(It)},[R,rt,It,ut,at,st]);let{createWidgetSession:er,isLoading:tr,error:nr}=AE(),[rr,ir]=X(!1),[ar,or]=X(!1),{supportedTokens:sr}=Rc({disabled:!d}),cr=J(()=>he.length===0?sr:[...sr,...he],[sr,he]),lr=Y(null);q(()=>{let e=`${d}-${u}`;if(d&&u&&cr?.length>0&&lr.current!==e){let t=cr?.find(e=>e.chainId===Number(u)&&(Pe(e.contractAddress,d)||e.symbol.toLowerCase()===d.toLowerCase()));if(t){s.console.log(`[trails-sdk] Fund: Setting destination token from toToken prop:`,t),oe(t),yn(t);let n=$(Number(u));n&&vn(n),lr.current=e}}else!d&&H&&(se(!1),Tt.current.hasManualDestinationSelection=!1,lr.current=null)},[d,u,cr,oe,yn,vn,H,se]);let ur=K(e=>{let t=e;e!==`0`&&e.length>1&&e.startsWith(`0`)&&e[1]!==`.`&&(t=e.replace(/^0+/,``)||`0`),Ft(ln.EXACT_INPUT),Lt(t)},[Ft,Lt]),dr=K(()=>{Ut===ln.EXACT_OUTPUT&&wn?.originAmountDisplay&&!It&&Lt(wn.originAmountDisplay)},[Ut,wn?.originAmountDisplay,It,Lt]);q(()=>{if(rt&&zn&&it?.contractAddress){let e=Number(zn.destinationAmount),t=Math.max(0,e-.25);s.console.log(`[trails-sdk] Adjusting onramp amount for fees:`,{originalAmount:e,adjustedAmount:t,feeSubtracted:.25}),Lt(t.toString()),Ft(ln.EXACT_INPUT)}},[rt,zn,it,Lt,Ft]),q(()=>{wn&&(Ut===ln.EXACT_OUTPUT&&wn.originAmountDisplay?Lt(wn.originAmountDisplay):Ut===ln.EXACT_INPUT&&wn.destinationAmountDisplay&&zt(wn.destinationAmountDisplay))},[wn,Ut,Lt,zt]),q(()=>{O&&O(on)},[on,O]),q(()=>{z&&!R&&!Dt&&(s.console.log(`[trails-sdk] Resetting hasManualOriginSelection - token was cleared`),B(!1))},[z,R,Dt,B]),q(()=>{z||!Me||R&&R.chainId===c.chainId&&Pe(R.contractAddress,c.contractAddress)||(s.console.log(`[Fund] Preselecting USDC on Base for Coinbase Mesh onramp`),ae(c))},[z,Me,R,ae]),q(()=>{ie||D!==`onramp-mesh`&&!R&&!Dt&&Et&&!z&&(s.console.log(`[trails-sdk] Auto-selecting origin token:`,Et),ae(Et))},[R,Dt,Et,ae,z,D,ie]),q(()=>{if(d)return;let e=z||ve(Tt.current.lastOriginSelectionTime,1e3),t=Tt.current.hasManualDestinationSelection||H||ve(Tt.current.lastDestinationSelectionTime,1e3);if(!V&&!kt&&Ot&&!t&&!e){s.console.log(`[trails-sdk] Auto-selecting destination token:`,Ot),oe(Ot),yn(Ot);let e=$(Ot.chainId);e&&vn(e)}},[V,kt,Ot,H,z,oe,yn,vn,d]),q(()=>{fr.current&&fr.current.focus()},[]);let fr=Y(null),[pr,mr]=X(!1),[hr,gr]=X(!1);q(()=>{V&&(s.console.log(`[trails-sdk] Syncing destination token to useSendForm:`,V),yn(V))},[V,yn]),q(()=>{if(!ce||!_n||!d)return;let e=_n.chainId===Number(u),t=_n.contractAddress?.toLowerCase()===d.toLowerCase()||_n.symbol?.toLowerCase()===d.toLowerCase();e&&t&&(V&&V.chainId===_n.chainId&&V.contractAddress?.toLowerCase()===_n.contractAddress?.toLowerCase()||(s.console.log(`[trails-sdk] Fund: Syncing resolved token from useSendForm to global provider:`,_n.symbol),oe(_n)))},[ce,_n,V,oe,d,u]);let _r=K(e=>{R&&R.symbol!==e.symbol&&(Lt(``),zt(``),ct(``),Ft(ln.EXACT_INPUT)),ae(e),ir(!1),B(!0),Tt.current.lastOriginSelectionTime=Date.now(),j?.(e),s.console.log(`[trails-sdk] selected origin token`,e)},[ae,B,j,R,Lt,zt,Ft]),vr=K(e=>{oe(e),yn(e);let t=$(e.chainId);t&&vn(t);let n=XE({destinationChainId:e.chainId,originChainId:R?.chainId,selectedRecipient:Re,connectedSolanaAddress:jt?.connected&&jt.publicKey?jt.publicKey.toBase58():null,evmFallbackAddress:o&&bn(o)?o:i?.address});n!==void 0&&n!==Re&&ze(n),or(!1),se(!0),Tt.current.hasManualDestinationSelection=!0,Tt.current.lastDestinationSelectionTime=Date.now(),j?.(e),s.console.log(`[trails-sdk] selected destination token`,e)},[oe,yn,vn,se,j,R?.chainId,Re,ze,jt,o,i?.address]),yr=K(e=>{rr?_r(e):ar&&vr(e)},[rr,ar,_r,vr]);return Xe?Z(Nw,{onBack:()=>Ze(!1),onSelectProvider:e=>{$e(e),Ze(!1)},selectedProvider:zn,providers:$t,isLoading:tn}):Ke?Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>qe(!1),headerContent:`Select Currency`,headerContentAlign:`left`}),Z(FE,{onCurrencySelect:e=>{Ve(e),qe(!1),Ue(!0)},onAutoSelect:e=>{Ve(e)},onSelectCountry:e=>{Ye(e)},onError:g,selectedCurrency:Be})]}):pr?Z(cb,{extraChains:Mt,disabledChains:Mn.disabledChains,onChainSelect:Nt,onBack:()=>{mr(!1),ir(!0)}}):rr?Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>ir(!1),headerContent:`Select From Token`,headerContentAlign:`left`,customActions:Se?void 0:Z(lb,{onError:g,fundMethod:D})}),Z(ib,{onTokenSelect:_r,onError:g,showContinueButton:!1,compactMode:!1,allSupportedTokens:!1,fundMethod:D,allowedChainIds:Mn.allowedChainIds,disabledChains:Mn.disabledChains,chainListScreen:!0,onNavigateToChainList:()=>{ir(!1),mr(!0)},recentTokens:A,onRecentTokenSelect:yr})]}):hr?Z(cb,{chains:pe,extraChains:me,disabledChains:Nn.disabledChains,onChainSelect:Fn,onBack:()=>{gr(!1),or(!0)}}):ar?Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>or(!1),headerContent:`Select destination token`,headerContentAlign:`left`,customActions:Z(lb,{onError:g,fundMethod:D,allSupportedTokens:!0,accountAddress:Xt})}),Z(ib,{onTokenSelect:vr,onError:g,allowedTokens:U,allowedTokenKeys:le,allowedTokenRestrictedChainIds:ue,allowedChainIds:Nn.allowedChainIds,catalogSupplementTokens:he,showContinueButton:!1,compactMode:!1,allSupportedTokens:!0,accountAddress:Xt,accountHeaderLabel:`Receiver`,fundMethod:D,disabledChains:Nn.disabledChains,includeSolanaChainFilter:_e,chainFilterChainId:Pn,onChainFilterChange:Fn,chainListScreen:!0,onNavigateToChainList:()=>{or(!1),gr(!0)},recentTokens:A,onRecentTokenSelect:yr})]}):Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>F(`fund-methods`),headerContent:`Fund`,headerContentAlign:`left`,showAccountActions:!0,customActions:ee?.hideSwap?void 0:Q(`button`,{type:`button`,onClick:()=>F(`swap`,{backTarget:`fund-form`}),className:`flex h-8 px-3 justify-center items-center gap-1.5 rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600`,title:`Swap`,children:[Z(xi,{className:`h-4 w-4`}),Z(`span`,{className:`text-sm font-medium`,children:`Swap`})]})}),Q(`form`,{onSubmit:async e=>{if(e.preventDefault(),s.console.log(`[trails-sdk] Creating widget session`,rt),rt&&zn&&Be){let{popup:t,blocked:n,error:r}=Uw(`meld-widget`,450,700);if(n){qt(r||`Popup blocked. Please allow popups for this site.`),g(r||`Popup blocked`);return}try{if(Gt(!0),qt(null),s.console.log(`[trails-sdk] prepareSendQuote`,wn),On){s.console.log(`[trails-sdk] Committing intent for onramp-meld flow`);try{await On({selectedFeeOption:En??null}),s.console.log(`[trails-sdk] Intent committed for onramp-meld`)}catch(e){s.console.error(`[trails-sdk] Failed to commit intent:`,e)}}let n=await er({depositAddress:wn?.originDepositAddress||``,userAddress:i?.address||``,countryCode:ht||``,sourceCurrencyCode:Be.currencyCode,sourceAmount:We,destinationCurrencyCode:`USDC_BASE`,serviceProvider:zn.serviceProvider,paymentMethodType:zn.paymentMethodType,lockFields:[`cryptoCurrency`,`destinationCurrencyCode`,`sourceCurrencyCode`,`walletAddress`]});s.console.log(`[Fund] Widget session response:`,n);let{widgetUrl:r,id:a,externalSessionId:o}=n;if(Tf({sessionId:rn?.sessionId||o,provider:zn?.serviceProvider||`Meld`,widgetUrl:r,depositAddress:wn?.originDepositAddress||``,userAddress:i?.address?.toLowerCase()||``,countryCode:ht||``,sourceCurrencyCode:Be?.currencyCode||``,sourceAmount:We,destinationCurrencyCode:`USDC_BASE`,paymentMethodType:zn?.paymentMethodType||``}),!Ww(t,r))throw Error(`Payment window was closed. Please try again.`);s.console.log(`[Fund] Opened onramp widget in popup`,{widgetUrl:r,meldTransactionId:a}),b&&wn&&(s.console.log(`[Fund] Calling onWaitingForOnrampConfirm with externalSessionId:`,o),b(wn,zn,{depositAddress:wn?.originDepositAddress||``,userAddress:i?.address?.toLowerCase()||``,countryCode:ht||``,sourceCurrencyCode:Be.currencyCode,sourceAmount:We,destinationCurrencyCode:`USDC_BASE`,serviceProvider:zn.serviceProvider,paymentMethodType:zn.paymentMethodType},o,t)),await mn(e)}catch(e){Gw(t),s.console.error(`[Fund] Error creating widget session`,e);let n=a(e)||`Failed to create widget session`;qt(n),g(n)}finally{Gt(!1)}return}s.console.log(`[trails-sdk] Calling handleSubmit from Fund`),mn(e)},className:`space-y-1`,children:[Q(`div`,{className:`pt-4 pb-4 trails-border-radius-container p-3 flex flex-col border border-gray-200 dark:border-gray-700 rounded-lg relative`,children:[Z(`div`,{className:`flex items-center justify-center`,children:Q(`div`,{className:`flex items-center justify-center space-x-2`,children:[Z(pb,{ref:fr,value:st,disabled:wt,onChange:e=>{let t=e.target.value;if(dt(!0),G.current&&clearTimeout(G.current),G.current=setTimeout(()=>{dt(!1)},300),t===``){ct(``),rt?Ge(``):Lt(``);return}if(rt){if(!t.match(/^\d*\.?\d{0,2}$/))return;if(ct(t),at&&Jn){let e=bs(t),n=Rs.getRate(),r=(n&&n.currency!==`USD`?e/n.rate:e)*Jn;Ge(r.toString())}else Ge(t)}else{let e=RegExp(`^\\d*\\.?\\d{0,${at?2:8}}$`);if(!t.match(e))return;if(ct(t),at&&Zn>0){let e=bs(t),n=Rs.getRate(),r=(n&&n.currency!==`USD`?e/n.rate:e)/Zn;ur(r.toString())}else ur(t)}},onFocus:dr,isLoading:gn&&Ut===ln.EXACT_OUTPUT,variant:`default`,inputSize:`large`,textAlign:`center`,isFiatInput:rt||at,currencySymbol:at?p[Rs.getRate()?.currency||`USD`]||`$`:rt?Be?.currencyCode:R?.symbol}),gn&&Ut===ln.EXACT_OUTPUT&&Z(Tw,{})]})}),rt&&(mt||_t)?Z(`div`,{className:`mt-2 text-center text-sm text-gray-500 dark:text-gray-400`,children:`Loading...`}):Z(`div`,{className:`mt-2 text-center text-sm`,children:rt?Be?.currencyCode===`USD`?st&&Number(st)>0?Q(`div`,{className:`text-xs text-gray-500 dark:text-gray-400 notranslate`,translate:`no`,children:[`≈ `,Ks(Number(st))]}):null:Jn!=null&&!Yn?Z(`div`,{className:`flex justify-center`,children:Q(`button`,{type:`button`,disabled:wt,onClick:()=>{let e=!at;if(ot(e),st){let t=parseFloat(st);if(vs(t)){if(e&&Jn){let e=t/Jn;ct(Number(e.toFixed(2)).toString())}else if(!e&&Jn){let e=t*Jn;ct(Number(e.toFixed(2)).toString())}}}},className:`text-xs transition-colors flex items-center gap-1 ${wt?`text-gray-400 cursor-not-allowed`:`text-blue-500 hover:text-blue-600 cursor-pointer`}`,title:Be?`${Be.currencyCode}`:``,children:[Q(`svg`,{"aria-hidden":`true`,width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[Z(`path`,{d:`M3.16669 6.5L5.50002 4.16667M5.50002 4.16667L7.83335 6.5M5.50002 4.16667L5.50002 11.8333`,stroke:`#3B82F6`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),Z(`path`,{d:`M12.8334 9.5L10.5 11.8333M10.5 11.8333L8.16669 9.5M10.5 11.8333L10.5 4.16667`,stroke:`#3B82F6`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),(()=>{let e=bs(st);if(at){let t=e*Jn,n=t>0?`${t.toFixed(2)} ${Be?.currencyCode}`:`0.00 ${Be?.currencyCode}`;return Q(`span`,{className:`notranslate`,translate:`no`,title:n,children:[`≈ `,n]})}else{let t=e/Jn;return Q(`span`,{className:`notranslate`,translate:`no`,title:Ks(t),children:[`≈ `,qs(t)]})}})()]})}):null:Z(`div`,{className:`flex justify-center`,children:Q(`button`,{type:`button`,onClick:()=>{let e=!at;if(s.console.log(`[TRAILS TOGGLE] Starting toggle, newMode (entering fiat):`,e),s.console.log(`[TRAILS TOGGLE] Current inputDisplayValue:`,st),s.console.log(`[TRAILS TOGGLE] tokenPriceUsd:`,Zn),ot(e),st&&Zn>0){let t=parseFloat(st);if(s.console.log(`[TRAILS TOGGLE] Parsed currentValue:`,t),vs(t)){let n=Rs.getRate();if(s.console.log(`[TRAILS TOGGLE] ForexRate data:`,n),e){let e=t*Zn;s.console.log(`[TRAILS TOGGLE] Token->Fiat: usdValue (token * price):`,e);let r=n&&n.currency!==`USD`?e*n.rate:e;s.console.log(`[TRAILS TOGGLE] Token->Fiat: displayValue after forex:`,r),s.console.log(`[TRAILS TOGGLE] Token->Fiat: forex rate used:`,n?.rate||`none (USD)`);let i=Number(r.toFixed(2)).toString();s.console.log(`[TRAILS TOGGLE] Token->Fiat: Setting input to:`,i),ct(i)}else{let e=n&&n.currency!==`USD`?t/n.rate:t;s.console.log(`[TRAILS TOGGLE] Fiat->Token: usdValue (input / rate):`,e),s.console.log(`[TRAILS TOGGLE] Fiat->Token: forex rate used:`,n?.rate||`none (USD)`);let r=e/Zn;s.console.log(`[TRAILS TOGGLE] Fiat->Token: tokenValue (usd / price):`,r);let i=Math.round(r*1e8)/1e8;ct(i.toString())}}}},className:`text-base text-blue-500 hover:text-blue-600 transition-colors cursor-pointer flex items-center gap-2 py-1.5`,title:R?`Toggle between USD and ${R.symbol}`:``,children:[Q(`svg`,{"aria-hidden":`true`,width:`20`,height:`20`,viewBox:`0 0 16 16`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[Z(`path`,{d:`M3.16669 6.5L5.50002 4.16667M5.50002 4.16667L7.83335 6.5M5.50002 4.16667L5.50002 11.8333`,stroke:`#3B82F6`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),Z(`path`,{d:`M12.8334 9.5L10.5 11.8333M10.5 11.8333L8.16669 9.5M10.5 11.8333L10.5 4.16667`,stroke:`#3B82F6`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),(()=>{let e=bs(st);if(s.console.log(`[TRAILS DISPLAY] isEnteringFiat:`,at),s.console.log(`[TRAILS DISPLAY] inputValue:`,e),at){let t=Rs.getRate();s.console.log(`[TRAILS DISPLAY] ForexRate data:`,t);let n=t&&t.currency!==`USD`?e/t.rate:e;s.console.log(`[TRAILS DISPLAY] Fiat mode - usdValue (input / rate):`,n);let r=Zn>0?n/Zn:0;s.console.log(`[TRAILS DISPLAY] Fiat mode - tokenAmount:`,r);let i=r>0?`${r.toFixed(8)} ${R?.symbol||``}`:`0 ${R?.symbol||``}`;return Q(`span`,{title:i,children:[`≈ `,i]})}else{let t=e*Zn;s.console.log(`[TRAILS DISPLAY] Token mode - usdAmount:`,t);let n=Ks(t),r=qs(t);return s.console.log(`[TRAILS DISPLAY] Token mode - displayValue:`,n),s.console.log(`[TRAILS DISPLAY] Token mode - localeValue:`,r),Q(`span`,{title:n,children:[`≈ `,r]})}})()]})})}),rt?Q(`div`,{className:`mt-3 flex justify-center items-center space-x-2`,children:[Z(`button`,{type:`button`,disabled:wt,className:`py-0.5 px-1.5 text-xs font-medium rounded-full transition-colors trails-bg-percentage-button trails-text-percentage-button ${wt?`opacity-50 cursor-not-allowed`:`cursor-pointer trails-hover-percentage-button`}`,onClick:()=>{if(Be?.currencyCode===`USD`)Ge(`25`),ct(`25`);else if(Jn){let e=25*Jn;Ge(e.toFixed(2)),ct(at?`25`:e.toString())}},children:`$25`}),Z(`button`,{type:`button`,disabled:wt,className:`py-0.5 px-1.5 text-xs font-medium rounded-full transition-colors trails-bg-percentage-button trails-text-percentage-button ${wt?`opacity-50 cursor-not-allowed`:`cursor-pointer trails-hover-percentage-button`}`,onClick:()=>{if(Be?.currencyCode===`USD`)Ge(`50`),ct(`50`);else if(Jn){let e=50*Jn;Ge(e.toFixed(2)),ct(at?`50`:e.toString())}},children:`$50`}),Z(`button`,{type:`button`,disabled:wt,className:`py-0.5 px-1.5 text-xs font-medium rounded-full transition-colors trails-bg-percentage-button trails-text-percentage-button ${wt?`opacity-50 cursor-not-allowed`:`cursor-pointer trails-hover-percentage-button`}`,onClick:()=>{if(Be?.currencyCode===`USD`)Ge(`100`),ct(`100`);else if(Jn){let e=100*Jn;Ge(e.toFixed(2)),ct(at?`100`:e.toString())}},children:`$100`})]}):R&&Hn&&D!==`direct-transfer`?Z(`div`,{className:`mt-3 flex justify-center items-center space-x-2`,children:Z(vT,{userBalance:Hn,userBalanceRaw:Un,decimals:Wn,isNativeToken:R.isNativeToken??!1,gasCostFormatted:wn?.gasCostFormatted,chainId:At||void 0,onAmountSelect:e=>{if(Ft(ln.EXACT_INPUT),Lt(e),zt(``),at&&Zn>0){let t=parseFloat(e)*Zn;ct(Number(t.toFixed(2)).toString())}else ct(e)},className:`opacity-100`})}):null,D===`onramp-mesh`&&Ce&&Z(`div`,{className:`mt-3 flex items-center justify-center`,children:Q(`div`,{className:`flex items-center gap-2 text-sm text-gray-900 dark:text-white`,children:[Z(`span`,{children:`Fund with`}),Z(Ay,{exchangeKey:Ce.exchangeKey,exchangeName:Ne,exchangeImageUrl:Ce.imageUrl,className:`h-5 w-5 rounded-full border border-solid border-gray-200 dark:border-gray-700`,imageClassName:`h-4 w-4 object-contain`,fallbackClassName:`text-[10px] font-semibold text-white`}),Z(`span`,{children:Ne})]})}),D===`onramp-bluvo`&&Te&&Z(`div`,{className:`mt-3 flex items-center justify-center`,children:Q(`div`,{className:`flex items-center gap-2 text-sm text-gray-900 dark:text-white`,children:[Z(`span`,{children:`Fund with`}),Z(`div`,{className:`h-5 w-5 overflow-hidden rounded-full border border-solid border-gray-200 dark:border-gray-700`,children:Te.logoUrl?Z(`img`,{src:Te.logoUrl,alt:Te.name,className:`h-full w-full object-contain`}):Z(`div`,{className:`flex h-full w-full items-center justify-center bg-blue-50 text-[10px] font-semibold text-blue-700 dark:bg-blue-900/30 dark:text-blue-200`,children:Te.name.slice(0,1)})}),Z(`span`,{children:Te.name})]})})]}),Q(`div`,{className:`mt-4 pt-4 pb-4 trails-border-radius-container p-3 mb-4 border border-gray-200 dark:border-gray-700 rounded-lg`,children:[Q(`div`,{className:`flex items-center justify-between mb-3 px-1`,children:[Z(`span`,{className:`text-sm font-medium text-black dark:text-white`,style:{minWidth:`138px`},children:`Sending`}),Z(`div`,{className:`w-7 flex-shrink-0`}),` `,o?Z(`span`,{className:`text-sm font-medium text-black dark:text-white`,style:{minWidth:`138px`},children:`Receiving`}):Z(KE,{selectedRecipient:Re,pulsating:In,showChainBadge:!1})]}),Q(`div`,{className:`flex items-center justify-between space-x-2`,children:[Z(`div`,{className:`min-w-[138px] flex flex-col mr-0`,children:rt?Z(IE,{currency:Be,onSelect:()=>qe(!0),unselectable:Ct}):wn?.noSufficientBalance?Z(`button`,{type:`button`,onClick:()=>{F(`fund-methods`)},className:`w-full flex items-center justify-center space-x-1.5 trails-border-radius-input px-2.5 py-1.5 border transition-all duration-200 bg-blue-500 hover:bg-blue-600 border-blue-500 text-white cursor-pointer`,children:Z(`span`,{className:`font-medium text-sm text-white`,children:`Add funds`})}):R?Z(gE,{token:R,chainId:At,onSelect:()=>ir(!0),fullWidth:!0}):Z(RE,{onClick:()=>{ir(!0)},className:`w-full flex items-center justify-center space-x-1.5 trails-border-radius-input px-2.5 py-1.5 border transition-all duration-200 bg-blue-500 hover:bg-blue-600 border-blue-700 text-white cursor-pointer`,children:Z(`span`,{className:`font-medium text-sm text-white`,children:`Select Token`})})}),Z(`div`,{className:`flex-shrink-0 mr-0`,children:Z(`div`,{className:`w-7 h-7 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center`,children:Z(`svg`,{"aria-hidden":`true`,xmlns:`http://www.w3.org/2000/svg`,width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,children:Z(`path`,{d:`M7.52861 2.86201C7.78895 2.60166 8.21096 2.60166 8.47131 2.86201L13.138 7.52868C13.3983 7.78903 13.3983 8.21104 13.138 8.47138L8.47131 13.1381C8.21096 13.3984 7.78895 13.3984 7.52861 13.1381C7.26826 12.8777 7.26826 12.4557 7.52861 12.1953L11.0573 8.6667H3.33329C2.9651 8.6667 2.66663 8.36822 2.66663 8.00003C2.66663 7.63184 2.9651 7.33336 3.33329 7.33336H11.0573L7.52861 3.80472C7.26826 3.54437 7.26826 3.12236 7.52861 2.86201Z`,fill:`black`})})})}),Z(`div`,{className:`min-w-[138px] flex`,children:Z(gE,{token:_n,chainId:_n?.chainId,onSelect:()=>or(!0),unselectable:!!d,fullWidth:!0})})]}),(!D||D===`wallet`||D===`onramp-mesh`)&&R&&Z(`div`,{className:`mt-3 pl-1 text-xs text-left`,children:wn?.noSufficientBalance?Q(`span`,{style:{color:`#F97316`},children:[`Insufficient funds`,Hn?`. Have ${Hn} ${R.symbol}`:``]}):Hn?Q(hi,{children:[Z(`span`,{className:`text-black dark:text-white notranslate`,translate:`no`,children:`Balance:`}),Q(`span`,{className:`text-gray-500 dark:text-gray-400 notranslate`,translate:`no`,children:[` ${Gn||Hn} `,R.symbol,Kn?Z(`span`,{className:`notranslate`,translate:`no`,children:` (${qn||Kn})`}):null]})]}):null})]}),Z(JE,{fundMethod:D,isSenderContractOnOrigin:!1,isSenderContractOnDestination:!1,isSequenceWallet:M}),!rt&&Bn&&Z(mE,{processedFeeOptions:Tn||[],selectedFeeOption:En,setSelectedFeeOption:Dn,chainId:R?.chainId,isRefetching:gn,originTokenInfo:An}),rt&&!tn&&!gn&&wn&&$t&&$t.length>0&&Z(LE,{providers:$t,selectedProvider:zn,trailsQuote:wn,setSelectedProvider:e=>{$e(e)},isRefetching:tn}),wn&&!gn&&!tn&&Z(`div`,{className:`mb-4`,children:Z(wb,{quote:wn,fiatToUsdExchangeRate:Jn,onRampQuote:zn,showContent:!0,swapMode:!1,isRefetching:gn,showInsufficientFunds:!1,isPassthrough:jg(wn.passthroughEligible,En,Tn)})}),rt&&nn&&Z(`div`,{className:`mt-4`,children:Z(XC,{errorPrettified:T(nn,`Error loading quote`),error:a(nn),severity:`error`})}),Kt&&Z(`div`,{className:`mt-4`,children:Z(XC,{errorPrettified:Kt,error:Kt,severity:`error`})}),Z(`button`,{type:`submit`,disabled:rt?!It||hn||Wt||!Be||!_n||!ht||!Xt||tn||tr||!zn||!!nn||!!nr||gn||Vn||!wn:!an||hn||!Sn||!Cn||Zt||gn||!wn||D===`onramp-mesh`&&(Rn||!Ln)||!rt&&D!==`direct-transfer`&&D!==`onramp-bluvo`&&wn?.noSufficientBalance||Bn&&jn,className:`w-full font-semibold py-4 px-4 trails-border-radius-button transition-colors bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white disabled:text-gray-500 disabled:cursor-not-allowed cursor-pointer relative`,children:hn||Wt||tr?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{}),Z(`span`,{children:Wt||tr?`Creating session...`:xn})]}):rt&&!wn&&!zn&&(nn||nr||Kt)?`Error Loading Quote`:D!==`direct-transfer`&&D!==`onramp-bluvo`&&wn?.noSufficientBalance?`Insufficient Balance`:D===`onramp-mesh`&&Rn?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:`Checking exchange funding...`})]}):D===`onramp-mesh`&&wn&&!Ln?`Exchange funding unavailable`:Zt?`Select recipient`:rt&&!We||!rt&&!It?`Enter amount`:rt&&(tn||gn||Vn||zn&&!wn)?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:`Getting quote...`})]}):rt&&!tn&&!gn&&!Vn&&wn?`Continue`:xn===`Getting quote...`?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:xn})]}):xn})]})]})},aD=({active:e=!1})=>e?Z(`div`,{className:`mb-2 p-3 rounded-lg bg-amber-50 border border-amber-200 dark:bg-amber-900/20 dark:border-amber-800`,children:Q(`div`,{className:`flex items-start gap-2`,children:[Z(ea,{className:`w-4 h-4 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5`}),Q(`div`,{className:`flex-1 min-w-0`,children:[Z(`p`,{className:`text-xs font-medium text-amber-800 dark:text-amber-200`,children:`Origin chain and wallet do not match`}),Z(`p`,{className:`text-xs text-amber-700 dark:text-amber-300 mt-0.5`,children:QT})]})]})}):null,oD=({selectedToken:e,onSend:t,onConfirm:n,onComplete:r,account:i,toRecipient:o,toAmount:c,toChainId:l,toToken:u,toCalldata:d,walletClient:f,onTransactionStateChange:p,onError:m,onWaitingForWalletConfirm:h,setWalletConfirmRetryHandler:g,swapProvider:_,bridgeProvider:v,swapProviderFallback:y,bridgeProviderFallback:b,fundMethod:x,onAmountUpdate:S,checkoutOnHandlers:C,recentTokens:w,onTrackToken:E,isSequenceWallet:D=!1})=>{let{mode:O,navigate:k}=y_(),A=wo(),{fundOptions:j}=A,M=To(A),N=Jr(),P=ni(),F=qu(),I=E_(i?.address),ee=J(()=>F&&x===`wallet`?[Ra]:void 0,[x,F]),{handleChainSelect:te}=D_(x??`wallet`),{tradeType:ne,buyAmount:re,setBuyAmount:ie,sellAmount:L,resetSwapState:R,enterFormMode:ae}=d_(),{selectedToken:z,setSelectedToken:B,hasManualSelection:V,setHasManualSelection:oe}=ul(),{selectedToken:H,setSelectedToken:se,hasManualSelection:ce,setHasManualSelection:U,isControlledByProps:le,availableDestinationTokens:ue,availableDestinationTokenKeys:de,availableDestinationTokenRestrictedChainIds:fe,availableDestinationChainIds:pe}=xl(),{destinationChainIds:me,destinationChainList:he,destinationChainListExtras:ge,destinationCatalogSupplementTokens:_e,destinationDisabledChains:ve,isEdgeDestinationSupported:ye}=rD(pe),{selectedRecipient:be,setSelectedRecipient:xe}=cu();q(()=>{ae(`fund-wallet`)},[]);let[Se,Ce]=X(re||``),[we,Te]=X(`token`),[Ee,De]=X(!1),[Oe,ke]=X(!1),[Ae,je]=X(!1),[Me,Ne]=X(!1),[Pe,Fe]=X(null),Ie=Y(null),Le=Y(!1);q(()=>{c&&!Le.current&&(Le.current=!0,ie(c),Ce(c))},[c,ie]),q(()=>{Ie.current?.focus()},[]);let Re=qE({selectedRecipient:be,toRecipient:o,accountAddress:i?.address,destinationChainId:H?.chainId??l??null}),ze=W(H?.chainId??l??0)&&!o;q(()=>{o&&xe(o)},[o,xe]);let Be=K(e=>{Ce(``),R(),r(e)},[r,R]),{amountRaw:Ve,handleSubmit:He,isSubmitting:Ue,isLoadingQuote:We,selectedDestToken:Ge,setSelectedDestinationChain:Ke,setSelectedDestToken:qe,buttonText:Je,destinationTokenAddress:Ye,isValidCustomToken:Xe,prepareSendQuote:Ze,processedFeeOptions:Qe,selectedFeeOption:$e,setSelectedFeeOption:et,quoteError:tt,quoteErrorPrettified:nt,isOriginFundingWalletMismatch:rt,balanceFormatted:it,balanceLocaleDisplay:at,balanceUsdDisplay:ot,balanceUsdLocaleDisplay:st,destTokenPrices:ct,isValidRecipient:lt}=nE({account:i,toAmount:ne===ln.EXACT_OUTPUT&&re||c,fromAmount:ne===ln.EXACT_INPUT?L:void 0,toRecipient:Re,toChainId:l,toToken:u,toCalldata:d,walletClient:f,onTransactionStateChange:p,onError:m,onWaitingForWalletConfirm:h,onSend:t,onConfirm:n,onComplete:Be,selectedToken:z||e||void 0,setWalletConfirmRetryHandler:g,tradeType:ne??void 0,swapProvider:_,bridgeProvider:v,swapProviderFallback:y,bridgeProviderFallback:b,fundMethod:x,mode:O,checkoutOnHandlers:C});q(()=>{S?.(Ve)},[Ve,S]),q(()=>{if(ne!==ln.EXACT_INPUT)return;let e=Ze?.destinationAmount;!e||e===re||(ie(e),we===`token`&&Ce(e))},[ne,Ze?.destinationAmount,re,ie,we]);let{defaultOriginToken:ut,isLoading:dt}=XT();q(()=>{M||!z&&!dt&&ut&&!V&&B(ut)},[z,dt,ut,B,V,M]);let{defaultDestinationToken:G,isLoading:pt}=OE(z);q(()=>{if(!u&&!H&&!pt&&G&&!ce){se(G),qe(G);let e=$(G.chainId);e&&Ke(e)}},[H,pt,G,ce,se,qe,Ke,u]);let{supportedTokens:mt}=Rc({disabled:!u}),ht=Y(null);q(()=>{let e=`${u}-${l}`;if(u&&l&&mt?.length>0&&ht.current!==e){let t=mt.find(e=>e.chainId===Number(l)&&(ft(e.contractAddress,u,e.chainId)||e.symbol.toLowerCase()===u.toLowerCase()));if(t){se(t),qe(t);let n=$(Number(l));n&&Ke(n),ht.current=e}}},[u,l,mt,se,qe,Ke]);let gt=J(()=>{let e=[...ve??[]];return W(z?.chainId??0)&&!e.includes(101)&&e.push(101),ZE({recipient:be,allowedChainIds:me,disabledChains:e.length>0?e:void 0})},[ve,z?.chainId,be,me]),_t=QE({fundMethod:x,allowedChainIds:null,disabledChains:J(()=>W(Ge?.chainId??H?.chainId??0)?[101]:void 0,[H?.chainId,Ge?.chainId])});nD({modeLabel:`Fund`,selectedRecipient:be,destinationToken:H,originChainId:z?.chainId,isDestinationLocked:le,defaultSolanaToken:_e[0],defaultEvmDestinationToken:G,availableDestinationTokens:ue,setDestinationToken:se,setSelectedDestToken:qe,setSelectedDestinationChain:Ke,setHasManualDestinationSelection:U,setDestinationChainFilterId:Fe}),q(()=>{H&&qe(H)},[H,qe]),q(()=>{if(!le||!Ge||!u)return;let e=Ge.chainId===Number(l),t=ft(Ge.contractAddress,u,Ge.chainId)||Ge.symbol?.toLowerCase()===u.toLowerCase();e&&t&&(H&&H.chainId===Ge.chainId&&ft(H.contractAddress,Ge.contractAddress,H.chainId)||se(Ge))},[le,Ge,H,se,u,l]);let vt=Ge||H,yt=ze&&!!z&&!!Ge&&!be,bt=x===`wallet`&&!!z?.chainId&&W(z.chainId),xt=J(()=>bt?Cd({evmAccountAddress:I,connectedWallets:N,svmWallet:F,session:P}):i?.address,[i?.address,N,I,bt,F,P]),St=J(()=>bt&&F?pd(F):void 0,[bt,F]),Ct=ct?.[0]?.priceUsd||Ze?.destinationTokenPriceUsd||0,wt=K(e=>{if(e===``){ie(``),Ce(``);return}let t=e;if(t!==`0`&&t.length>1&&t.startsWith(`0`)&&t[1]!==`.`&&(t=t.replace(/^0+/,``)||`0`),RegExp(`^\\d*\\.?\\d{0,${we===`usd`?2:8}}$`).test(t))if(Ce(t),we===`usd`){let e=parseFloat(t);if(Number.isFinite(e)&&Ct>0){let t=e/Ct;ie(t.toFixed(8).replace(/\.?0+$/,``))}else ie(``)}else ie(t)},[ie,we,Ct]);q(()=>{if(we!==`usd`||Ct<=0||!Se)return;let e=parseFloat(Se);if(!Number.isFinite(e)||e<=0)return;let t=(e/Ct).toFixed(8).replace(/\.?0+$/,``);t!==re&&ie(t)},[we,Ct,Se,re,ie]);let Tt=K(()=>{let e=we===`usd`?`token`:`usd`;if(Se&&Ct>0){let t=parseFloat(Se);if(Number.isFinite(t)&&t>0)if(e===`usd`){let e=t*Ct;Ce(Number(e.toFixed(2)).toString())}else{let e=t/Ct;Ce(e.toFixed(8).replace(/\.?0+$/,``)||`0`)}}Te(e)},[we,Se,Ct]),Et=J(()=>{let e=parseFloat(Se||`0`);if(!Number.isFinite(e)||e<=0||Ct<=0)return null;if(we===`usd`){let t=e/Ct;return`${t.toFixed(t<.01?8:6).replace(/\.?0+$/,``)} ${vt?.symbol||``}`.trim()}return`$${(e*Ct).toFixed(2)}`},[Se,Ct,we,vt?.symbol]),Dt=!Ze?.noSufficientBalance,Ot=+(we===`usd`)+(Se||`0`).length,kt=fb({inputValue:`x`.repeat(Ot),size:`large`,textAlign:we===`usd`?`left`:`center`}),At=(()=>{let e=Se||`0`,t=(e.match(/\./g)||[]).length,n=e.length-t;return Math.max(n+t*.3+.1,1)})();if(Oe)return Z(cb,{extraChains:ee,disabledChains:_t.disabledChains,onChainSelect:te,onBack:()=>{ke(!1),De(!0)}});if(Ee)return Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>De(!1),headerContent:`Fund with`,headerContentAlign:`left`,customActions:Z(lb,{onError:m,fundMethod:x})}),Z(ib,{onTokenSelect:e=>{B(e),oe(!0),De(!1),E?.(e),s.console.log(`[trails-sdk] selected origin token (exact-output)`,e)},onError:m,showContinueButton:!1,compactMode:!1,allSupportedTokens:!1,fundMethod:x,allowedChainIds:_t.allowedChainIds,disabledChains:_t.disabledChains,chainListScreen:!0,onNavigateToChainList:()=>{De(!1),ke(!0)},recentTokens:w})]});if(Me)return Z(cb,{chains:he,extraChains:ge,disabledChains:gt.disabledChains,onChainSelect:Fe,onBack:()=>{Ne(!1),je(!0)}});if(Ae)return Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>je(!1),headerContent:`Receive`,headerContentAlign:`left`,customActions:Z(lb,{onError:m,fundMethod:x,allSupportedTokens:!0,accountAddress:Re})}),Z(ib,{onTokenSelect:e=>{se(e),qe(e),U(!0);let t=$(e.chainId);t&&Ke(t);let n=XE({destinationChainId:e.chainId,originChainId:z?.chainId,selectedRecipient:be,connectedSolanaAddress:F?.connected&&F.publicKey?F.publicKey.toBase58():null,evmFallbackAddress:o&&bn(o)?o:i?.address});n!==void 0&&n!==be&&xe(n),je(!1),E?.(e),s.console.log(`[trails-sdk] selected destination token (exact-output)`,e)},onError:m,allowedTokens:ue,allowedTokenKeys:de,allowedTokenRestrictedChainIds:fe,allowedChainIds:gt.allowedChainIds,catalogSupplementTokens:_e,showContinueButton:!1,compactMode:!1,allSupportedTokens:!0,accountAddress:Re,accountHeaderLabel:`Receiver`,fundMethod:x,disabledChains:gt.disabledChains,includeSolanaChainFilter:ye,chainFilterChainId:Pe,onChainFilterChange:Fe,chainListScreen:!0,onNavigateToChainList:()=>{je(!1),Ne(!0)},recentTokens:w})]});let jt=Rl({originToken:z,originTokenBalance:z?.balance??`0`,originTokenAmount:Ze?.originAmountDisplay||``,isLoadingBalance:!1}),Mt=Il(x),Nt=!!$e&&!!jt&&Bl($e,jt),Pt=!re||Ue||!Ye||!Xe||We||!Ze||!Dt||ze&&!lt||Mt&&Nt,Ft=Ue?Je:re?ze&&!lt?`Select recipient`:Dt?We||Je===`Getting quote...`?Q(`span`,{className:`inline-flex items-center gap-2`,children:[Z(Tw,{}),` Getting quote...`]}):`Fund`:`Insufficient balance`:`Enter amount`;return Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>k(`fund-methods`),headerContent:`Fund`,headerContentAlign:`left`,showAccountActions:!0,customActions:j?.hideSwap?void 0:Q(`button`,{type:`button`,onClick:()=>k(`swap`,{backTarget:`fund-form`}),className:`flex h-8 px-3 justify-center items-center gap-1.5 rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600`,title:`Swap`,children:[Z(xi,{className:`h-4 w-4`}),Z(`span`,{className:`text-sm font-medium`,children:`Swap`})]})}),Q(`form`,{onSubmit:e=>{e.preventDefault(),He(e)},className:`space-y-3`,children:[Q(`div`,{className:`rounded-2xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 p-4 sm:p-5`,children:[Q(`div`,{className:`flex items-baseline justify-center mb-3 px-2 overflow-hidden`,children:[we===`usd`&&Z(`span`,{className:`leading-none font-semibold tabular-nums notranslate select-none ${Se?`text-gray-900 dark:text-white`:`text-gray-300 dark:text-gray-600`}`,style:{fontSize:kt.fontSize},translate:`no`,children:`$`}),Z(`input`,{ref:Ie,type:`text`,inputMode:`decimal`,value:Se,placeholder:`0`,onChange:e=>wt(e.target.value),"aria-label":`Amount to receive`,className:`bg-transparent outline-none leading-none font-semibold tabular-nums text-gray-900 dark:text-white placeholder-gray-300 dark:placeholder-gray-600 notranslate`,translate:`no`,style:{...kt,width:`${At}ch`,minWidth:`1ch`,maxWidth:`100%`}})]}),Z(`button`,{type:`button`,onClick:()=>je(!0),disabled:!!u,className:`mx-auto flex items-center gap-2 mb-3 ${u?`cursor-default`:`cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-full px-2 py-1 transition-colors`}`,children:vt?Q(hi,{children:[Z(Jy,{symbol:vt.symbol,imageUrl:vt.imageUrl,chainId:vt.chainId,contractAddress:vt.contractAddress,size:28}),Z(`span`,{className:`text-base font-semibold text-gray-900 dark:text-white`,children:vt.symbol}),!u&&Z(ki,{className:`h-4 w-4 text-gray-400 dark:text-gray-500`})]}):Q(`span`,{className:`text-base font-semibold text-blue-500`,children:[`Select token`,Z(ki,{className:`inline h-4 w-4 -mt-0.5`})]})}),Z(`div`,{className:`flex justify-center`,children:Q(`button`,{type:`button`,onClick:Tt,title:`Switch to ${we===`usd`?vt?.symbol||`token`:`USD`} input`,className:`flex items-center gap-1 py-0.5 px-2 rounded-full text-xs text-blue-500 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-500/10 transition-colors cursor-pointer`,children:[Q(`svg`,{"aria-hidden":`true`,width:`12`,height:`12`,viewBox:`0 0 16 16`,fill:`none`,children:[Z(`path`,{d:`M3.16669 6.5L5.50002 4.16667M5.50002 4.16667L7.83335 6.5M5.50002 4.16667L5.50002 11.8333`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),Z(`path`,{d:`M12.8334 9.5L10.5 11.8333M10.5 11.8333L8.16669 9.5M10.5 11.8333L10.5 4.16667`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),Q(`span`,{className:`notranslate tabular-nums`,translate:`no`,children:[`≈`,` `,Et||(we===`usd`?`0 ${vt?.symbol||``}`:`$0.00`)]})]})})]}),Z(JE,{fundMethod:x,isSenderContractOnOrigin:!1,isSenderContractOnDestination:!1,isSequenceWallet:D}),Mt&&Qe.length>1&&Z(mE,{processedFeeOptions:Qe,selectedFeeOption:$e,setSelectedFeeOption:et,chainId:z?.chainId,isRefetching:We,originTokenInfo:jt}),Q(`div`,{className:`rounded-2xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 overflow-hidden`,children:[Q(`button`,{type:`button`,onClick:()=>De(!0),className:`w-full px-4 py-3 sm:px-5 flex items-center gap-3 cursor-pointer
87
+ hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors text-left`,children:[Z(`span`,{className:`text-sm font-medium text-gray-900 dark:text-white`,children:`Fund with`}),z?Q(`span`,{className:`flex items-center gap-2 min-w-0`,children:[Z(Jy,{symbol:z.symbol,imageUrl:z.imageUrl,chainId:z.chainId,contractAddress:z.contractAddress,size:24}),Z(`span`,{className:`text-sm font-semibold text-gray-900 dark:text-white truncate`,children:z.symbol})]}):Z(`span`,{className:`text-sm text-gray-500 dark:text-gray-400`,children:`Select token`}),Q(`span`,{className:`ml-auto flex items-center gap-0.5 text-sm font-medium text-blue-500`,children:[`Change`,Z(ki,{className:`h-4 w-4`})]})]}),xt&&Q(hi,{children:[Z(`div`,{className:`border-t border-gray-100 dark:border-gray-800 bg-white dark:bg-gray-900`}),Q(`button`,{type:`button`,onClick:()=>k(`fund-methods`),className:`w-full flex items-center justify-between px-4 py-3 sm:px-5 cursor-pointer
88
+ hover:bg-gray-50 dark:hover:bg-gray-800/50
89
+ transition-colors text-left`,children:[Z(`span`,{className:`text-sm font-medium text-gray-900 dark:text-white`,children:`From`}),Q(`span`,{className:`flex items-center gap-2 min-w-0 text-sm font-medium text-blue-500 dark:text-blue-300`,children:[bt&&(St||F?.walletId)?Z(Na,{walletId:F?.walletId,icon:St,label:F?.walletName??`Solana wallet`,size:18,className:`shrink-0`,imageClassName:`shrink-0 rounded-full object-cover`,fallback:Z(Wy,{walletAddress:xt,size:18,showWalletConnectorIcon:!0})}):Z(Wy,{walletAddress:xt,size:18,showWalletConnectorIcon:!0}),Z(cw,{address:xt,startChars:4,endChars:4,className:`truncate`}),Z(ki,{className:`h-4 w-4 shrink-0 text-blue-500 dark:text-blue-300`})]})]})]}),ze&&Q(hi,{children:[Z(`div`,{className:`border-t border-gray-100 dark:border-gray-800 bg-white dark:bg-gray-900`}),Q(`div`,{className:`w-full flex items-center justify-between px-4 py-3 sm:px-5`,children:[Z(`span`,{className:`text-sm font-medium text-gray-900 dark:text-white`,children:`To`}),Z(KE,{selectedRecipient:be,pulsating:yt,showChainBadge:!1})]})]})]}),z&&it&&!Ze?.noSufficientBalance&&Q(`div`,{className:`px-1 text-xs text-gray-500 dark:text-gray-400 notranslate`,translate:`no`,children:[`Funding balance: `,at||it,` `,z.symbol,ot?` (${st||ot})`:``]}),z&&Ze?.noSufficientBalance&&Q(`div`,{className:`px-1 text-xs`,style:{color:`#F97316`},children:[`Insufficient funds`,it?`. Have ${it} ${z.symbol}`:``]}),Z(aD,{active:rt}),tt&&!rt&&Z(XC,{errorPrettified:nt||T(tt,`Error loading quote`),error:a(tt),severity:`error`}),Z(`button`,{type:`submit`,disabled:Pt,className:`w-full font-semibold py-4 px-4 trails-border-radius-button transition-colors bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white disabled:text-gray-500 disabled:cursor-not-allowed cursor-pointer relative`,children:Ft})]})]})},sD=e=>{let{setTradeType:t}=d_(),{fundMethod:n,tradeType:r=`EXACT_INPUT`}=e,{fromAmount:i}=wo(),a=r===`EXACT_OUTPUT`&&(!n||n===`wallet`),o=a&&!i?ln.EXACT_OUTPUT:ln.EXACT_INPUT;return q(()=>{t(o)},[o,t]),Z(a?oD:iD,{...e})},cD=({selectedToken:e,onSend:t,onConfirm:n,onComplete:r,account:i,toRecipient:a,toAmount:o,toChainId:c,toToken:l,toCalldata:u,walletClient:d,onTransactionStateChange:f,onError:m,onWaitingForWalletConfirm:h,setWalletConfirmRetryHandler:g,swapProvider:_,bridgeProvider:v,swapProviderFallback:y,bridgeProviderFallback:b,onAmountUpdate:x,checkoutOnHandlers:S,recentTokens:C,onTrackToken:w,isSequenceWallet:T=!1,fromToken:E,fromChainId:D,defaultInputMode:O})=>{let{mode:k,navigate:A}=y_(),j=To({fromToken:E,fromChainId:D}),M=!E,{isBalanceVisible:N}=vu(),{selectedToken:P,setSelectedToken:F,hasManualSelection:I,setHasManualSelection:ee,availableOriginTokens:te,availableOriginTokenKeys:ne,availableOriginTokenRestrictedChainIds:re,availableOriginChainIds:ie}=ul(),{selectedToken:L,setSelectedToken:R,hasManualSelection:ae,setHasManualSelection:z,availableDestinationTokens:B}=xl(),V=J(()=>nl(ie),[ie]),{destinationChainListExtras:oe,destinationCatalogSupplementTokens:H,destinationDisabledChains:se,isEdgeDestinationSupported:ce}=rD(null),{token:U,isLoadingBalance:le}=ev(P,ZT(P,i?.address)),{selectedRecipient:ue,setSelectedRecipient:de}=cu(),fe=qu(),pe=Y({hasManualDestinationSelection:!1,lastOriginSelectionTime:0,lastDestinationSelectionTime:0}),{defaultOriginToken:me,isLoading:he}=XT(),{defaultDestinationToken:ge,isLoading:_e}=OE(P),[ye,be]=X(e?.chainId||P?.chainId),{tradeType:xe,setTradeType:Se,sellAmount:Ce,setSellAmount:we,buyAmount:Te,setBuyAmount:Ee,resetSwapState:De,enterFormMode:Oe}=d_();q(()=>{Oe(`withdraw`)},[]),x_((a==null||a===``)&&!ue,`recipients`,{backTarget:`withdraw`}),q(()=>{a&&(s.console.log(`[trails-sdk] Withdraw Setting selectedRecipient to toRecipient:`,a),de(a))},[a,de]);let ke=L?.chainId??c??null,Ae=W(Number(ke)),je=W(Number(P?.chainId));q(()=>{Ae&&(je||ue||!fe?.connected||!fe.publicKey||de(fe.publicKey.toBase58()))},[Ae,je,ue,de,fe?.connected,fe?.publicKey]);let Me=qE({selectedRecipient:ue,toRecipient:a,accountAddress:i?.address,destinationChainId:ke}),Ne=Me??null,Fe=Ae&&!Me,Ie=xe||ln.EXACT_INPUT,[Le,Re]=X(O===`fiat`),[ze,Be]=X(``),[Ve,He]=X(!1),Ue=Y(null);q(()=>()=>{Ue.current&&clearTimeout(Ue.current)},[]);let We=K(e=>{Be(``),De(),r(e)},[r,De]),{amount:Ge,amountRaw:Ke,balanceFormatted:qe,balanceRaw:Je,tokenDecimals:Ye,balanceLocaleDisplay:Xe,balanceUsdDisplay:Ze,balanceUsdLocaleDisplay:Qe,handleSubmit:$e,isSubmitting:et,isLoadingQuote:tt,selectedDestToken:nt,setSelectedDestinationChain:rt,setSelectedDestToken:it,buttonText:at,destinationTokenAddress:ot,isValidCustomToken:st,prepareSendQuote:ct,processedFeeOptions:lt,selectedFeeOption:ut,setSelectedFeeOption:dt,sourceTokenPrices:G}=nE({account:i,toAmount:Ie===ln.EXACT_OUTPUT?Te:o,fromAmount:Ie===ln.EXACT_INPUT?Ce:void 0,toRecipient:Me,toChainId:c,toToken:l,toCalldata:u,walletClient:d,onTransactionStateChange:f,onError:m,onWaitingForWalletConfirm:h,onSend:t,onConfirm:n,onComplete:We,selectedToken:P??void 0,setWalletConfirmRetryHandler:g,tradeType:Ie,swapProvider:_,bridgeProvider:v,swapProviderFallback:y,bridgeProviderFallback:b,fundMethod:`wallet`,mode:k,checkoutOnHandlers:S}),ft=Rl({originToken:U??P,originTokenBalance:U?.balance??P?.balance,originTokenAmount:Ce,isLoadingBalance:le}),pt=!!ut&&!!ft&&Bl(ut,ft),mt=QE({fundMethod:`wallet`,allowedChainIds:ie,disabledChains:J(()=>W(nt?.chainId??0)?[101]:void 0,[nt?.chainId])}),ht=J(()=>{let e=[...se??[]];return W(P?.chainId??0)&&!e.includes(101)&&e.push(101),ZE({recipient:Ne,allowedChainIds:null,disabledChains:e.length>0?e:void 0})},[se,P?.chainId,Ne]),gt=G?.[0]?.priceUsd||0,_t=K(e=>{let t=e;e!==`0`&&e.length>1&&e.startsWith(`0`)&&e[1]!==`.`&&(t=e.replace(/^0+/,``)||`0`),Se(ln.EXACT_INPUT),we(t)},[Se,we]);q(()=>{ct&&(Ie===ln.EXACT_OUTPUT&&ct.originAmountDisplay?we(ct.originAmountDisplay):Ie===ln.EXACT_INPUT&&ct.destinationAmountDisplay&&Ee(ct.destinationAmountDisplay))},[ct,Ie,we,Ee]),q(()=>{x&&x(Ke)},[Ke,x]),q(()=>{I&&!P&&!he&&(s.console.log(`[trails-sdk] Resetting hasManualOriginSelection - token was cleared`),ee(!1))},[I,P,he,ee]),q(()=>{j||!P&&!he&&me&&!I&&(s.console.log(`[trails-sdk] Auto-selecting origin token:`,me),F(me),be(me.chainId))},[P,he,me,F,I,j]),q(()=>{if(l)return;let e=I||ve(pe.current.lastOriginSelectionTime,1e3),t=pe.current.hasManualDestinationSelection||ae||ve(pe.current.lastDestinationSelectionTime,1e3);if(!L&&!_e&&ge&&!t&&!e){s.console.log(`[trails-sdk] Auto-selecting destination token:`,ge),R(ge),it(ge);let e=$(ge.chainId);e&&rt(e)}},[L,_e,ge,ae,I,R,it,rt,l]),q(()=>{vt.current&&vt.current.focus()},[]);let vt=Y(null),[yt,bt]=X(!1),[xt,St]=X(!1),[Ct,wt]=X(!1),[Tt,Et]=X(!1),[Dt,Ot]=X(null);nD({modeLabel:`Withdraw`,selectedRecipient:ue,destinationToken:L,originChainId:P?.chainId,isDestinationLocked:!!l&&!!c,defaultSolanaToken:H[0],defaultEvmDestinationToken:ge,availableDestinationTokens:B,setDestinationToken:R,setSelectedDestToken:it,setSelectedDestinationChain:rt,setHasManualDestinationSelection:z,setDestinationChainFilterId:Ot});let kt=J(()=>fe?[Ra]:void 0,[fe]),{handleChainSelect:At}=D_(`wallet`),{supportedTokens:jt}=Rc({disabled:!!l||yt||xt}),Mt=Y(null);q(()=>{let e=`${l}-${c}`;if(l&&c&&jt?.length>0&&Mt.current!==e){let t=jt?.find(e=>e.chainId===Number(c)&&(Pe(e.contractAddress,l)||e.symbol.toLowerCase()===l.toLowerCase()));if(t){s.console.log(`[trails-sdk] Withdraw: Setting destination token from toToken prop:`,t),R(t),it(t);let n=$(Number(c));n&&rt(n),Mt.current=e}}else!l&&ae&&(z(!1),pe.current.hasManualDestinationSelection=!1,Mt.current=null)},[l,c,jt,R,it,rt,ae,z]),q(()=>{L&&(s.console.log(`[trails-sdk] Syncing destination token to useSendForm:`,L),it(L))},[L,it]);let Nt=Y(null);q(()=>{let e=`${E}-${D}`;if(E&&D&&jt?.length>0&&Nt.current!==e){let t=jt?.find(e=>e.chainId===Number(D)&&(Pe(e.contractAddress,E)||e.symbol.toLowerCase()===E.toLowerCase()));t&&(s.console.log(`[trails-sdk] Withdraw: Setting origin token from fromToken prop:`,t),F(t),be(t.chainId),ee(!0),Nt.current=e)}},[E,D,jt,F,ee]);let Pt=K(e=>{(!P||P.symbol!==e.symbol)&&(we(``),Ee(``),Se(ln.EXACT_INPUT),Be(``)),F(e),be(e.chainId),bt(!1),ee(!0),pe.current.lastOriginSelectionTime=Date.now(),w?.(e),s.console.log(`[trails-sdk] selected origin token`,e)},[F,ee,w,P,we,Ee,Se]),Ft=K(e=>{R(e),it(e);let t=$(e.chainId);t&&rt(t),St(!1),z(!0),pe.current.hasManualDestinationSelection=!0,pe.current.lastDestinationSelectionTime=Date.now(),w?.(e),s.console.log(`[trails-sdk] selected destination token`,e)},[R,it,rt,z,w]),It=K(e=>{yt?Pt(e):xt&&Ft(e)},[yt,xt,Pt,Ft]);return Ct?Z(cb,{chains:V,extraChains:kt,disabledChains:mt.disabledChains,onChainSelect:At,onBack:()=>{wt(!1),bt(!0)}}):yt?Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>bt(!1),headerContent:`Select Token to Withdraw`,headerContentAlign:`left`,customActions:Z(lb,{onError:m})}),Z(ib,{onTokenSelect:Pt,onError:m,allowedTokens:te,allowedTokenKeys:ne,allowedTokenRestrictedChainIds:re,allowedChainIds:mt.allowedChainIds,showContinueButton:!1,compactMode:!1,allSupportedTokens:!1,fundMethod:`wallet`,disabledChains:mt.disabledChains,chainListScreen:!0,onNavigateToChainList:()=>{bt(!1),wt(!0)},recentTokens:C,onRecentTokenSelect:It})]}):Tt?Z(cb,{extraChains:oe,disabledChains:ht.disabledChains,onChainSelect:Ot,onBack:()=>{Et(!1),St(!0)}}):xt?Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>St(!1),headerContent:`Select Token to Receive`,headerContentAlign:`left`,customActions:Z(lb,{onError:m,fundMethod:`wallet`,allSupportedTokens:!0})}),Z(ib,{onTokenSelect:Ft,onError:m,showContinueButton:!1,compactMode:!1,allSupportedTokens:!0,fundMethod:`wallet`,allowedChainIds:ht.allowedChainIds,disabledChains:ht.disabledChains,catalogSupplementTokens:H,includeSolanaChainFilter:ce,chainFilterChainId:Dt,onChainFilterChange:Ot,chainListScreen:!0,onNavigateToChainList:()=>{St(!1),Et(!0)},recentTokens:C,onRecentTokenSelect:It})]}):Q(`div`,{className:`space-y-2`,children:[Z(M_,{headerContent:`Withdraw`,headerContentAlign:`left`,showAccountActions:!0,customActions:Q(`button`,{type:`button`,onClick:()=>A(`swap`,{backTarget:`withdraw`}),className:`flex h-8 px-3 justify-center items-center gap-1.5 rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600`,title:`Swap`,children:[Z(xi,{className:`h-4 w-4`}),Z(`span`,{className:`text-sm font-medium`,children:`Swap`})]})}),Q(`form`,{onSubmit:e=>{e.preventDefault(),s.console.log(`[trails-sdk] Calling handleSubmit from Withdraw`),$e(e)},className:`space-y-1`,children:[Q(`div`,{className:`pt-4 pb-4 trails-border-radius-container p-3 flex flex-col border border-gray-200 dark:border-gray-700 rounded-lg relative`,children:[Z(`div`,{className:`flex items-center justify-center`,children:Q(`div`,{className:`flex items-center justify-center space-x-2`,children:[Z(pb,{ref:vt,value:ze,onChange:e=>{let t=e.target.value;if(He(!0),Ue.current&&clearTimeout(Ue.current),Ue.current=setTimeout(()=>{He(!1)},300),t===``){Be(``),we(``);return}let n=RegExp(`^\\d*\\.?\\d{0,${Le?2:8}}$`);if(t.match(n))if(Be(t),Le&&gt>0){let e=bs(t),n=Rs.getRate(),r=(n&&n.currency!==`USD`?e/n.rate:e)/gt;_t(r.toString())}else _t(t)},isLoading:tt&&Ie===ln.EXACT_OUTPUT,variant:`default`,inputSize:`large`,textAlign:`center`,isFiatInput:Le,currencySymbol:Le?p[Rs.getRate()?.currency||`USD`]||`$`:P?.symbol}),tt&&Ie===ln.EXACT_OUTPUT&&Z(Tw,{})]})}),!M&&Z(`div`,{className:`mt-3 flex justify-center`,children:Q(`div`,{className:`flex items-center space-x-1 text-sm`,children:[Z(`span`,{className:`text-gray-500 dark:text-gray-400`,children:`To:`}),Z(KE,{selectedRecipient:Ne,showChainBadge:!1})]})}),Z(`div`,{className:`mt-2 text-center text-sm`,children:Z(`div`,{className:`flex justify-center`,children:Q(`button`,{type:`button`,onClick:()=>{let e=!Le;if(Re(e),ze&&gt>0){let t=parseFloat(ze);if(vs(t)){let n=Rs.getRate();if(e){let e=t*gt,r=n&&n.currency!==`USD`?e*n.rate:e,i=Number(r.toFixed(2)).toString();Be(i)}else{let e=(n&&n.currency!==`USD`?t/n.rate:t)/gt,r=Math.round(e*1e8)/1e8;Be(r.toString())}}}},className:`text-xs text-blue-500 hover:text-blue-600 transition-colors cursor-pointer flex items-center gap-1`,title:P?`Toggle between USD and ${P.symbol}`:``,children:[Q(`svg`,{"aria-hidden":`true`,width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[Z(`path`,{d:`M3.16669 6.5L5.50002 4.16667M5.50002 4.16667L7.83335 6.5M5.50002 4.16667L5.50002 11.8333`,stroke:`#3B82F6`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),Z(`path`,{d:`M12.8334 9.5L10.5 11.8333M10.5 11.8333L8.16669 9.5M10.5 11.8333L10.5 4.16667`,stroke:`#3B82F6`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),(()=>{let e=bs(ze);if(Le){let t=Rs.getRate(),n=t&&t.currency!==`USD`?e/t.rate:e,r=gt>0?n/gt:0,i=r>0?`${r.toFixed(8)} ${P?.symbol||``}`:`0 ${P?.symbol||``}`;return Q(`span`,{title:i,children:[`≈ `,i]})}else{let t=e*gt;return Q(`span`,{title:Ks(t),children:[`≈ `,qs(t)]})}})()]})})}),P&&qe&&Z(`div`,{className:`mt-3 flex justify-center items-center space-x-2`,children:Z(vT,{userBalance:qe,userBalanceRaw:Je,decimals:Ye,isNativeToken:P.isNativeToken??!1,gasCostFormatted:ct?.gasCostFormatted,chainId:ye||void 0,onAmountSelect:e=>{if(Se(ln.EXACT_INPUT),we(e),Ee(``),Le&&gt>0){let t=parseFloat(e)*gt;Be(Number(t.toFixed(2)).toString())}else Be(e)},className:`opacity-100`})})]}),Q(`div`,{className:`mt-4 pt-4 pb-4 trails-border-radius-container p-3 mb-4 border border-gray-200 dark:border-gray-700 rounded-lg`,children:[Q(`div`,{className:`flex items-center justify-between mb-3 px-1`,children:[Q(`div`,{className:`flex flex-col`,style:{minWidth:`138px`},children:[Z(`span`,{className:`text-sm font-medium text-black dark:text-white`,children:M?`From`:`Withdraw`}),M&&Z(`div`,{className:`mt-1`,children:Z(hE,{sendToScreen:{screen:`select-funding-wallet`,backScreen:`withdraw`}})})]}),Z(`div`,{className:`w-7 shrink-0`}),Q(`div`,{className:`flex flex-col`,style:{minWidth:`138px`},children:[Z(`span`,{className:`text-sm font-medium text-black dark:text-white`,children:M?`To`:`Receive`}),M&&Z(`div`,{className:`mt-1`,children:Z(KE,{selectedRecipient:Ne,showChainBadge:!1})})]})]}),Q(`div`,{className:`flex items-center justify-between space-x-2`,children:[Z(`div`,{className:`min-w-[138px] flex flex-col mr-0 py-3.5`,children:Z(gE,{token:P,chainId:ye,onSelect:()=>bt(!0),unselectable:!!E,fullWidth:!0})}),Z(`div`,{className:`shrink-0 mr-0`,children:Z(`div`,{className:`w-7 h-7 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center`,children:Z(`svg`,{"aria-hidden":`true`,xmlns:`http://www.w3.org/2000/svg`,width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,children:Z(`path`,{d:`M7.52861 2.86201C7.78895 2.60166 8.21096 2.60166 8.47131 2.86201L13.138 7.52868C13.3983 7.78903 13.3983 8.21104 13.138 8.47138L8.47131 13.1381C8.21096 13.3984 7.78895 13.3984 7.52861 13.1381C7.26826 12.8777 7.26826 12.4557 7.52861 12.1953L11.0573 8.6667H3.33329C2.9651 8.6667 2.66663 8.36822 2.66663 8.00003C2.66663 7.63184 2.9651 7.33336 3.33329 7.33336H11.0573L7.52861 3.80472C7.26826 3.54437 7.26826 3.12236 7.52861 2.86201Z`,fill:`currentColor`,className:`text-gray-900 dark:text-white`})})})}),Z(`div`,{className:`min-w-[138px] flex`,children:Z(gE,{token:nt,chainId:nt?.chainId,onSelect:()=>St(!0),unselectable:!!l,fullWidth:!0})})]}),P&&Z(`div`,{className:`mt-3 pl-1 text-xs text-left`,children:ct?.noSufficientBalance||!le&&Je!==void 0&&Je!==``&&BigInt(Je)===0n?Z(`span`,{style:{color:`#F97316`},children:`Insufficient funds`}):qe?Q(hi,{children:[Z(`span`,{className:`text-black dark:text-white notranslate`,translate:`no`,children:`Balance:`}),Q(`span`,{className:`text-gray-500 dark:text-gray-400 notranslate`,translate:`no`,children:[` `,N?`${Xe||qe} ${P.symbol}`:`••••••`,Ze&&N?Q(`span`,{className:`notranslate`,translate:`no`,children:[` `,`(`,Qe||Ze,`)`]}):null]})]}):null})]}),Z(mE,{processedFeeOptions:lt||[],selectedFeeOption:ut,setSelectedFeeOption:dt,chainId:P?.chainId,isRefetching:tt,originTokenInfo:ft}),ct&&!tt&&Z(`div`,{className:`mb-4`,children:Z(wb,{quote:ct,showContent:!0,swapMode:!1,isRefetching:tt,showInsufficientFunds:!1})}),Z(`button`,{type:`submit`,disabled:!Ge||et||!ot||!st||Fe||tt||!ct||ct?.noSufficientBalance||pt,className:`w-full font-semibold py-4 px-4 trails-border-radius-button transition-colors bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white disabled:text-gray-500 disabled:cursor-not-allowed cursor-pointer relative`,children:et?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:at})]}):ct?.noSufficientBalance?`Insufficient Balance`:Fe?`Select recipient`:Ce?at===`Getting quote...`?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:at})]}):at||`Make withdrawal`:`Enter amount`})]})]})},lD=({address:e,children:t,stopPropagation:n=!0,className:r=``,onCopy:i})=>{let[a,o]=X(!1);return Q(`span`,{className:`relative inline-block`,children:[Z(`button`,{type:`button`,onClick:async t=>{n&&(t.preventDefault(),t.stopPropagation());try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),2*Ee),i?.()}catch(e){s.console.error(`[trails-sdk] Failed to copy address:`,e)}},className:`inline cursor-pointer rounded-md border-none text-inherit transition-all duration-300 ease-out hover:underline ${a?`bg-green-100 px-1 py-0.5 text-green-900 shadow-sm dark:bg-green-700 dark:text-green-50 dark:ring-green-400/70`:`bg-transparent p-0 px-0.5 -mx-0.5`} ${r}`,title:a?`Copied!`:`Click to copy`,"aria-label":a?`Address copied`:`Copy address`,children:t}),a?Z(`span`,{className:`pointer-events-none absolute -top-6 left-1/2 z-10 -translate-x-1/2 whitespace-nowrap rounded-md bg-green-600 px-2 py-1 text-[11px] font-semibold text-white shadow-md animate-in fade-in-0 zoom-in-95 dark:bg-green-500`,"aria-live":`polite`,children:`Copied`}):null]})},uD=[`wallet`,`onramp-meld`,`direct-transfer`,`onramp-mesh`],dD={"connected-wallet":`wallet`,"crypto-transfer":`direct-transfer`,"cc-onramp":`onramp-meld`,exchange:`onramp-mesh`,"exchange-onramp":`onramp-mesh`};function fD({fundMethodsList:e,hideUnlistedFundMethods:t=!1}){if(!e?.length)return{orderedMethods:[...uD],disabledMethods:new Set};let n=new Set,r=[];for(let t of e){let e=dD[t];!e||n.has(e)||(n.add(e),r.push(e))}if(t)return{orderedMethods:r,disabledMethods:new Set};let i=uD.filter(e=>!n.has(e));return{orderedMethods:[...r,...i],disabledMethods:new Set(i)}}const pD=`w-full text-left px-4 py-3 flex items-center justify-between transition-colors trails-hover-bg rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900`,mD=`${pD} cursor-not-allowed opacity-50`;function hD(e){let t=e.connector,n=t?{id:t.id??``,name:t.name??``}:void 0,r=t?.type?.toLowerCase(),i=t?.flow?.toLowerCase(),a=t?.uid?.toLowerCase();return Hr(n)||r===`walletconnect`||i===`walletconnect`||a?.includes(`:walletconnect`)===!0}const gD=({headerContent:e,onramp:t,onSelectTransferCrypto:n,onSelectOnrampMeld:r,onSelectOnrampExchange:i,onSelectWalletConnect:a,onSelectConnectedAccount:o})=>{let{address:c,chainId:l}=Yr(),u=Xr(),d=Jr(),f=ni(),{disconnect:p,switchAccount:m}=ai(),{mode:h}=y_(),g=ux(),{selectedFundMethod:_,setSelectedFundMethod:v,setPaymentMethod:b,selectedFundingWallet:x,setSelectedFundingWallet:S}=Vu(),{selectedToken:C,clearSelectedToken:w,setHasManualSelection:T}=ul(),{clearChainFilter:E}=mu(),{setConnectionContext:D}=$o(),{fundOptions:O,hideAddWallet:k}=wo(),A=O?.hideWallets??[],j=O?.fundMethodsList,M=O?.hideUnlistedFundMethods??!1,N=qu(),{selectedToken:P}=xl(),F=W(P?.chainId??0),I=h===`swap`||h===`fund`,ee=d.filter(e=>!(A.length>0&&A.some(t=>t.toLowerCase()===e.address.toLowerCase()))),te=ee.filter(hD),ne=ee.filter(e=>!hD(e)),{orderedMethods:re,disabledMethods:ie}=fD({fundMethodsList:j,hideUnlistedFundMethods:M}),L=J(()=>vd({connectedWallets:[...ne,...te],svmWallet:N,session:f}),[ne,te,N,f]),R=re.includes(`wallet`),ae=re.filter(e=>e!==`wallet`),z=e=>ie.has(e),B=!!t,V=()=>{D(`fund-method-selection`,`fund-methods`),g({backTarget:`fund-methods`})},oe=e=>Q(`button`,{type:`button`,disabled:e,onClick:e?void 0:V,className:e?mD:`${pD} cursor-pointer`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(ji,{"aria-hidden":`true`,className:`h-6 w-6 shrink-0 text-gray-600 dark:text-gray-100`}),Z(`span`,{className:`text-sm font-medium`,children:`Connect wallet`})]}),Z(ki,{className:`w-5 h-5 text-gray-400`})]},`wallet-add-button`),H=e=>Q(`button`,{type:`button`,disabled:e,onClick:e?void 0:V,className:`inline-flex items-center gap-1 rounded-full px-2 py-1 text-xs font-medium transition-colors ${e?`text-gray-400 dark:text-gray-500 cursor-not-allowed`:`text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer`}`,"aria-label":`Connect additional wallet`,children:[Z(ji,{"aria-hidden":`true`,className:`h-3.5 w-3.5`}),Z(`span`,{children:`Add wallet`})]}),se=(e,t)=>{let n=e.evmWallet,r=!n&&e.networks.includes(`solana`)&&!!e.solanaAddress,i=r&&F,a=!t&&!i,d=t||i,f=_===`wallet`&&Qu(x,e.selection),h=r&&typeof N?.disconnect==`function`,g=()=>{if(S(e.selection),$u(C?.chainId,e.selection)&&(w(),T(!1),E()),n){v(`wallet`),n.address.toLowerCase()!==c?.toLowerCase()&&m(n.connectionId,n.address),o?.();return}e.networks.includes(`solana`)&&(v(`wallet`),o?.())},b=async()=>{if(n){try{await p(n.connectionId),td(x,n)&&S(null)}catch(e){s.console.error(`[trails-sdk] Failed to disconnect funding wallet:`,e)}return}if(!(!h||!N?.disconnect))try{await Promise.resolve(N.disconnect()),Zu(x)&&S(null)}catch(e){s.console.error(`[trails-sdk] Failed to disconnect Solana funding wallet:`,e)}},D=n?.address??e.solanaAddress??``,O=!!n?.address&&!!e.solanaAddress;return Q(`div`,{onClick:a?g:void 0,onKeyDown:a?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),g())}:void 0,"aria-disabled":!a,className:d?mD:`${pD} ${a?`cursor-pointer`:`cursor-default`} ${f?`bg-gray-50 dark:bg-gray-800`:``}`,children:[Q(`div`,{className:`flex items-center gap-3 flex-1 min-w-0`,children:[Z(gw,{walletAddress:n?.address,walletId:e.walletId??n?.walletId,connector:n?.connector,icon:e.icon??n?.icon,iconAlt:e.name,chainId:n?dw(n,u,l):void 0,networks:e.networks}),Q(`div`,{className:`flex flex-col min-w-0`,children:[Z(`span`,{className:`text-sm font-medium truncate`,children:e.name}),Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 truncate`,children:O?Q(hi,{children:[Z(lD,{address:n.address,children:Z(cw,{address:n.address,startChars:6,endChars:4})}),` / `,Z(lD,{address:e.solanaAddress,children:wt(e.solanaAddress)})]}):n?Z(lD,{address:D,children:Z(cw,{address:D,startChars:6,endChars:4})}):D?Z(lD,{address:D,children:wt(D)}):null})]})]}),Q(`div`,{className:`flex items-center gap-2`,children:[(n?.showDisconnect===!0||h)&&Z(y,{message:`Disconnect`,side:`top`,children:Z(`button`,{type:`button`,"aria-label":`Disconnect ${e.name||n?.connector?.name||`wallet`}`,title:`Disconnect`,onClick:e=>{e.stopPropagation(),b()},className:`h-7 w-7 inline-flex items-center justify-center rounded-full text-gray-400 hover:text-gray-700 hover:bg-gray-100 dark:text-gray-500 dark:hover:text-gray-200 dark:hover:bg-gray-700 transition-colors cursor-pointer`,children:Z(Ui,{className:`w-4 h-4`})})}),Z(ki,{className:`w-5 h-5 text-gray-400 dark:text-white`})]})]},rd(e.selection))},ce=e=>{let t=z(e);if(e===`onramp-meld`){if(!I)return null;let e=t;return Q(`button`,{type:`button`,disabled:e,onClick:e?void 0:()=>{v(`onramp-meld`),b({id:`CREDIT_DEBIT_CARD`,name:`Credit or debit card`}),r?.()},className:e?mD:`${pD} cursor-pointer`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(Fi,{className:`w-8 h-8 text-blue-700 dark:text-blue-100`}),Z(`span`,{className:`text-sm font-medium`,children:`Credit or debit card`})]}),Q(`div`,{className:`flex items-center gap-2`,children:[Z(iE,{"aria-label":`Supported cards`,className:`h-6 w-auto`}),Z(ki,{className:`w-5 h-5 text-gray-400`})]})]},`onramp-meld`)}if(e===`direct-transfer`){if(te.length>0)return null;let e=t;return Q(`button`,{type:`button`,disabled:e,onClick:e?void 0:n,className:e?mD:`${pD} cursor-pointer`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(Wi,{className:`w-8 h-8 text-gray-700 dark:text-gray-200`}),Q(`div`,{className:`flex flex-col`,children:[Z(`span`,{className:`text-sm font-medium`,children:`QR crypto transfer`}),Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`Send from mobile wallet`})]})]}),Z(ki,{className:`w-5 h-5 text-gray-400`})]},`direct-transfer`)}if(e===`onramp-mesh`){if(h===`pay`)return null;let e=t||!B;return Q(`button`,{type:`button`,disabled:e,title:B&&!t?void 0:`Coming soon`,onClick:e?void 0:()=>{v(`onramp-mesh`),i?.()},className:e?mD:`${pD} cursor-pointer`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(Si,{className:`w-8 h-8 text-purple-700 dark:text-purple-100`}),Z(`span`,{className:`text-sm font-medium`,children:`From exchange`})]}),Q(`div`,{className:`flex items-center gap-2`,children:[Z(aE,{"aria-label":`Supported exchanges`,className:`h-6 w-auto`}),Z(ki,{className:`w-5 h-5 text-gray-400`})]})]},`onramp-mesh`)}return null},U=z(`wallet`),le=R&&ae.length>0;return Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{headerContent:e||`Choose a funding method`,headerContentAlign:`left`,rightSideContent:Z(`div`,{className:`w-9`})}),Z(`div`,{className:`flex-1`,children:Q(`div`,{className:`flex flex-col gap-3`,children:[R?Q(`section`,{"aria-label":`Connected wallets`,children:[Q(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[Z(`p`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`Connected wallets`}),L.length>0&&!k?H(U):null]}),Q(`div`,{className:`flex flex-col gap-3`,children:[L.map(e=>se(e,U)),L.length===0&&!k?oe(U):null]})]}):null,le?Z(`div`,{"aria-hidden":`true`,className:`border-t border-gray-200 dark:border-gray-700`}):null,ae.length>0?Q(`section`,{"aria-label":le?`Other funding options`:`Funding options`,children:[le?Z(`p`,{className:`mb-2 text-xs text-gray-500 dark:text-gray-400`,children:`Other options`}):null,Z(`div`,{className:`flex flex-col gap-3`,children:ae.map(e=>{let t=ce(e);return t?Z(sr,{children:t},e):null})})]}):null]})})]})},_D=({onBack:e,onSelectExchange:t})=>{let n=L(),{onramp:r,apiKey:i,trailsApiUrl:a}=wo(),o=gv(),c=uy(r),[l,u]=X(!1),[d,f]=X({}),p=yv(c),{data:m=[],isLoading:h,error:g}=Or({queryKey:[`mesh-exchange-options`,p,a,i],queryFn:async()=>((await o.getMeshIntegrations({environment:p})).integrations||[]).map(e=>({key:e.key,integrationId:e.id,exchangeName:e.displayName||e.key,imageUrl:e.imageUrl||``})),enabled:!!i,staleTime:1440*60*1e3,gcTime:1440*60*1e3,refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),_=J(()=>n?m:m.filter(e=>{let t=e.key.toLowerCase();return t!==`kraken`&&t!==`krakendirect`}),[m,n]),v=l?_:_.slice(0,3);return Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:e,headerContent:`Select Exchange`,headerContentAlign:`left`}),Z(`div`,{className:`flex-1`,children:h?Z(`div`,{className:`flex h-full items-center justify-center`,children:Q(`div`,{className:`text-center`,children:[Z(`div`,{className:`mt-4 mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-2 border-solid border-blue-500 border-t-transparent`}),Z(`p`,{className:`text-sm text-gray-500 dark:text-gray-400`,children:`Loading exchanges...`})]})}):g?Z(`div`,{className:`flex h-full items-center justify-center`,children:Z(`div`,{className:`rounded-lg border border-solid border-red-200 bg-red-50 p-4 text-sm text-red-700 dark:border-red-800 dark:bg-red-900/20 dark:text-red-300`,children:g instanceof Error?g.message:`Failed to load exchanges`})}):_.length===0?Z(`div`,{className:`flex h-full items-center justify-center`,children:Z(`div`,{className:`rounded-lg border border-solid border-gray-200 bg-gray-50 p-4 text-sm text-gray-600 dark:border-gray-700 dark:bg-gray-800/70 dark:text-gray-300`,children:`No supported exchanges are currently available.`})}):Z(`div`,{className:`max-h-[420px] overflow-y-auto pr-1 pt-2`,children:Q(`div`,{className:`space-y-2`,children:[v.map(e=>Q(`button`,{type:`button`,onClick:()=>{s.console.log(`[trails-sdk] Selected Mesh exchange in widget:`,e),t({integrationId:e.integrationId,exchangeKey:e.key,exchangeName:e.exchangeName,imageUrl:e.imageUrl})},className:`w-full flex items-center justify-between cursor-pointer py-3 px-3 rounded-xl transition-colors duration-200 bg-transparent hover:bg-gray-50 dark:hover:bg-gray-800/60 text-gray-900 dark:text-white`,children:[Q(`div`,{className:`flex items-center space-x-3 flex-1`,children:[Z(Ay,{exchangeKey:e.key,exchangeName:e.exchangeName,exchangeImageUrl:d[e.integrationId]?void 0:e.imageUrl,className:`h-10 w-10 rounded-full`,imageClassName:`h-7 w-7 object-contain`,onError:()=>{f(t=>({...t,[e.integrationId]:!0}))}}),Q(`div`,{className:`flex-1 text-left`,children:[Z(`h4`,{className:`text-base font-medium leading-6 text-gray-900 dark:text-gray-100`,children:e.exchangeName}),Z(`p`,{className:`mt-0.5 text-xs text-gray-500 dark:text-gray-400`,children:`Connect your account to transfer funds`})]})]}),Z(ki,{className:`h-5 w-5 text-gray-700 dark:text-gray-300`})]},e.integrationId)),!l&&_.length>3&&Z(`button`,{type:`button`,onClick:()=>u(!0),className:`mt-4 w-full cursor-pointer rounded-full border-none bg-gray-100 px-6 py-3 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-100 dark:hover:bg-gray-600`,children:`Show more`})]})})}),p===`sandbox`&&Z(`div`,{className:`mt-4 border border-solid border-yellow-200 bg-yellow-50 p-3 dark:border-yellow-800 dark:bg-yellow-900/20`,children:Q(`div`,{className:`text-center`,children:[Z(`p`,{className:`text-sm font-medium text-yellow-800 dark:text-yellow-200`,children:`Sandbox environment`}),Z(`p`,{className:`text-xs text-yellow-600 dark:text-yellow-300`,children:`No real funds are used`})]})})]})};function vD({exchangeName:e,exchangeKey:t,exchangeImageUrl:n,onBack:r,onContinue:i}){let a=e||`Exchange`;return Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:r,headerContent:`Fund with ${a}`,headerContentAlign:`left`}),Q(`div`,{className:`flex flex-1 flex-col justify-between rounded-2xl border border-solid border-gray-200 bg-transparent p-6 dark:border-gray-700`,children:[Q(`div`,{className:`flex flex-1 flex-col items-center justify-center text-center`,children:[Z(Ay,{exchangeKey:t,exchangeName:a,exchangeImageUrl:n,className:`mb-5 h-14 w-14 rounded-full border border-solid border-gray-200 dark:border-gray-700`,imageClassName:`h-10 w-10 object-contain`,fallbackClassName:`text-base font-semibold text-gray-700 dark:text-gray-200`}),Q(`h3`,{className:`max-w-[320px] text-xl font-semibold text-gray-900 dark:text-white`,children:[`Connect `,a,` account`]}),Q(`p`,{className:`mt-2 text-sm text-gray-500 dark:text-gray-400`,children:[`By continuing you accept the`,` `,Z(`a`,{href:`https://trails.build/sequence-platforms-terms-of-use.pdf`,target:`_blank`,rel:`noopener noreferrer`,className:`text-gray-600 underline dark:text-gray-300`,children:`terms of use`})]})]}),Z(`div`,{className:`mt-6 flex justify-center`,children:Q(`button`,{type:`button`,onClick:i,className:`min-w-[220px] cursor-pointer rounded-full bg-blue-600 px-7 py-3 text-base font-semibold text-white transition-colors hover:bg-blue-700`,children:[`Continue to `,a]})})]})]})}function yD({connectedBrokerName:e,connectedBrokerImageUrl:t,connectedBrokerExchangeKey:n,connectedAccountLabel:r,isLoadingBalance:i,balanceUsd:a,balanceUsdDisplay:o,onBack:s,onContinue:c,onLogout:l}){return Q(`div`,{className:`flex flex-col h-full p-4`,children:[Z(M_,{onBack:s,headerContent:`Connected Exchange`,headerContentAlign:`left`}),Q(`div`,{className:`flex-1 flex flex-col justify-between gap-4`,children:[Q(`div`,{className:`rounded-lg border border-solid border-gray-200 dark:border-gray-700 p-4`,children:[Z(`p`,{className:`text-sm text-gray-500 dark:text-gray-400`,children:`Exchange`}),Q(`div`,{className:`mt-1 flex items-center gap-2`,children:[Z(Ay,{exchangeKey:n,exchangeName:e,exchangeImageUrl:t,className:`h-8 w-8 rounded-full border border-solid border-gray-200 dark:border-gray-700`,imageClassName:`h-6 w-6 object-contain`}),Z(`p`,{className:`text-base font-medium text-gray-900 dark:text-white`,children:e})]}),Z(`p`,{className:`text-sm text-gray-500 dark:text-gray-400 mt-3`,children:`Account`}),Z(`p`,{className:`text-base font-medium text-gray-900 dark:text-white mt-1`,children:r}),!i&&a>0&&Q(hi,{children:[Z(`p`,{className:`text-sm text-gray-500 dark:text-gray-400 mt-3`,children:`Balance`}),Z(`p`,{className:`text-base font-medium text-gray-900 dark:text-white mt-1 notranslate`,children:o})]})]}),Q(`div`,{className:`grid grid-cols-1 gap-2`,children:[Z(`button`,{type:`button`,onClick:c,className:`w-full font-semibold py-4 px-4 trails-border-radius-button transition-colors bg-blue-500 hover:bg-blue-600 text-white cursor-pointer`,children:`Continue with connected account`}),Z(`button`,{type:`button`,onClick:l,className:`w-full flex items-center justify-center cursor-pointer font-medium py-2 px-4 bg-transparent border-none trails-text-secondary hover:trails-text-primary transition-colors duration-200`,children:`Logout`})]})]})]})}const bD=[`CREDIT_DEBIT_CARD`,`EXCHANGE`,`PAYPAL`,`GOOGLE_PAY`,`APPLE_PAY`,`SEPA`],xD=e=>e.filter(e=>bD.includes(e.paymentMethod));function SD(e){let{trailsClient:t,fiatCurrency:n,enabled:r=!0}=e,i=gv(),{defaultCurrencyCode:a,isLoading:o}=Vw({enabled:r}),s=n||a||null,c=t===void 0?i:t,l=PS.paymentMethodList(c,s),u=r&&!(n===void 0&&o),{data:d=[],isLoading:f,error:p}=Or({...l,enabled:u,select:xD});return{paymentMethods:d,isLoading:f,error:p}}const CD=({onBack:e})=>{let{navigate:t}=y_(),{isDark:n}=ue(),{setSelectedFundMethod:r,setPaymentMethod:i}=Vu(),{paymentMethods:a,isLoading:o,error:s}=SD({enabled:!0});return Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:e,headerContent:`Select payment method`,headerContentAlign:`left`,rightSideContent:Z(`div`,{className:`w-9`})}),Z(`div`,{className:`flex-1`,children:Z(`div`,{className:`flex flex-col gap-1`,children:o?Z(`div`,{className:`px-4 py-3 text-sm text-gray-500 dark:text-gray-400`,children:`Loading payment methods...`}):s?Z(`div`,{className:`px-4 py-3 text-sm text-red-500 dark:text-red-400`,children:`Failed to load payment methods`}):a.map(e=>Q(`button`,{type:`button`,onClick:()=>{r(`onramp-meld`),i({id:e.paymentMethod,name:e.name}),t(`fund-form`)},className:`w-full text-left px-4 py-3 flex items-center justify-between cursor-pointer transition-colors trails-hover-bg rounded-xl`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(`img`,{src:n?e.logos?.dark||``:e.logos?.light,alt:e.name,className:`w-8 h-8`}),Z(`span`,{className:`text-sm font-medium`,children:e.name})]}),Z(ki,{className:`w-5 h-5 text-gray-400`})]},e.paymentMethod))})})]})},wD=({address:e,chainId:t,size:n=20})=>{let r=Jr(),i=qu(),{ensAvatar:a}=Iy({address:e}),o=i?.connected&&i.publicKey?i.publicKey.toBase58():null,s=ut(e)&&!!o&&e.trim()===o.trim(),c=J(()=>r.find(t=>Pe(t.address,e)),[r,e]);return s||c?Z(GE,{address:e,chainId:t,size:n,avatar:s&&i?Z(Na,{walletId:i.walletId,icon:i.walletIcon,label:i.walletName??`Solana`,size:n,className:`shrink-0`,imageClassName:`shrink-0 rounded-full object-cover`}):void 0}):a||t==null?Z(zE,{address:e,size:n,className:`shrink-0`}):Z(HE,{chainId:t,size:n})};function TD(){let{payMessage:e,appName:t,appUrl:n,appImageUrl:r,appDescription:i,toAddress:a,toChainId:o,toAmount:c,toToken:l,toCalldata:u}=wo(),{targetAmountUsdFormatted:d,targetAmountUsdFormattedLocale:f}=KT(),p=J(()=>o?$(Number(o)):null,[o]),{tokenInfo:m}=Uc({address:l||``,chainId:o?Number(o):void 0}),h=J(()=>{if(!e)return[];let s=[],l=/\{([^}]+)\}/g,u=0,h=l.exec(e);for(;h!==null;){switch(h.index>u&&s.push({type:`text`,value:e.substring(u,h.index)}),h[1]){case`APP_NAME`:s.push({type:`appName`,value:t||``});break;case`APP_URL`:s.push({type:`appUrl`,value:n||``});break;case`APP_IMAGE`:s.push({type:`appImage`,value:r||``});break;case`APP_DESCRIPTION`:s.push({type:`text`,value:i||``});break;case`TO_AMOUNT_USD`:{let e=d||`$0.00`;if(e===`$0.00`||e===`$0`){let e=c||`0`,t=m?.symbol||``;s.push({type:`amount`,value:`${e} ${t}`.trim()})}else s.push({type:`amount`,value:e});break}case`TO_AMOUNT_LOCALE_USD`:{let e=f||`$0.00`;if(e===`$0.00`||e===`$0`){let e=c||`0`,t=m?.symbol||``;s.push({type:`amount`,value:`${e} ${t}`.trim()})}else s.push({type:`amount`,value:e});break}case`TO_ADDRESS`:s.push({type:`toAddress`,value:a||``});break;case`TO_ADDRESS_TRUNCATED`:s.push({type:`toAddressTruncated`,value:a||``});break;case`TO_CHAIN_ID`:s.push({type:`toChainId`,value:o?String(o):``});break;case`TO_AMOUNT`:s.push({type:`toAmount`,value:c||``});break;case`TO_TOKEN_SYMBOL`:s.push({type:`toTokenSymbol`,value:m?.symbol||``});break;case`TO_TOKEN_NAME`:s.push({type:`toTokenName`,value:m?.name||``});break;case`TO_CHAIN_NAME`:s.push({type:`toChainName`,value:p?.name||``});break;case`TO_TOKEN_IMAGE`:s.push({type:`toTokenImage`,value:m?.imageUrl||``});break;case`TO_CHAIN_IMAGE`:s.push({type:`toChainImage`,value:o?String(o):``});break;default:s.push({type:`text`,value:h[0]})}u=l.lastIndex,h=l.exec(e)}return u<e.length&&s.push({type:`text`,value:e.substring(u)}),s},[e,t,n,r,i,d,f,a,c,m?.symbol,m?.name,m?.imageUrl,p?.name,o]);return{message:J(()=>e?Z(hi,{children:h.map(e=>{switch(e.type){case`appImage`:return e.value?Z(`img`,{src:e.value,alt:t||`App`,className:`inline-block w-4 h-4 mx-1 rounded`,onError:e=>{s.console.error(`Error loading app image: ${e}, appImageUrl: ${r}`),e.currentTarget.style.display=`none`}},`${e.type}`):null;case`appName`:return n?Z(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:`font-bold hover:underline cursor-pointer mx-1`,title:i||t||``,children:e.value},`${e.type}`):Z(`span`,{className:`font-bold mx-1`,title:i||``,children:e.value},`${e.type}`);case`amount`:return Z(`span`,{className:`font-bold mx-1`,children:e.value},`${e.type}`);case`appUrl`:return e.value?Z(`a`,{href:e.value,target:`_blank`,rel:`noopener noreferrer`,className:`hover:underline cursor-pointer mx-1`,children:e.value},`${e.type}`):null;case`toAddress`:return e.value?Z(`a`,{href:Za({address:e.value,chainId:o?Number(o):1}),target:`_blank`,rel:`noopener noreferrer`,className:`font-mono text-sm hover:underline cursor-pointer mx-1`,children:e.value},`${e.type}`):null;case`toAddressTruncated`:return e.value?Z(`a`,{href:Za({address:e.value,chainId:o?Number(o):1}),target:`_blank`,rel:`noopener noreferrer`,className:`font-mono text-sm hover:underline cursor-pointer mx-1`,children:wt(e.value)},`${e.type}`):null;case`toChainId`:return Z(`span`,{className:`mx-1`,children:e.value},`${e.type}`);case`toAmount`:return Z(`span`,{className:`font-bold mx-1`,children:e.value},`${e.type}`);case`toTokenSymbol`:return Z(`span`,{className:`font-bold mx-1`,children:e.value},`${e.type}`);case`toTokenName`:return Z(`span`,{className:`mx-1`,children:e.value},`${e.type}`);case`toChainName`:return Z(`span`,{className:`font-semibold mx-1`,children:e.value},`${e.type}`);case`toTokenImage`:return e.value&&m?.symbol?Z(`span`,{className:`inline-block mx-1`,children:dr(Jy,{imageUrl:e.value,symbol:m.symbol,chainId:o?Number(o):void 0,size:16})},`${e.type}`):null;case`toChainImage`:return o?Z(`span`,{className:`inline-block mx-1`,children:dr(Ty,{chainId:Number(o),size:16})},`${e.type}`):null;case`text`:return Z(`span`,{children:e.value},`${e.type}`);default:return Z(`span`,{children:e.value},`${e.type}`)}})}):Q(`div`,{className:`flex flex-col items-center justify-center px-8 py-4 space-y-4 min-w-full`,children:[r&&Z(`img`,{src:r,alt:t||`App`,className:`w-12 h-12 rounded-lg`,onError:e=>{s.console.error(`Error loading app image: ${e}, appImageUrl: ${r}`),e.currentTarget.style.display=`none`}}),Z(`div`,{className:`font-bold text-center`,children:(()=>{let e=f||d||`$0.00`,t=c||`0`,n=m?.symbol||``,r=e===`$0.00`||e===`$0`?`${t} ${n}`.trim():e,i=r.length,a=`text-6xl`;return i>12?a=`text-2xl`:i>10?a=`text-3xl`:i>8?a=`text-4xl`:i>6&&(a=`text-5xl`),Z(`div`,{className:a,children:r})})()}),a&&Q(`div`,{className:`flex items-center space-x-2 text-center`,children:[Z(`span`,{className:`text-sm text-gray-900 dark:text-gray-100`,children:u?`to`:`Recipient`}),Z(wD,{address:a,chainId:o?Number(o):null,size:20}),Z(`a`,{href:Za({address:a,chainId:o?Number(o):1}),target:`_blank`,rel:`noopener noreferrer`,className:`text-sm hover:underline cursor-pointer text-blue-600 dark:text-blue-400`,children:Z(cw,{address:a,startChars:4,endChars:4})})]})]}),[e,h,t,n,r,i,m,o,a,u,d,f,c]),parts:h}}const ED=({missingProps:e,componentName:t})=>e.length===0?null:Z(XC,{errorPrettified:`Missing required ${t} prop${e.length>1?`s`:``}`,error:`The following required props are missing for the ${t} component:
90
+ ${e.map(e=>`- ${e}`).join(`
91
+ `)}
92
+
93
+ Please ensure all required props are provided when rendering the ${t} component.`,severity:`error`}),DD=({selectedToken:e,onBack:t,account:n,walletClient:r,onTransactionStateChange:i,onError:a,onWaitingForWalletConfirm:o,onConfirm:c,onComplete:l,onSend:u,isSequenceWallet:d=!1,setWalletConfirmRetryHandler:f,swapProvider:p,bridgeProvider:m,swapProviderFallback:h,bridgeProviderFallback:g,fundMethod:_,checkoutOnHandlers:v,recentTokens:y,onRecentTokenSelect:b,onTrackToken:x,toRecipient:S,toAmount:C,toChainId:w,toToken:T,toCalldata:E,onAmountUpdate:D})=>{let{mode:O,navigate:k}=y_(),A=To(wo()),{selectedToken:j,setSelectedToken:M}=ul(),{selectedToken:N,setSelectedToken:P,isControlledByProps:F,availableDestinationTokens:I,availableDestinationTokenKeys:ee,availableDestinationTokenRestrictedChainIds:te,availableDestinationChainIds:ne}=xl(),{destinationChainIds:re,destinationChainList:ie,destinationChainListExtras:L,destinationCatalogSupplementTokens:R,destinationDisabledChains:ae,isEdgeDestinationSupported:z}=rD(ne),{selectedRecipient:B,setSelectedRecipient:V}=cu(),{setAmount:oe,clearAmount:H}=du(),{targetAmountUsd:se}=KT(),{enterFormMode:ce}=d_();q(()=>{C?ce(`pay`):ce(`pay`)&&H()},[]);let U=j||e,{defaultOriginToken:le,isLoading:ue}=XT(),{defaultDestinationToken:de,isLoading:fe}=OE(U),{message:pe}=TD(),[me,he]=X(``),[ge,_e]=X(``),[ve,ye]=X(!1),[be,xe]=X(!1),Se=S||B||null,Ce=!!Se&&!!n?.address&&!Pe(Se,n.address),[we,Te]=X(!1),[Ee,De]=X(!1),[Oe,ke]=X(null),Ae=qu(),je=J(()=>Ae&&(!_||_===`wallet`)?[Ra]:void 0,[_,Ae]),{handleChainSelect:Me}=D_(_??`wallet`),[Ne,Fe]=X(!1),Ie=Y(null),{trackClick:Le}=k_(),Re=Y(null),{token:ze,isLoadingBalance:Be}=ev(U,ZT(U,n?.address),{withPrices:!0}),Ve=B||S||n?.address,He=J(()=>{if(!U||!N||!Ve||!n?.address)return!1;let e=U.contractAddress?.toLowerCase()===N.contractAddress?.toLowerCase()&&U.chainId===N.chainId,t=Pe(Ve,n.address);return e&&t},[U,N,Ve,n?.address]),{amountUsdDisplay:Ue,amountUsdLocaleDisplay:We,isLoadingQuote:Ge,prepareSendQuote:Ke,setAmount:qe,handleSubmit:Je,isSubmitting:Ye,buttonText:Xe,isValidRecipient:Ze,selectedDestinationChain:Qe,selectedDestToken:$e,setSelectedDestToken:et,setSelectedDestinationChain:tt,quoteError:nt,quoteErrorPrettified:rt,isOriginFundingWalletMismatch:it,destinationTokenAddress:at,isValidCustomToken:ot,isSenderContractOnOrigin:st,isSenderContractOnDestination:ct,processedFeeOptions:lt,selectedFeeOption:ut,setSelectedFeeOption:dt}=nE({account:n,toAmount:me||C,toRecipient:Ve,toChainId:w,toToken:T,toCalldata:E,walletClient:r,onTransactionStateChange:i,onError:a,onWaitingForWalletConfirm:o,onConfirm:c,onComplete:l,onSend:u,selectedToken:U,setWalletConfirmRetryHandler:f,tradeType:ln.EXACT_OUTPUT,swapProvider:p,bridgeProvider:m,swapProviderFallback:h,bridgeProviderFallback:g,fundMethod:_,mode:O,checkoutOnHandlers:v,skipFeeBalanceFetch:_===`onramp-meld`||_===`direct-transfer`||_===`onramp-mesh`}),G=QE({fundMethod:_,allowedChainIds:null,disabledChains:J(()=>W($e?.chainId??0)?[101]:void 0,[$e?.chainId])}),ft=J(()=>{let e=[...ae??[]];return W(U?.chainId??0)&&!e.includes(101)&&e.push(101),ZE({recipient:B,allowedChainIds:re,disabledChains:e.length>0?e:void 0})},[ae,U?.chainId,B,re]),pt=J(()=>{let e=[$e?.chainId,N?.chainId,Qe?.id,w];for(let t of e){if(t==null)continue;let e=typeof t==`number`?t:Number(t);if(!Number.isNaN(e))return e}return null},[$e?.chainId,N?.chainId,Qe?.id,w]);q(()=>{A||!U&&!ue&&le&&(s.console.log(`[trails-sdk] Auto-selecting origin token:`,le),M(le))},[U,ue,le,M,A]),q(()=>{if(N&&(et(N),tt)){let e=$(N.chainId);e&&tt(e)}},[N,et,tt]),q(()=>{if(!F||!$e||!T)return;let e=$e.chainId===Number(w),t=$e.contractAddress?.toLowerCase()===T.toLowerCase()||$e.symbol?.toLowerCase()===T.toLowerCase();e&&t&&(N&&N.chainId===$e.chainId&&N.contractAddress?.toLowerCase()===$e.contractAddress?.toLowerCase()||(s.console.log(`[trails-sdk] Syncing resolved token from useSendForm to global provider:`,$e.symbol),P($e)))},[F,$e,N,P,T,w]),q(()=>{S&&(s.console.log(`[trails-sdk] Pay syncing selectedRecipient from toRecipient prop:`,S),V(S))},[S,V]),q(()=>{s.console.log(`[trails-sdk] Pay component toAmount effect:`,{toAmount:C,tokenAmountForBackend:me,inputDisplayValue:ge,willUpdate:!!C&&C!==me}),C&&C!==me&&(s.console.log(`[trails-sdk] Updating amount from toAmount prop:`,C),he(C),_e(C),qe(C),oe(C))},[C,me,ge,qe,oe]),q(()=>{if(F||$e?.symbol)return;let e=N||de;if(e&&!fe&&(s.console.log(`[trails-sdk] Initializing destination token:`,{symbol:e.symbol,chainId:e.chainId,name:e.name,contractAddress:e.contractAddress}),!N&&de&&P(de),et(e),tt&&e.chainId)){let t=$(e.chainId);t&&tt(t)}},[F,N,de,fe,$e?.symbol,P,et,tt]),nD({modeLabel:`Pay`,selectedRecipient:B,destinationToken:$e,originChainId:U?.chainId,isDestinationLocked:F,defaultSolanaToken:R[0],defaultEvmDestinationToken:de,availableDestinationTokens:I,setDestinationToken:P,setSelectedDestToken:et,setSelectedDestinationChain:tt,setDestinationChainFilterId:ke}),q(()=>{Ie.current&&Ie.current.focus()},[]);let mt=K(e=>{if(e===``){_e(``),he(``),qe(``),oe(``),D?.(``);return}e.length>16||e.match(/^\d*\.?\d{0,8}$/)&&(_e(e),he(e),qe(e),oe(e),D?.(e))},[qe,oe,D]),ht=ge,gt=fb({inputValue:ht}),_t=K(e=>{M(e),ye(!1),s.console.log(`[trails-sdk] selected origin token`,e),x?.(e)},[M,x]),vt=K(e=>{if(P(e),et(e),tt&&e.chainId){let t=$(e.chainId);t&&tt(t)}Te(!1),s.console.log(`[trails-sdk] selected destination token`,e),x?.(e)},[P,et,tt,x]);if(be)return Z(cb,{extraChains:je,disabledChains:G.disabledChains,onChainSelect:Me,onBack:()=>{xe(!1),ye(!0)}});if(Ee)return Z(cb,{chains:ie,extraChains:L,disabledChains:ft.disabledChains,onChainSelect:ke,onBack:()=>{De(!1),Te(!0)}});if(ve)return Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>ye(!1),headerContent:`Select Token`,headerContentAlign:`left`,customActions:Z(lb,{onError:a,fundMethod:_})}),Z(ib,{onTokenSelect:_t,targetAmountUsd:se,onError:a,fundMethod:_,showContinueButton:!1,compactMode:!1,recentTokens:y,onRecentTokenSelect:e=>{M(e),ye(!1),b?.(e)},allSupportedTokens:!1,allowedChainIds:G.allowedChainIds,disabledChains:G.disabledChains,chainListScreen:!0,onNavigateToChainList:()=>{ye(!1),xe(!0)},onNavigateToFundMethods:()=>{k(`payment-methods`)}})]});if(we)return Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>Te(!1),headerContent:`Select Token`,headerContentAlign:`left`,customActions:Z(lb,{onError:a,fundMethod:_,allSupportedTokens:!0,accountAddress:Ve})}),Z(ib,{onTokenSelect:vt,targetAmountUsd:se,onError:a,fundMethod:_,allowedTokens:I,allowedTokenKeys:ee,allowedTokenRestrictedChainIds:te,allowedChainIds:ft.allowedChainIds,catalogSupplementTokens:R,showContinueButton:!1,compactMode:!1,recentTokens:y,onRecentTokenSelect:e=>{P(e),et(e),Te(!1),b?.(e)},allSupportedTokens:!0,accountAddress:Ve,accountHeaderLabel:`Receiver`,disabledChains:ft.disabledChains,includeSolanaChainFilter:z,chainFilterChainId:Oe,onChainFilterChange:ke,chainListScreen:!0,onNavigateToChainList:()=>{Te(!1),De(!0)}})]});let yt=[],bt=!!T;C||yt.push(`toAmount`),bt||yt.push(`toToken`),S||yt.push(`toAddress`);let xt=!!(T&&C&&w&&S);if(yt.length>0)return Q(`div`,{className:`space-y-4`,children:[Z(M_,{onBack:t,headerContent:`Pay`,headerContentAlign:`left`,showAccountActions:!0,customActions:Q(`button`,{type:`button`,onClick:()=>k(`swap`,{backTarget:`send-form`}),className:`flex h-8 px-3 justify-center items-center gap-1.5 rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600`,title:`Swap`,children:[Z(xi,{className:`h-4 w-4`}),Z(`span`,{className:`text-sm font-medium`,children:`Swap`})]})}),Z(ED,{missingProps:yt,componentName:`Pay`})]});let St=Rl({originToken:ze??U,originTokenBalance:ze?.balance??U?.balance,originTokenAmount:Ke?.originAmountFormatted,isLoadingBalance:Be}),Ct=Il(_),wt=!!ut&&!!St&&Bl(ut,St);return Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:t,headerContent:`Pay`,headerContentAlign:`left`,showAccountActions:!0,customActions:Q(`button`,{type:`button`,onClick:()=>k(`swap`,{backTarget:`send-form`}),className:`flex h-8 px-3 justify-center items-center gap-1.5 rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600`,title:`Swap`,children:[Z(xi,{className:`h-4 w-4`}),Z(`span`,{className:`text-sm font-medium`,children:`Swap`})]})}),xt?Q(hi,{children:[Z(`div`,{className:`space-y-1 trails-bg-secondary p-3 border bg-white dark:bg-gray-800`,style:{borderColor:`var(--trails-bg-secondary-hover)`,borderWidth:`1px`,borderStyle:`solid`,borderRadius:`var(--trails-border-radius-large-button)`},children:Z(`div`,{className:`flex justify-start`,children:Z(`div`,{className:`flex items-center font-medium trails-text-primary text-sm flex-wrap whitespace-break-spaces break-all min-w-full`,children:pe})})}),Z(`div`,{className:`mb-4`,children:Q(`div`,{className:`pt-4 pb-4 trails-border-radius-container p-3 group transition-all duration-200 border bg-white dark:bg-gray-800 min-h-[120px] flex flex-col`,style:{borderColor:`var(--trails-bg-secondary-hover)`,borderWidth:`1px`,borderStyle:`solid`},children:[Q(`div`,{className:`mb-4 flex justify-between items-center`,children:[Q(`div`,{className:`text-sm font-medium trails-text-secondary text-left m-0`,children:[`Pay with`,_===`direct-transfer`?``:_===`onramp-mesh`?` Exchange`:_===`onramp-meld`?` Onramp Provider`:``]}),Z(hE,{})]}),Q(`div`,{className:`flex items-center space-x-2 flex-1`,children:[Z(`div`,{className:`flex-1`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Z(pb,{ref:Re,value:Ke?.originAmountFormattedLocale||Ke?.originAmountFormatted||``,readOnly:!0,isLoading:Ge,variant:`default`,inputSize:`standard`}),Ge&&Z(Tw,{})]})}),Z(`div`,{className:`relative`,children:Z(gE,{token:U,chainId:U?.chainId,onSelect:()=>ye(!0)})})]}),Q(`div`,{className:`mt-4 flex justify-between items-center`,children:[Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,title:Ke?.originAmountUsdDisplay||void 0,children:U?.symbol&&Ke?.originAmountFormatted?Ke?.originAmountUsdDisplay===`$0.00`||Ke?.originAmountUsdDisplay===`$0`?Q(hi,{children:[Ke.originAmountFormatted,` `,U.symbol]}):Q(`span`,{className:`notranslate`,translate:`no`,children:[`≈ `,Ke?.originAmountUsdLocaleDisplay||Ke?.originAmountUsdDisplay||qs(0),` `,Ke?.fees?.totalFeeAmountUsd&&parseFloat(Ke.fees.totalFeeAmountUsd)>0?Z(`button`,{type:`button`,onClick:()=>Fe(!0),className:`text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 cursor-pointer transition-colors`,children:Q(`span`,{className:`notranslate`,translate:`no`,children:[`(incl.`,` `,Ke.fees.totalFeeAmountUsdLocaleDisplay||Ke.fees.totalFeeAmountUsdDisplay,` `,`fees)`]})}):null]}):Z(`span`,{children:`\xA0`})}),U&&_!==`direct-transfer`&&_!==`onramp-mesh`&&Q(`div`,{className:`flex items-center space-x-2`,children:[Z(`button`,{type:`button`,className:`text-xs text-gray-500 dark:text-gray-400 cursor-pointer hover:text-gray-700 dark:hover:text-gray-200 transition-colors bg-transparent border-none p-0`,onClick:()=>{if(ze?.balanceFormatted){let e=parseFloat(ze.balanceFormatted);_s(e)&&he(e.toFixed(6))}},onKeyDown:e=>{if((e.key===`Enter`||e.key===` `)&&(e.preventDefault(),ze?.balanceFormatted)){let e=parseFloat(ze.balanceFormatted);_s(e)&&he(e.toFixed(6))}},title:`Click to use full balance`,disabled:!ze?.balanceFormatted,children:Q(`span`,{translate:`no`,children:[`Balance:`,` `,Be?Z(`span`,{className:`inline-block w-12 h-3 bg-gray-200 dark:bg-gray-700 rounded animate-pulse`}):ze?.balanceLocaleDisplay||ze?.balanceFormatted||``]})}),!C&&ze?.balanceFormatted&&Z(vT,{userBalance:ze.balanceFormatted,userBalanceRaw:ze.balance??`0`,decimals:ze.decimals??18,isNativeToken:U.isNativeToken??!1,gasCostFormatted:Ke?.gasCostFormatted,chainId:U.chainId,onAmountSelect:e=>{he(e)},className:`opacity-100`})]})]})]})})]}):Q(hi,{children:[Q(`div`,{className:`space-y-1 trails-bg-secondary trails-border-radius-container p-3`,children:[Z(`div`,{className:`relative`,children:S?Q(`div`,{className:`w-full flex items-center justify-between space-x-3 trails-border-radius-list-button px-4 py-2 ${Ce?`bg-amber-500/10 border border-solid border-amber-500/30`:`trails-bg-secondary`}`,children:[Z(`div`,{className:`text-left`,children:Z(`div`,{className:`font-medium trails-text-primary text-sm`,children:`Recipient address`})}),Q(`div`,{className:`flex items-center gap-2.5`,children:[Z(wD,{address:S,chainId:pt,size:20}),Z(cw,{address:S,className:`font-medium trails-text-primary text-sm`})]})]}):Q(`button`,{type:`button`,onClick:()=>k(`recipients`),className:`w-full flex items-center justify-between space-x-3 trails-border-radius-list-button px-4 py-2 transition-all duration-200 cursor-pointer ${Ce?`bg-amber-500/10 border border-solid border-amber-500/30 hover:bg-amber-500/15`:`hover:trails-hover-bg hover:bg-gray-50 dark:hover:bg-gray-700`}`,children:[Z(`div`,{className:`text-left`,children:Z(`div`,{className:`font-medium trails-text-primary text-sm`,children:`Recipient address`})}),Q(`div`,{className:`flex items-center gap-2.5`,children:[B?Q(hi,{children:[Z(wD,{address:B,chainId:pt,size:20}),Z(cw,{address:B,className:`font-medium trails-text-primary text-sm`})]}):Q(hi,{children:[Z(`div`,{className:`font-medium text-gray-900 dark:text-white text-sm`,children:`Select address`}),Z(`div`,{className:`w-6 h-6 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center`,children:Z(`div`,{className:`w-4 h-4 rounded-full bg-gray-400 dark:bg-gray-500`})})]}),Z(ki,{className:`w-4 h-4 trails-text-muted flex-shrink-0`})]})]})}),Z(`div`,{className:`relative`,children:Q(`button`,{type:`button`,onClick:()=>ye(!0),className:`w-full flex items-center justify-between space-x-3 hover:trails-hover-bg hover:bg-gray-50 dark:hover:bg-gray-700 trails-border-radius-list-button px-4 py-2 transition-all duration-200 cursor-pointer`,children:[Z(`div`,{className:`text-left`,children:Z(`div`,{className:`font-medium trails-text-primary text-sm`,children:`Payment method`})}),Q(`div`,{className:`flex items-center space-x-2`,children:[U?Q(hi,{children:[Z(`div`,{className:`font-medium trails-text-primary text-sm`,children:Ge?Z(`div`,{className:`h-4 w-20 bg-gray-200 dark:bg-gray-700 rounded animate-pulse`}):Ke?.originAmountFormatted?Q(`span`,{children:[Ke.originAmountFormatted,` `,U.symbol]}):``}),Z(Jy,{symbol:U.symbol,imageUrl:U.imageUrl,chainId:U.chainId,size:20})]}):Q(hi,{children:[Z(`div`,{className:`font-medium text-gray-900 dark:text-white text-sm`,children:`Select payment token`}),Z(`div`,{className:`w-6 h-6 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center`,children:Z(qi,{className:`w-4 h-4 text-gray-400`})})]}),Z(ki,{className:`w-4 h-4 trails-text-muted flex-shrink-0`})]})]})})]}),Z(`div`,{className:`space-y-1`,children:Q(`div`,{className:`pt-4 pb-4 p-3 group transition-all duration-200 border min-h-[120px] flex flex-col `,style:{borderColor:`var(--trails-bg-secondary-hover)`,borderWidth:`1px`,borderStyle:`solid`,borderRadius:`var(--trails-border-radius-large-button)`},children:[Q(`div`,{className:`mb-4 flex justify-between items-center`,children:[Z(`div`,{className:`text-sm font-medium trails-text-secondary text-left m-0`,children:`Recipient receives`}),Z(hE,{})]}),Q(`div`,{className:`flex items-center space-x-2 flex-1`,children:[Z(`div`,{className:`flex-1`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Z(`input`,{ref:Ie,type:`text`,value:ht,onChange:e=>mt(e.target.value),placeholder:`0 ${$e?.symbol||``}`,readOnly:!!C,autoComplete:`off`,className:`w-full bg-transparent font-bold trails-text-primary placeholder:trails-text-muted border-none outline-none ${Ge?`animate-pulse`:``}`,style:gt}),Ge&&Z(Tw,{})]})}),Z(`div`,{className:`relative`,children:Z(gE,{token:$e,chainId:N?.chainId||w,onSelect:()=>Te(!0),unselectable:!!T})})]}),Z(`div`,{className:`mt-4 flex justify-between items-center`,children:Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:$e?.symbol&&ht?Q(`span`,{className:`notranslate`,translate:`no`,children:[`≈`,` `,We||Ue||qs(0)]}):Z(`span`,{children:`\xA0`})})})]})})]}),Z(JE,{fundMethod:_,isSenderContractOnOrigin:st,isSenderContractOnDestination:ct,isSequenceWallet:d}),Z(aD,{active:it}),!it&&Z(XC,{errorPrettified:rt,error:nt,severity:`warning`}),Ct&&U&&Z(mE,{processedFeeOptions:lt,selectedFeeOption:ut,setSelectedFeeOption:dt,chainId:U.chainId,isRefetching:Ge,originTokenInfo:St}),Ke&&Z(`div`,{className:`mb-4`,children:Z(wb,{quote:Ke,showContent:!0,isRefetching:Ge,initialExpanded:Ne,isPassthrough:jg(Ke.passthroughEligible,ut,lt)})}),Z(`form`,{onSubmit:e=>{Le({component:`PayWidget`,action:`submit_payment`,label:Xe||`Pay`,metadata:{originToken:U?.symbol||``,destinationToken:$e?.symbol||``,amount:me||``,recipient:B||``,fundMethod:_||``,chainId:w?.toString()||``}}),Je(e)},children:Z(`button`,{type:`submit`,disabled:!me||parseFloat(me)<=0||Ye||Ge||!Ze||!at||!ot||He||Ct&&Ke?.noSufficientBalance||!Ke||Ct&&wt,className:`w-full font-semibold py-4 px-4 trails-border-radius-button transition-colors bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white disabled:text-gray-500 disabled:cursor-not-allowed cursor-pointer relative`,children:Ye?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:Xe})]}):n?.address?Ct&&Ke?.noSufficientBalance?`Insufficient Balance`:B?U?$e?!me||parseFloat(me)<=0?`Enter an amount`:He?`No quote available`:Ge?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:`Getting quote...`})]}):Xe===`Getting quote...`||Xe===`No quote available`?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:Xe})]}):Xe||`Pay`:`Select destination token`:`Select payment token`:`Select recipient address`:`Connect your wallet`})})]})};function OD({chainId:e,depositAddress:t,tokenAddress:n,requiredAmount:r,enabled:i=!0}){let[a,o]=X(!1),[c,l]=X(null),[u,d]=X(null),[f,p]=X(0);return q(()=>{if(!i||!e||!t||!n||!r)return;let a=async()=>{try{if(W(e)){s.console.warn(`[useDepositMonitor] Skipping EVM balance polling for Solana chainId`,e);return}let i=Va(e);if(!i){s.console.warn(`[useDepositMonitor] No public client available for chain`,e);return}let a=await xp({account:{address:t},tokenAddress:n,depositAmount:r,publicClient:i});o(a.hasEnoughBalance),l(a.balance?.toString()||null),d(a.balanceFormatted);let c=a.balance&&a.requiredAmount?Number(a.balance)/Number(a.requiredAmount)*100:0;p(Math.min(c,100)),s.console.log(`[useDepositMonitor] Balance check result`,{depositAddress:t,hasEnoughBalance:a.hasEnoughBalance,balance:a.balanceFormatted,required:a.requiredAmountFormatted,percentComplete:`${(Number(a.balance)/Number(a.requiredAmount)*100).toFixed(2)}%`})}catch(e){s.console.error(`[useDepositMonitor] Error checking balance`,e)}};a();let c=setInterval(a,15*Ee);return()=>clearInterval(c)},[i,e,t,n,r]),{hasSufficientDeposit:a,depositBalance:c,depositBalanceFormatted:u,percentageComplete:f}}const kD=({depositAddress:e,requiredAmount:t,tokenAddress:n,tokenSymbol:r,tokenDecimals:i,chainId:a,onDepositComplete:o})=>{let c=Y(!1);OD({chainId:a,depositAddress:e,tokenAddress:n,requiredAmount:t,enabled:!0});let{sortedTokens:l}=Q_(e,n,{disabled:!1,refetchInterval:2e3}),u=J(()=>{if(!l||l.length===0)return null;let e=St(n),t=bt(e);return l.find(n=>{let r=n.isNativeToken??!1;return n.chainId===a?t?r:!r&&n.contractAddress?.toLowerCase()===e:!1})},[l,n,a]),d=J(()=>!l||l.length===0?[]:l.filter(e=>e.chainId===a?Cs(e.balance||`0`):!1),[l,a]),f=J(()=>{if(d.length===0)return!1;if(d.length>1)return!0;let e=d[0];if(!e)return!1;let t=St(n),r=bt(t),i=e.isNativeToken??!1,a=i?void 0:e.contractAddress?.toLowerCase();return r&&i?!1:r===i?!(!r&&a===t):!0},[d,n]),p=J(()=>{let e=BigInt(t),n=u?.balance?BigInt(u.balance):0n,r=e>0n?Number(n*10000n/e)/100:0,a=n>=e,o=n>0n&&n<e,s=n>e,c=vn(n,i),l=vn(e,i);return{currentBalance:n,percentage:Math.min(r,100),isComplete:a,isPartial:o,isOverpaid:s,currentFormatted:c,requiredFormatted:l}},[t,u,i]),m=p.isComplete?{icon:Z(Ei,{className:`w-4 h-4 text-green-500`}),text:`Complete`,progressColor:`bg-green-500`}:p.isPartial?{icon:Z(Mi,{className:`w-4 h-4 text-blue-500`}),text:`In progress`,progressColor:`bg-blue-500`}:{icon:Z(Mi,{className:`w-4 h-4 text-gray-400`}),text:`Waiting for deposit`,progressColor:`bg-gray-300`};return q(()=>{p.isComplete&&o&&!c.current&&(s.console.log(`[trails-sdk] Deposit confirmed in DepositTracker, calling onDepositComplete`),c.current=!0,o())},[p.isComplete,o]),Q(`div`,{className:`space-y-3`,children:[Q(`div`,{className:`space-y-2`,children:[Q(`div`,{className:`flex items-center gap-2`,children:[Z(`span`,{className:`text-sm font-medium text-gray-900 dark:text-white`,children:`Deposit status`}),Q(`span`,{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium`,style:{backgroundColor:`#BFDBFE`,color:`#1D4ED8`},children:[m.text,Q(`svg`,{"aria-hidden":`true`,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,className:`text-blue-500`,children:[Z(`circle`,{cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`2`}),Z(`path`,{d:`M12 16V12M12 8H12.01`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})]})]})]}),Z(`div`,{className:`w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2.5 overflow-hidden`,children:Z(`div`,{className:`${m.progressColor} h-full transition-all duration-500 ease-out`,style:{width:`${Math.min(p.percentage,100)}%`}})}),Q(`div`,{className:`flex justify-between items-center text-xs`,children:[Q(`div`,{className:`flex items-center gap-1`,children:[Z(Jy,{imageUrl:u?.imageUrl,symbol:r,chainId:a,contractAddress:n,size:16}),Q(`span`,{className:`text-gray-600 dark:text-gray-400`,children:[Ws(p.currentFormatted,{maxFractionDigits:6,minFractionDigits:2}),` `,`/`,` `,Ws(p.requiredFormatted,{maxFractionDigits:6,minFractionDigits:2}),` `,r]})]}),Q(`span`,{className:`font-semibold text-gray-500 dark:text-gray-500`,children:[p.percentage.toFixed(1),`%`]})]})]}),f&&Q(`div`,{className:`space-y-1.5`,children:[Z(`p`,{className:`text-xs text-gray-600 dark:text-gray-400`,children:`Detected Deposits:`}),Z(`div`,{className:`trails-border-radius-container border trails-border-primary max-h-[200px] overflow-y-auto`,children:d.map((e,t)=>{let n=e.isNativeToken??!1,r=e.chainId??a,i=vn(BigInt(e.balance||`0`),e.decimals),o=n?`native-${r}`:`${e.contractAddress}-${r}`;return Q(`div`,{children:[Q(`div`,{className:`px-2 py-1.5 flex items-center gap-2`,children:[Z(Jy,{imageUrl:e.imageUrl,symbol:e.symbol,chainId:r,contractAddress:n?void 0:e.contractAddress,size:16}),Q(`div`,{className:`flex flex-col flex-1 min-w-0`,children:[Q(`span`,{className:`text-xs text-gray-900 dark:text-white truncate`,children:[Ws(i,{maxFractionDigits:6,minFractionDigits:2}),` `,e.symbol]}),e.balanceUsdFormatted&&Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:e.balanceUsdFormatted})]})]}),t<d.length-1&&Z(`div`,{className:`border-t trails-border-primary`})]},o)})})]})]})},AD=({onBack:e,onChangeWallet:t,quote:n,use681QrCode:r,selectedWalletId:i,walletOptions:a,onIntentExecuted:o})=>{let c=la(),l=a||c,u=Y(!1),[d,f]=X(!1),p=l.find(e=>e.id===i)??l[0],m=r??p?.usesEip681??!0,h=n?yn(n.originDepositAddress):null,g=n?yn(n.originToken.contractAddress):null,_=n&&h?`ethereum:${h}@${n.originChain.id}`:``,v=n&&h&&g?bt(g)?`ethereum:${h}@${n.originChain.id}?value=${n.originAmount}`:`ethereum:${g}@${n.originChain.id}/transfer?address=${h}&uint256=${n.originAmount}`:``,y=m?v:_,b=n?vn(BigInt(n.originAmount),n.originToken.decimals):``,x=n&&g?Za({address:g,chainId:n.originChain.id}):``,S=K(async()=>{if(s.console.log(`[DirectTransfer] handleDepositComplete called`),!(!n?.intentId||u.current)){u.current=!0;try{s.console.log(`[DirectTransfer] Deposit complete after commit/execute`,{intentId:n.intentId,originDepositAddress:n.originDepositAddress}),o?.()}catch(e){u.current=!1,s.console.error(`[DirectTransfer] Failed to advance after deposit completion:`,e)}}},[n,o]),C=K(async()=>{if(n)try{await de(b),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},[n,b]);return Q(`div`,{className:`flex flex-col min-h-full`,children:[Z(M_,{onBack:e,headerContent:`Deposit`,headerContentAlign:`left`,rightSideContent:Q(`div`,{className:`flex flex-row items-center gap-2`,children:[Z(Jy,{symbol:n?.originToken.symbol,chainId:n?.originChain.id,contractAddress:n?.originToken.contractAddress,size:30}),Q(`div`,{className:`flex flex-col items-start`,children:[Z(`div`,{className:`flex items-center gap-1`,children:Q(`span`,{className:`text-xs font-bold text-gray-900 dark:text-white`,children:[parseFloat(vn(BigInt(n?.originAmount??0),n?.originToken.decimals??0)).toLocaleString(void 0,{maximumFractionDigits:4}),` `,Z(`a`,{href:x,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-0.5 underline decoration-dotted underline-offset-2 hover:opacity-80 transition-opacity`,children:n?.originToken.symbol})]})}),Q(`a`,{href:Za({address:n?.originDepositAddress??``,chainId:n?.originChain.id??0}),target:`_blank`,rel:`noopener noreferrer`,className:`text-xs font-medium text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100 inline-flex items-center gap-0.5 transition-colors`,children:[`on `,n?.originChain.name,Z(Li,{className:`w-3 h-3`})]})]})]})}),Q(`div`,{className:`flex flex-col flex-1`,children:[n&&Q(`div`,{className:`bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-2`,children:[Q(`div`,{className:`flex items-center justify-center mb-2`,children:[Z(`span`,{className:`text-sm font-medium text-black dark:text-white`,children:`Scan QR code with`}),Q(`button`,{type:`button`,onClick:t,className:`flex items-center gap-1 hover:opacity-80 transition-opacity ml-2`,children:[Z(Na,{walletId:p?.id,label:p?.label??`Wallet`,size:24,className:`w-6 h-6`}),Z(Di,{className:`w-4 h-4 text-gray-400`})]})]}),Z(`div`,{className:`flex justify-center mb-2`,children:Z(D,{url:y,size:190})}),Q(`div`,{className:`flex items-center justify-center gap-4 mb-2`,children:[Z(`div`,{className:`w-20 border-t border-black dark:border-white`}),Z(`span`,{className:`text-sm text-black dark:text-white`,children:`or`}),Z(`div`,{className:`w-20 border-t border-black dark:border-white`})]}),Z(`div`,{className:`flex justify-center`,children:Q(`div`,{className:`flex flex-col items-start`,children:[Z(`span`,{className:`text-sm font-medium text-black dark:text-white mb-2`,children:`Copy the one-time deposit address`}),Z(`div`,{className:`flex items-center`,children:Z(U,{text:n.originDepositAddress,size:`md`,className:`p-0`,iconColor:`#2563EB`,buttonContent:Z(`span`,{className:`text-sm font-mono text-blue-700 dark:text-blue-400`,children:wt(n.originDepositAddress,15,4)})})})]})})]}),n&&Q(`div`,{className:`flex items-start gap-3 bg-orange-50 dark:bg-orange-950/40 border border-orange-200 dark:border-orange-800 rounded-2xl p-4 mt-1`,children:[Z(`div`,{className:`shrink-0 mt-1`,children:Z(`svg`,{"aria-hidden":`true`,width:`30`,height:`30`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,style:{color:`#F97316`},children:Z(`path`,{d:`M12 9V13M12 17H12.01M10.29 3.86L1.82 18C1.64 18.3 1.55 18.64 1.55 19C1.55 19.36 1.64 19.7 1.82 20C2 20.3 2.26 20.56 2.56 20.74C2.86 20.92 3.21 21.01 3.56 21H20.44C20.79 21.01 21.14 20.92 21.44 20.74C21.74 20.56 22 20.3 22.18 20C22.36 19.7 22.45 19.36 22.45 19C22.45 18.64 22.36 18.3 22.18 18L13.71 3.86C13.53 3.56 13.27 3.32 12.97 3.15C12.67 2.98 12.34 2.89 12 2.89C11.66 2.89 11.33 2.98 11.03 3.15C10.73 3.32 10.47 3.56 10.29 3.86Z`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),Q(`div`,{className:`flex flex-col`,children:[Q(`span`,{className:`text-sm font-bold`,style:{color:`#FF6900`},children:[`Deposit exactly`,Q(`button`,{type:`button`,className:`cursor-pointer underline inline-flex items-center rounded px-1 transition-colors ${d?`bg-green-100 dark:bg-green-900/30`:`hover:bg-orange-100/60 dark:hover:bg-orange-900/20`}`,onClick:C,children:[vn(BigInt(n.originAmount),n.originToken.decimals),` `]}),n.originToken.symbol,` on `,n.originChain.name]}),Z(`span`,{className:`text-xs text-black dark:text-white mt-1`,children:`Deposited funds in excess of the requested amount cannot be refunded. Do not use the same deposit address for other deposits.`})]})]}),n&&Z(`div`,{className:`p-4 border border-gray-200 dark:border-gray-700 rounded-2xl mt-1`,children:Z(kD,{depositAddress:n.originDepositAddress,requiredAmount:n.originAmount,tokenAddress:n.originToken.contractAddress,tokenSymbol:n.originToken.symbol,tokenDecimals:n.originToken.decimals,chainId:n.originChain.id,onDepositComplete:S})}),n&&Z(`div`,{className:`space-y-2 pb-4 mt-4 px-4`,children:Z(wb,{quote:n,showContent:!0})})]})]})},jD=({onTryAgain:e,onBack:t,onRetry:n,title:r,message:i,showAnimation:a=!0,transactionStatus:o,transactionError:s})=>{let[c,l]=X(!1);q(()=>{if(a){let e=setTimeout(()=>l(!0),100);return()=>clearTimeout(e)}else l(!0)},[a]);let{title:u,message:d}=(()=>{switch(o?.toUpperCase()){case`DECLINED`:return{title:r||`Onramp Payment Declined`,message:i||`Your onramp payment was declined. Please check your payment method and try again.`};case`FAILED`:return{title:r||`Onramp Transaction Failed`,message:i||`Your onramp transaction could not be completed. Please try again.`};case`ERROR`:return{title:r||`Onramp Transaction Error`,message:i||`An error occurred while processing your onramp transaction. Please try again.`};case`CANCELLED`:return{title:r||`Onramp Transaction Cancelled`,message:i||`Your onramp transaction was cancelled. You can try again if needed.`};default:return{title:r||`Onramp Error`,message:i||`There was a problem processing your onramp transaction. Please try again.`}}})();return Q(`div`,{className:`space-y-6`,children:[Z(M_,{onBack:t,headerContent:u}),Q(`div`,{className:`flex flex-col items-center justify-center min-h-[400px] space-y-6 px-4`,children:[Z(`div`,{className:`transition-all duration-700 ease-out ${c?`opacity-100 scale-100`:`opacity-0 scale-75`}`,children:Z(`div`,{className:`w-20 h-20 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center`,children:Z(gi,{className:`w-10 h-10 text-red-600 dark:text-red-400`})})}),Q(`div`,{className:`text-center space-y-4 transition-all duration-700 ease-out delay-200 ${c?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:[Z(`h2`,{className:`text-xl font-semibold text-gray-900 dark:text-white`,children:u}),Z(`p`,{className:`text-gray-600 dark:text-gray-400 max-w-md leading-relaxed`,children:d}),o&&Q(`div`,{className:`text-sm text-gray-500 dark:text-gray-500 mt-2`,children:[`Status: `,o]}),s&&Z(`div`,{className:`text-xs text-gray-400 dark:text-gray-600 mt-1 max-w-md break-words`,children:s}),Z(`div`,{className:`text-sm text-gray-500 dark:text-gray-500 mt-2`,children:`No payment was processed`})]}),Q(`div`,{className:`flex flex-col sm:flex-row gap-3 w-full max-w-xs transition-all duration-700 ease-out delay-400 ${c?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:[Q(`button`,{type:`button`,onClick:n||e,className:`flex-1 flex items-center justify-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors cursor-pointer`,children:[Z(Gi,{className:`w-4 h-4`}),`Try Again`]}),t&&Z(`button`,{type:`button`,onClick:t,className:`flex-1 px-6 py-3 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 font-medium rounded-lg transition-colors cursor-pointer`,children:`Cancel`})]})]})]})},MD=({onTryAgain:e,onBack:t,onRetry:n,title:r=`Session Timeout`,message:i=`Your payment session has timed out. Please try again to continue with your transaction.`,showAnimation:a=!0})=>{let[o,s]=X(!1);return q(()=>{if(a){let e=setTimeout(()=>s(!0),100);return()=>clearTimeout(e)}else s(!0)},[a]),Q(`div`,{className:`space-y-6`,children:[Z(M_,{onBack:t,headerContent:r}),Q(`div`,{className:`flex flex-col items-center justify-center min-h-[400px] space-y-6 px-4`,children:[Z(`div`,{className:`transition-all duration-700 ease-out ${o?`opacity-100 scale-100`:`opacity-0 scale-75`}`,children:Z(`div`,{className:`w-20 h-20 rounded-full bg-orange-100 dark:bg-orange-900/30 flex items-center justify-center`,children:Z(Mi,{className:`w-10 h-10 text-orange-600 dark:text-orange-400`})})}),Q(`div`,{className:`text-center space-y-4 transition-all duration-700 ease-out delay-200 ${o?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:[Z(`h2`,{className:`text-xl font-semibold text-gray-900 dark:text-white`,children:r}),Z(`p`,{className:`text-gray-600 dark:text-gray-400 max-w-md leading-relaxed`,children:i}),Z(`div`,{className:`text-sm text-gray-500 dark:text-gray-500 mt-2`,children:`No payment was processed`})]}),Q(`div`,{className:`flex flex-col sm:flex-row gap-3 w-full max-w-xs transition-all duration-700 ease-out delay-400 ${o?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:[Q(`button`,{type:`button`,onClick:n||e,className:`flex-1 flex items-center justify-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors cursor-pointer`,children:[Z(Gi,{className:`w-4 h-4`}),`Try Again`]}),t&&Z(`button`,{type:`button`,onClick:t,className:`flex-1 px-6 py-3 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 font-medium rounded-lg transition-colors cursor-pointer`,children:`Cancel`})]})]})]})},ND=({txHash:e,chainId:t,className:n=``,expandOnHover:r=!1,sliceStart:i=10,sliceEnd:a=6})=>{let[o,s]=X(!1);if(!tg(e))return null;let c=`${e.slice(0,i)}…${e.slice(-a)}`,l=Xa({txHash:e,chainId:t});return r?Q(`a`,{href:l,target:`_blank`,rel:`noopener noreferrer`,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),className:`font-mono transition-all duration-300 cursor-pointer hover:underline relative inline-block ${n}`,children:[Z(`span`,{className:`transition-all duration-300 ${o?`opacity-0`:`opacity-100`}`,children:c}),Z(`span`,{className:`absolute left-0 top-0 transition-all duration-300 underline ${o?`opacity-100`:`opacity-0`}`,children:e})]}):Z(`a`,{href:l,target:`_blank`,rel:`noopener noreferrer`,className:`font-mono cursor-pointer hover:underline ${n}`,children:c})},PD=e=>{if(!e)return``;let t=[];return e.originDepositAddress&&t.push(`Deposit to: ${wt(e.originDepositAddress)} (${e.originChain?.name||`Chain ${e.originChain?.id}`})`),e.destinationAddress&&e.destinationAddress!==e.originDepositAddress&&t.push(`Recipient: ${wt(e.destinationAddress)} (${e.destinationChain?.name||`Chain ${e.destinationChain?.id}`})`),t.join(`
94
+ `)},FD=({onRampQuote:e,quote:t,tokenSize:n=20,className:r=`mt-4 text-sm text-gray-700 dark:text-gray-300 flex items-center gap-3 justify-center`,textClassName:i=`font-medium`})=>!e?.sourceCurrencyCode||!t?.originToken||!t?.destinationToken?null:Q(`div`,{className:r,title:PD(t),children:[Z(`span`,{className:i,children:e.sourceCurrencyCode}),Z(`span`,{className:`text-gray-500 dark:text-gray-400`,children:`→`}),Q(`div`,{className:`flex items-center gap-2 cursor-help`,title:t.originDepositAddress?`Deposit to: ${t.originDepositAddress}`:void 0,children:[Z(Jy,{imageUrl:t.originToken.imageUrl,symbol:t.originToken.symbol,chainId:t.originChain?.id,contractAddress:t.originToken.contractAddress,size:n}),Z(`span`,{className:i,children:t.originToken.symbol})]}),Z(`span`,{className:`text-gray-500 dark:text-gray-400`,children:`→`}),Q(`div`,{className:`flex items-center gap-2 cursor-help`,title:t.destinationAddress?`Recipient: ${t.destinationAddress}`:void 0,children:[Z(Jy,{imageUrl:t.destinationToken.imageUrl,symbol:t.destinationToken.symbol,chainId:t.destinationChain?.id,contractAddress:t.destinationToken.contractAddress,size:n}),Z(`span`,{className:i,children:t.destinationToken.symbol})]})]}),ID=({onBack:e,onRetry:t,onIntentExecuted:n,quote:r,onRampQuote:i,widgetCreationParams:a,onCreateWidgetSession:o,externalSessionId:c,popupWindowRef:l})=>{let[u,d]=X(!1),[f,p]=X(1200),[m,h]=X(!1),[g,_]=X(!1),[v,y]=X(!1),[b,x]=X(!1),[S,C]=X(0),w=Y(null),{address:T}=Kr(),E=r?.originDepositAddress&&T?.toLowerCase()===r.originDepositAddress.toLowerCase(),{transaction:D,isLoading:O,error:k,settledTransactionHash:A,settledAmount:j,isSuccess:M,windowClosed:N,state:P,resetWindowClosed:F,setWindowRef:I}=Kw({externalSessionId:c,popupOpened:!0,enabled:!!c});q(()=>{if(l)return I(l),()=>{I(null)}},[l,I]);let ee=!!r?.originDepositAddress&&!E,{hasSufficientDeposit:te,depositBalanceFormatted:ne,percentageComplete:re}=OD({chainId:r?.originChain?.id,depositAddress:r?.originDepositAddress,tokenAddress:r?.originToken?.contractAddress,requiredAmount:r?.originAmount,enabled:ee}),ie=E?M:te,L=E?!!c:ee,R=E?j||`0`:ne,ae=E?M?100:0:re,z=E?A:null,B=(N||P===`window-closed`)&&!M&&!ie;q(()=>{let e=c||r?.intentId||`unknown`;!M||w.current===e||(w.current=e,Ef({fundMethod:`onramp-meld`,userAddress:T,intentId:r?.intentId||void 0,intentAddress:r?.originDepositAddress,externalSessionId:c||void 0,transactionId:D?.id,transactionHash:A||D?.transactionHash,status:D?.status||`COMPLETED`,provider:D?.serviceProvider||i?.serviceProvider,sourceAmount:D?.sourceAmount??i?.sourceAmount?.toString(),sourceCurrencyCode:D?.sourceCurrencyCode||i?.sourceCurrencyCode,destinationAmount:j||D?.destinationAmount||i?.destinationAmount?.toString(),destinationCurrencyCode:D?.destinationCurrencyCode||i?.destinationCurrencyCode,countryCode:i?.countryCode,paymentMethodType:i?.paymentMethodType,paymentMethod:D?.paymentMethod}))},[M,T,r?.intentId,r?.originDepositAddress,i?.serviceProvider,i?.sourceAmount,i?.sourceCurrencyCode,i?.destinationAmount,i?.destinationCurrencyCode,i?.countryCode,i?.paymentMethodType,c,D?.id,D?.transactionHash,D?.status,D?.serviceProvider,D?.sourceAmount,D?.sourceCurrencyCode,D?.destinationAmount,D?.destinationCurrencyCode,D?.paymentMethod,A,j]),q(()=>{if(!B&&D?.status){let e=D.status.toUpperCase();[`DECLINED`,`FAILED`,`CANCELLED`].includes(e)&&_(!0),e===`SETTLING`&&!b&&(x(!0),C(0))}},[D?.status,b,B]),q(()=>{d(!0)},[]),q(()=>{!ie||v||(s.console.log(`[OnrampProviderConfirmation] Deposit detected after commit/execute`,{intentId:r?.intentId,transactionHash:z,amount:R,isDirectDeposit:E}),y(!0),n&&n())},[r,v,z,ie,n,E,R]),q(()=>{if(m||B)return;let e=setInterval(()=>{b?C(e=>e+1):p(t=>t<=1?(clearInterval(e),h(!0),0):t-1)},1e3);return()=>clearInterval(e)},[m,b,B]);let V=()=>b?S:f,oe=()=>{h(!1),p(1200),x(!1),C(0),_(!1),y(!1),d(!1),setTimeout(()=>d(!0),100),F()},H=()=>{e?.()},se=async()=>{if(!a||!o){t?.(),F();return}let{popup:e,blocked:n}=Uw(`onramp-widget`,400,700);if(n){s.console.error(`Popup blocked - cannot retry widget`),t?.();return}try{I(e);let{widgetUrl:n}=await o(a);if(!Ww(e,n)){Gw(e),t?.();return}h(!1),p(1200),x(!1),C(0),_(!1),y(!1),d(!1),setTimeout(()=>d(!0),100),F()}catch(n){Gw(e),I(null),s.console.error(`Failed to regenerate widget session:`,n),t?.()}};return B?Z(jD,{onTryAgain:oe,onRetry:se,onBack:H,intentId:r?.intentId,transactionStatus:`CANCELLED`,title:`Onramp Window Closed`,message:`Your onramp window was closed before payment completion. Please try again to restart the flow.`}):g?Z(jD,{onTryAgain:oe,onRetry:se,onBack:H,transactionStatus:D?.status,transactionError:k?.message}):m?Z(MD,{onTryAgain:oe,onRetry:se,onBack:H,title:`Session Timeout`,message:`Your payment session has timed out. Please try again to continue with your onramp transaction.`}):Q(`div`,{className:`space-y-6`,children:[Z(`div`,{className:`flex items-center relative`,children:Z(`button`,{type:`button`,onClick:e,className:`absolute left-0 top-0 p-2 rounded-full transition-colors cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800 hover:trails-hover-bg text-gray-600 dark:text-gray-400`,children:Z(Oi,{className:`h-6 w-6`})})}),Z(`div`,{className:`flex flex-col justify-center min-h-full space-y-6 pt-8`,children:Q(`div`,{className:`text-center`,children:[Q(`div`,{className:`mb-2 transition-all duration-500 ease-out ${u?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:[Z(`h2`,{className:`text-xl font-bold text-gray-900 dark:text-white`,children:b?`Payment is settling...`:`Complete your purchase in the onramp window...`}),Z(`div`,{className:`mt-4 flex items-center justify-center`,children:Q(`div`,{className:`flex items-center space-x-2 px-4 py-2 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-700`,children:[Q(`svg`,{className:`w-5 h-5 text-blue-600 dark:text-blue-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:b?`Processing Time`:`Time Remaining`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z`})]}),Q(`div`,{className:`flex flex-col items-start`,children:[Z(`span`,{className:`text-xs text-blue-600 dark:text-blue-400`,children:b?`Processing for`:`Time remaining`}),Z(`span`,{className:`text-lg font-mono font-bold text-blue-600 dark:text-blue-400`,children:_e(V())})]})]})}),!b&&Z(`p`,{className:`mt-4 text-sm text-left text-gray-600 dark:text-gray-400`,children:`Complete the payment within the time limit. We use USDC on Base network as the intermediary token, please do not change it.`}),Z(FD,{onRampQuote:i,quote:r,tokenSize:20}),b&&Z(`p`,{className:`mt-4 text-sm text-left text-gray-600 dark:text-gray-400`,children:`Your transaction is settling with payment provider. This usually takes 1-5 minutes to complete.`}),(()=>{if(!c)return Z(`div`,{className:`mt-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700`,children:Z(`p`,{className:`text-sm text-gray-600 dark:text-gray-400`,children:`No external session ID - status monitoring disabled`})});if(k)return Z(`div`,{className:`mt-4 p-4 bg-red-50 dark:bg-red-900/20 rounded-lg border border-red-200 dark:border-red-700`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Q(`svg`,{className:`w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`Error`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})]}),Q(`div`,{children:[Z(`p`,{className:`text-sm font-medium text-red-800 dark:text-red-200`,children:`Error checking transaction status`}),Z(`p`,{className:`text-xs text-red-600 dark:text-red-400 mt-1`,children:k.message})]})]})});if(O)return Z(`div`,{className:`mt-4 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-700`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Q(`svg`,{className:`w-5 h-5 text-blue-600 dark:text-blue-400 animate-spin`,fill:`none`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`Loading`}),Z(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),Z(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z`})]}),Z(`p`,{className:`text-sm text-blue-800 dark:text-blue-200`,children:`Checking transaction status...`})]})});if(D?.status){let e=e=>{switch(e?.toUpperCase()){case`COMPLETED`:case`SUCCESS`:return`green`;case`SETTLING`:return`blue`;case`DECLINED`:case`FAILED`:return`red`;case`ERROR`:case`PENDING`:case`PROCESSING`:return`yellow`;default:return`blue`}},t=e=>{switch(e?.toUpperCase()){case`COMPLETED`:case`SUCCESS`:return`Payment completed successfully`;case`SETTLING`:return`Finalizing your payment with the provider`;case`PENDING`:return`Waiting for payment confirmation`;case`PROCESSING`:return`Processing your payment`;case`ERROR`:return`Verifying payment status`;case`DECLINED`:return`Payment was declined`;case`FAILED`:return`Payment failed`;default:return`Checking payment status`}},n=e(D.status),r={green:`bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-700`,red:`bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-700`,yellow:`bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-700`,blue:`bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-700`},i={green:`text-green-800 dark:text-green-200`,red:`text-red-800 dark:text-red-200`,yellow:`text-yellow-800 dark:text-yellow-200`,blue:`text-blue-800 dark:text-blue-200`},a={green:`text-green-600 dark:text-green-400`,red:`text-red-600 dark:text-red-400`,yellow:`text-yellow-600 dark:text-yellow-400`,blue:`text-blue-600 dark:text-blue-400`};return Z(`div`,{className:`mt-4 p-4 rounded-lg border ${r[n]}`,children:Q(`div`,{className:`flex items-start space-x-3`,children:[Z(`div`,{className:`flex-shrink-0 mt-0.5`,children:n===`yellow`||n===`blue`||D.status?.toUpperCase()===`SETTLING`?Q(`svg`,{className:`w-5 h-5 ${a[n]} animate-spin`,fill:`none`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`Processing`}),Z(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),Z(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z`})]}):n===`green`?Q(`svg`,{className:`w-5 h-5 ${a[n]}`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`Success`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z`})]}):Q(`svg`,{className:`w-5 h-5 ${a[n]}`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`Error`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z`})]})}),Q(`div`,{className:`flex-1 text-left`,children:[Z(`p`,{className:`text-sm font-medium ${i[n]}`,children:t(D.status)}),Q(`p`,{className:`text-xs mt-1 ${i[n]} opacity-75`,children:[`Status:`,` `,D.status===`ERROR`?`PROCESSING`:D.status?.toUpperCase()]}),(D.sourceAmount||D.destinationAmount)&&Q(`p`,{className:`text-xs mt-1 ${i[n]} opacity-75`,children:[`Amount:`,` `,D.sourceAmount||D.destinationAmount,` `,D.sourceCurrencyCode||D.destinationCurrencyCode]})]})]})})}return Q(hi,{children:[Z(`div`,{className:`mt-4 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-700`,children:Q(`div`,{className:`flex items-start space-x-3`,children:[Z(`div`,{className:`flex-shrink-0 mt-0.5`,children:Q(`svg`,{className:`w-5 h-5 text-blue-600 dark:text-blue-400 animate-spin`,fill:`none`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`Loading`}),Z(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),Z(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z`})]})}),Q(`div`,{className:`flex-1`,children:[Z(`p`,{className:`text-sm font-medium text-blue-800 dark:text-blue-200`,children:`Initializing payment monitoring`}),Z(`p`,{className:`text-xs mt-1 text-blue-800 dark:text-blue-200 opacity-75`,children:`Status: INITIALIZING`})]})]})}),Z(FD,{onRampQuote:i,quote:r,tokenSize:14,className:`text-xs mt-2 text-gray-600 dark:text-gray-400 opacity-70 flex items-center gap-2 justify-center`,textClassName:``})]})})(),r?.originDepositAddress?L?ie?Z(`div`,{className:`mt-4 p-4 bg-green-50 dark:bg-green-900/20 rounded-lg border border-green-200 dark:border-green-700`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Q(`svg`,{className:`w-5 h-5 text-green-600 dark:text-green-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`Success`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M5 13l4 4L19 7`})]}),Q(`div`,{children:[Z(`p`,{className:`text-sm font-medium text-green-800 dark:text-green-200`,children:E?`Funds arrived at recipient address`:`Funds arrived at intent address`}),Q(`p`,{className:`text-xs text-green-600 dark:text-green-400 mt-1`,children:[`Received: `,R,` `,r?.originToken?.symbol]}),z?Q(`p`,{className:`text-xs text-green-600 dark:text-green-400 mt-1`,children:[`Transaction:`,` `,Z(ND,{txHash:z,chainId:r?.originChain?.id||1,className:`text-green-600 dark:text-green-400`})]}):E&&M&&Z(`p`,{className:`text-xs text-green-600 dark:text-green-400 mt-1`,children:`Transaction confirmed`}),v&&!E&&Z(`p`,{className:`text-xs text-green-600 dark:text-green-400 mt-2 font-medium`,children:`Processing transaction...`})]})]})}):R&&Number(R)>0?Z(`div`,{className:`mt-4 p-4 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-700`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Q(`svg`,{className:`w-5 h-5 text-yellow-600 dark:text-yellow-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`Waiting`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z`})]}),Q(`div`,{children:[Z(`p`,{className:`text-sm font-medium text-yellow-800 dark:text-yellow-200`,children:E?`Waiting for transaction confirmation...`:`Monitoring for deposits...`}),ae>0&&Q(`div`,{className:`mt-2`,children:[Q(`div`,{className:`flex justify-between text-xs text-yellow-600 dark:text-yellow-400 mb-1`,children:[Z(`span`,{children:`Progress`}),Q(`span`,{children:[ae.toFixed(0),`%`]})]}),Z(`div`,{className:`w-full bg-yellow-200 dark:bg-yellow-800 rounded-full h-2`,children:Z(`div`,{className:`bg-yellow-600 dark:bg-yellow-400 h-2 rounded-full transition-all duration-500`,style:{width:`${Math.min(ae,100)}%`}})})]}),Q(`p`,{className:`text-xs text-yellow-600 dark:text-yellow-400 mt-1`,children:[`Current balance: `,R,` `,r?.originToken?.symbol]})]})]})}):null:Z(`div`,{className:`mt-4 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-700`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Q(`svg`,{className:`w-5 h-5 text-blue-600 dark:text-blue-400 animate-spin`,fill:`none`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`Loading`}),Z(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),Z(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z`})]}),Z(`p`,{className:`text-sm text-blue-800 dark:text-blue-200`,children:`Starting deposit monitoring...`})]})}):null,Z(`div`,{className:`mt-3 p-3 bg-amber-50 dark:bg-amber-900/20 rounded-lg border border-amber-200 dark:border-amber-700`,children:Q(`div`,{className:`flex items-start space-x-3`,children:[Z(`div`,{className:`flex-shrink-0 mt-0.5`,children:Z(`span`,{className:`text-amber-600 dark:text-amber-400`,children:`⚠️`})}),Z(`div`,{className:`flex-1 text-left`,children:Z(`p`,{className:`text-sm font-medium text-amber-800 dark:text-amber-200`,children:`Important: Do not close this window or navigate away while your payment is processing.`})})]})})]}),!b&&f<=60&&f>0&&Z(`div`,{className:`transition-all duration-500 ease-out delay-150 ${u?`opacity-100 translate-y-0`:`opacity-0 translate-y-4`}`,children:Z(`div`,{className:`p-4 trails-border-radius-container text-sm bg-yellow-50 border border-solid border-yellow-200 dark:bg-yellow-900/20 dark:border-yellow-700/50`,children:Q(`div`,{className:`flex items-start space-x-3`,children:[Q(`svg`,{className:`w-5 h-5 mt-0.5 shrink-0 text-yellow-600 dark:text-yellow-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:[Z(`title`,{children:`Warning`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z`})]}),Q(`div`,{children:[Z(`p`,{className:`font-medium text-yellow-800 dark:text-yellow-300`,children:`Less than 1 minute remaining`}),Z(`p`,{className:`mt-1 text-xs text-yellow-700 dark:text-yellow-400`,children:`Please complete your payment soon or the transaction will be canceled.`})]})]})})}),Z(wb,{quote:r,onRampQuote:i,showContent:!0,compact:!0})]})})]})},LD=({onBack:e,onSelectWalletConnect:t,onSelectQRCode:n})=>Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:e,headerContent:`QR Code Options`,headerContentAlign:`left`,rightSideContent:Z(`div`,{className:`w-9`})}),Z(`div`,{className:`flex-1`,children:Z(`div`,{className:`space-y-4`,children:Q(`div`,{className:`trails-border-radius-container border trails-border-primary`,children:[Q(`button`,{type:`button`,onClick:t,className:`w-full text-left px-3 py-4 text-sm flex items-center justify-between cursor-pointer transition-colors trails-text-primary trails-hover-bg`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(na,{className:`w-4 h-4`}),Z(`span`,{className:`text-sm font-bold`,children:`Via WalletConnect`}),Z(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200`,children:`Recommended`})]}),Z(ki,{className:`w-5 h-5 text-gray-400`})]}),Z(`div`,{className:`border-b border-gray-200 dark:border-gray-700`}),Q(`button`,{type:`button`,onClick:n,className:`w-full text-left px-3 py-4 text-sm flex items-center justify-between cursor-pointer transition-colors trails-text-primary trails-hover-bg`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(Wi,{className:`w-4 h-4`}),Z(`span`,{className:`text-sm font-bold`,children:`Via Deposit QR Code`})]}),Z(ki,{className:`w-5 h-5 text-gray-400`})]})]})})})]}),RD=({onBack:e,onSelect:t,selectedWalletId:n,walletOptions:r,title:i=`Which wallet will scan the QR code?`,disabled:a=!1})=>{let o=la();return Q(`div`,{className:`space-y-6`,children:[Z(M_,{onBack:e,headerContent:`Deposit`,headerContentAlign:`left`}),Q(`div`,{className:`space-y-6`,children:[Z(`div`,{className:`text-center px-4`,children:Z(`h2`,{className:`text-lg font-semibold text-gray-900 dark:text-gray-100`,children:i})}),Z(`div`,{className:`grid grid-cols-2 gap-3`,children:(r||o).map(e=>Q(`button`,{type:`button`,onClick:()=>!a&&t(e.id),disabled:a,className:`flex flex-col items-center justify-center gap-3 rounded-xl border px-4 py-6 text-center transition-all duration-200 min-h-[120px] ${e.id===n?`border-blue-500 bg-blue-50 shadow-md dark:border-blue-400 dark:bg-blue-900/30`:`border-gray-200 bg-white hover:bg-gray-50 hover:shadow-sm active:scale-[0.98] dark:border-gray-700 dark:bg-gray-900 dark:hover:bg-gray-800`} ${a?`opacity-60 cursor-not-allowed`:`cursor-pointer`}`,children:[Z(Na,{walletId:e.id,label:e.label,size:48,className:`h-12 w-12 shrink-0`,fallback:Z(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-gray-200 text-sm font-semibold text-gray-600 dark:bg-gray-700 dark:text-gray-200 shrink-0`,children:e.label.charAt(0).toUpperCase()})}),Z(`div`,{className:`text-sm font-semibold text-gray-900 dark:text-gray-100`,children:e.label})]},e.id))})]})]})};async function zD(e,t,n){let r=Va(n);return Promise.all(t.map(async t=>{if(t.isNative){let n=await r.getBalance({address:e});return{...t,balance:n}}try{let n=await r.readContract({address:t.tokenAddress,abi:_n,functionName:`balanceOf`,args:[e]});return{...t,balance:n}}catch(r){return s.console.warn(`[recover] Failed to read token balance; treating as zero`,{tokenAddress:t.tokenAddress,intentAddress:e,chainId:n,error:r}),{...t,balance:0n}}}))}async function BD(e,t,n,r){let i=await zD(e,n,r),a=[];for(let{tokenAddress:e,isNative:n,balance:r}of i)r<=0n||(n?a.push({to:t,value:r,data:`0x`,gasLimit:0n,delegateCall:!1,onlyFallback:!1,behaviorOnError:`revert`}):a.push({to:Ca.from(e),value:0n,data:L_(t,r),gasLimit:0n,delegateCall:!1,onlyFallback:!1,behaviorOnError:`revert`}));return a.length===0?{payload:{type:`call`,space:VD(),nonce:0n,calls:[]},hasBalance:!1}:{payload:{type:`call`,space:VD(),nonce:0n,calls:a},hasBalance:!0}}function VD(){if(!globalThis.crypto?.getRandomValues)throw Error(`Secure random generator not available for recovery space`);let e=new Uint8Array(20);globalThis.crypto.getRandomValues(e);let t=BigInt(`0x${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}`);if(t<=1n)throw Error(`Generated reserved recovery space`);return t}async function HD(e,t,n,r,i,a,o){let s=$(t);if(!s)throw Error(`Chain info not found for chain ID: ${t}`);let c=await vC(e,t),l=jC(i,r),u=!1,d=Xt.fillLeaves(a.topology,e=>{if(Ca.isEqual(Ca.from(e.address),r))return u=!0,l});if(!u)throw Error(`Signer ${r} is not an authorized signer for intent wallet ${e}. Connect the correct wallet to recover.`);let f=Xt.encodeSignature({noChainId:!1,configuration:{threshold:a.threshold,checkpoint:a.checkpoint,checkpointer:a.checkpointer,topology:d}}),p=Sa.encodeData(Kt.EXECUTE,[wa.toHex(Jt.encode(n)),wa.toHex(f)]);if(!c){let t=wa.toHex(Gt.hashConfiguration(a)),n=qt.deploy(t,o),r=Kt.DefaultGuestAddress,i={type:`call`,space:0n,nonce:0n,calls:[{to:n.to,value:0n,data:n.data,gasLimit:0n,delegateCall:!1,onlyFallback:!1,behaviorOnError:`revert`},{to:e,value:0n,data:p,gasLimit:0n,delegateCall:!1,onlyFallback:!1,behaviorOnError:`revert`}]};return{to:r,data:wa.toHex(Jt.encode(i,r)),chain:s}}return{to:e,data:p,chain:s}}function UD({intent:e,walletClient:t,ownerAddress:n}){let r=t?pi(t):void 0,[i,a]=X(!1),[o,c]=X(null);return{recover:K(async()=>{a(!0),c(null);try{if(!e)throw Error(`No stored intent available for offline recovery`);if(!r?.account)throw Error(`Wallet client account is required for recovery`);let t=Ca.from(r.account.address),i=Ca.from(n),a=[];e.originIntentAddress&&a.push({intentAddress:Ca.from(e.originIntentAddress),chainId:e.originChainId,tokens:[{tokenAddress:e.originTokenAddress,isNative:bt(e.originTokenAddress)}]}),e.destinationIntentAddress&&e.destinationTokenAddress&&a.push({intentAddress:Ca.from(e.destinationIntentAddress),chainId:e.destinationChainId,tokens:[{tokenAddress:e.destinationTokenAddress,isNative:bt(e.destinationTokenAddress)}]});let o,c,l,u;for(let e of a){let t=bm(e.intentAddress);if(!t){s.console.debug(`[trails-sdk] No cached config for intent address, skipping`,e.intentAddress);continue}let{payload:n,hasBalance:r}=await BD(e.intentAddress,i,e.tokens,e.chainId);if(!r){s.console.debug(`[trails-sdk] No balance at intent address, skipping`,e.intentAddress);continue}o=e,c=n,l=t.config,u=t.context;break}if(!o||!c||!l||!u)throw Error(`No recoverable balance found — either no funds remain or intent configuration is not cached`);await Hh({walletClient:r,desiredChainId:o.chainId}),await Nr(r);let d=Jt.toTyped(o.intentAddress,o.chainId,c),f=await Wr(r.signTypedData({account:r.account,...d}),`Offline recovery signature`),p=await HD(o.intentAddress,o.chainId,c,t,f,l,u),m={account:r.account,to:p.to,data:p.data,chain:p.chain};return await r.sendTransaction(m)}catch(e){let t=e instanceof Error?e:Error(String(e));throw c(t),t}finally{a(!1)}},[e,r,n]),isLoading:i,error:o}}function WD(e){return!!e&&typeof e==`object`&&`transaction`in e&&!!e.transaction?.intentId&&`balancesByIntentAddress`in e}const GD=({data:e,onBack:t})=>{let n=WD(e)?e:null,r=n?.transaction,i=kr(),{data:a}=si(),o=ci(n?.selectedWallet?.connectionId,n?.selectedWallet?.address)||a||null,{sequenceSupport:c,trailsAppUrl:l}=Vx(),[u,d]=X(!1),[f,p]=X(!1),[m,h]=X(!1),[,g]=X(!1),[_,v]=X(!1),y=Y(!1),b=Y(!1),[x,S]=X(null),[C,w]=X(null),T=J(()=>!r?.intentId||!r.mainSigner?null:Om(r.mainSigner).find(e=>e.intentId===r.intentId)??null,[r?.intentId,r?.mainSigner]),{intent:E,isLoading:D,error:O,refetch:k}=DS({intentId:r?.intentId,enabled:!!r?.intentId}),A=E||T,j=K(()=>{y.current=!0,v(!0),p(!1),h(!1)},[]),{recover:M,recoverToken:N,selectedRecoveryTarget:P,hasIntentBalance:F}=qC({intent:C?null:A,balancesByIntentAddress:n?.balancesByIntentAddress??{},walletClient:o||void 0,onTransactionSubmitted:j}),{recover:I,isLoading:ee}=UD({intent:T,walletClient:o||void 0,ownerAddress:r?.mainSigner??``}),te=u||ee,ne=N?.chainId??P?.chainId,re=!!c?.WaasFeeOptionsController&&!!ne,ie=!!r?.intentId&&!!o&&!C&&!_&&(F||n?.isOffline&&!!T),L=K(()=>{let e=n?.selectedWallet?.address||r?.mainSigner;setTimeout(()=>{i.invalidateQueries({queryKey:[`intentTransactionHistory`,e]}),i.invalidateQueries({queryKey:[`getIntent`,r?.intentId]}),k()},2e3)},[i,k,r?.intentId,r?.mainSigner,n?.selectedWallet?.address]),R=K(async()=>{if(!b.current){if(!r?.intentId||!o){s.console.error(`[Recover] Cannot recover: missing intentId or walletClient`);return}b.current=!0;try{d(!0),S(null),re||(y.current=!1,v(!1));let e,t=ne??r.originChainId??0;if(T)e=await I();else{let n=await M();e=n.txHash,t=n.chainId}s.console.log(`[Recover] Recover transaction sent`,{intentId:r.intentId,txHash:e}),t&&w({hash:e,chainId:t}),S(null),L()}catch(e){s.console.error(`[Recover] Failed to recover intent`,{intentId:r.intentId,error:e});let t=e instanceof Error?e.message:typeof e==`string`?e:`Failed to recover intent. Please try again.`;y.current||v(!1),S(t)}finally{b.current=!1,d(!1),p(!1),h(!1)}}},[o,re,L,M,I,ne,T,r]);q(()=>{!f||!m||(h(!1),R())},[R,m,f]);let ae=()=>{if(!r?.intentId||!o){s.console.error(`[Recover] Cannot recover: missing intentId or walletClient`);return}if(!(b.current||_)){if(S(null),g(!1),y.current=!1,v(!1),re){p(!0),h(!0);return}R()}},z=K(e=>{g(e),e&&j()},[j]),B=r?.intentId?`${l}/intent/${r.intentId}`:null,V=P?.address?Za({address:P.address,chainId:P.chainId}):null,oe=N?.contractAddress&&N.chainId?Za({address:N.contractAddress,chainId:N.chainId}):null,H=J(()=>C?Xa({txHash:C.hash,chainId:C.chainId}):null,[C]);return!n||!r?Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:t,headerContent:`Recover funds`}),Z(`div`,{className:`flex flex-1 items-center justify-center px-4 py-10 text-center`,children:Q(`div`,{children:[Z(`h3`,{className:`mb-2 text-base font-medium text-gray-900 dark:text-gray-100`,children:`Recovery details unavailable`}),Z(`p`,{className:`text-sm text-gray-600 dark:text-gray-400`,children:`Return to history and select a recoverable transaction.`})]})})]}):Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:t,headerContent:`Recover funds`,rightSideContent:Z(`button`,{type:`button`,onClick:()=>void k(),disabled:D,className:`p-2 rounded-md transition-colors cursor-pointer ${D?`opacity-50 cursor-not-allowed text-gray-400 dark:text-gray-500`:`text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-gray-700 dark:hover:text-gray-200`} focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400`,title:`Refresh recovery details`,"aria-label":`Refresh recovery details`,children:Q(`svg`,{className:`w-4 h-4 ${D?`animate-spin`:``}`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:[Z(`title`,{children:`Refresh recovery details`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15`})]})})}),Q(`div`,{className:`flex flex-1 flex-col gap-4 overflow-y-auto py-2 trails-scrollbar`,children:[Q(`div`,{className:`rounded-lg border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-800/60`,children:[Q(`div`,{className:`mb-3 flex items-center justify-between gap-3`,children:[Q(`div`,{children:[Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`Intent`}),Q(`div`,{className:`flex items-center gap-1.5`,children:[B?Q(`a`,{href:B,target:`_blank`,rel:`noopener noreferrer`,className:`flex cursor-pointer items-center gap-1 font-mono text-xs text-gray-900 transition-colors hover:text-blue-600 hover:underline dark:text-gray-100 dark:hover:text-blue-400`,title:`View intent on Trails`,children:[wt(r.intentId,6,6),Q(`svg`,{className:`h-3 w-3 shrink-0`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,children:[Z(`title`,{children:`View intent`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14`})]})]}):Z(`div`,{className:`font-mono text-xs text-gray-900 dark:text-gray-100`,children:wt(r.intentId,6,6)}),Z(U,{text:r.intentId??``,size:`sm`,className:`p-1`})]})]}),P&&Q(`div`,{className:`text-right`,children:[Q(`div`,{className:`flex items-center justify-end gap-1.5`,children:[Z(Ty,{chainId:P.chainId,size:16}),Z(`span`,{className:`text-xs font-medium text-gray-900 dark:text-gray-100`,children:P.chainName}),Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:P.isOrigin?`Origin`:`Destination`})]}),P.address&&Q(`div`,{className:`mt-0.5 flex justify-end items-center gap-1 font-mono text-xs text-gray-500 dark:text-gray-400`,children:[V?Q(`a`,{href:V,target:`_blank`,rel:`noopener noreferrer`,className:`flex cursor-pointer items-center gap-1 transition-colors hover:text-blue-600 hover:underline dark:hover:text-blue-400`,title:`View intent address on explorer`,children:[wt(P.address,4,4),Q(`svg`,{className:`h-3 w-3 shrink-0`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,children:[Z(`title`,{children:`View intent address`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14`})]})]}):Z(`span`,{children:wt(P.address,4,4)}),Z(U,{text:P.address,size:`sm`,className:`p-1`})]})]})]}),N?Q(`div`,{className:`flex items-center justify-between gap-3 rounded-lg bg-white px-3 py-2 dark:bg-gray-900`,children:[Q(`div`,{className:`flex min-w-0 items-center gap-2`,children:[Z(Jy,{symbol:N.symbol,imageUrl:N.imageUrl,chainId:N.chainId,size:28}),Q(`div`,{className:`min-w-0`,children:[Z(`div`,{className:`truncate text-sm font-medium text-gray-900 dark:text-gray-100`,children:N.symbol}),N.contractAddress&&Q(`div`,{className:`flex items-center gap-1 font-mono text-xs text-gray-500 dark:text-gray-400`,children:[oe?Q(`a`,{href:oe,target:`_blank`,rel:`noopener noreferrer`,className:`flex cursor-pointer items-center gap-1 transition-colors hover:text-blue-600 hover:underline dark:hover:text-blue-400`,title:`View token address on explorer`,children:[wt(N.contractAddress,4,4),Q(`svg`,{className:`h-3 w-3 shrink-0`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,children:[Z(`title`,{children:`View token address`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14`})]})]}):Z(`span`,{children:wt(N.contractAddress,4,4)}),Z(U,{text:N.contractAddress,size:`sm`,className:`p-1`})]})]})]}),Q(`div`,{className:`text-right`,children:[Q(`div`,{className:`text-sm font-medium text-gray-900 dark:text-gray-100`,children:[N.balanceFormatted,` `,N.symbol]}),N.balanceUsdDisplay&&Q(`div`,{className:`mt-0.5 text-xs text-gray-500 dark:text-gray-400`,children:[`≈ `,N.balanceUsdDisplay]})]})]}):D?Z(`div`,{className:`py-4 text-center text-sm text-gray-600 dark:text-gray-400`,children:`Loading recovery details...`}):Z(`div`,{className:`py-4 text-center text-sm text-gray-600 dark:text-gray-400`,children:T?`Recoverable funds will be checked from locally stored intent data.`:`No recoverable token balance is available for this intent.`})]}),O&&Z(XC,{error:O.message,severity:`warning`}),x&&Z(XC,{error:x,severity:`error`}),f&&re&&!_&&Q(`div`,{className:`rounded-lg border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-800/60`,children:[Z(`div`,{className:`mb-3 text-sm font-medium text-gray-900 dark:text-gray-100`,children:`Select a fee token to restore funds with your embedded wallet`}),Z(Lb,{chainId:ne,setIsFeeOptionConfirmed:z})]}),H?Q(`a`,{href:H,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex cursor-pointer items-center justify-center gap-1.5 text-sm font-medium text-blue-600 transition-colors hover:text-blue-700 hover:underline dark:text-blue-400 dark:hover:text-blue-300`,title:`View refund on explorer`,children:[C&&Z(Ty,{chainId:C.chainId,size:16}),Z(`span`,{children:`View refund`}),Q(`svg`,{className:`h-3.5 w-3.5 shrink-0`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,children:[Z(`title`,{children:`View refund on explorer`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14`})]})]}):Z(`button`,{type:`button`,onClick:ae,disabled:!ie||te||_,className:`inline-flex cursor-pointer items-center justify-center rounded-full bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500 dark:bg-blue-700 dark:hover:bg-blue-600 dark:disabled:bg-gray-700 dark:disabled:text-gray-400`,children:_&&te?`Tx Sent`:te?`Restoring...`:_?`Tx Sent`:`Recover`})]})]})},KD=`trails-recent-recipients`;function qD(){let[e,t]=X([]);q(()=>{try{let e=localStorage.getItem(KD);if(e){let n=JSON.parse(e).sort((e,t)=>t.timestamp-e.timestamp);t(n)}}catch(e){s.console.error(`[trails-sdk] Failed to load recent recipients:`,e)}},[]);let n=K(e=>{try{localStorage.setItem(KD,JSON.stringify(e))}catch(e){s.console.error(`[trails-sdk] Failed to save recent recipients:`,e)}},[]),r=K(async e=>{try{return e.endsWith(`.eth`)?(s.console.log(`[trails-sdk] ENS resolution not implemented: ${e}`),{ensName:e}):bn(e)?(s.console.log(`[trails-sdk] Reverse ENS resolution not implemented: ${e}`),{address:e,ensName:``}):{}}catch(e){return s.console.error(`[trails-sdk] ENS resolution failed:`,e),{}}},[]);return{recentRecipients:e,addRecentRecipient:K(async(e,r,i)=>{let a=e.trim();if(!a)return;let o;if(bn(a))o={address:a,ensName:i,timestamp:Date.now()};else if(ut(a))o={address:a,timestamp:Date.now()};else if(a.endsWith(`.eth`))if(r&&bn(r))o={address:r,ensName:i||a,resolvedAddress:r,timestamp:Date.now()};else return;else return;t(e=>{let t=e.filter(e=>!at(e.address,o.address)&&(!o.ensName||e.ensName!==o.ensName)),r=[o,...t].slice(0,10);return n(r),r}),s.console.log(`[trails-sdk] Added recent recipient:`,o)},[n]),removeRecentRecipient:K(e=>{t(t=>{let r=t.filter(t=>!at(t.address,e));return n(r),r})},[n]),clearRecentRecipients:K(()=>{t([]);try{localStorage.removeItem(KD)}catch(e){s.console.error(`[trails-sdk] Failed to clear recent recipients:`,e)}},[]),resolveENS:r}}const JD=({recipientInput:e,onChange:t,validationMessage:n,validationColor:r=`text-gray-500`,onUseConnected:i,canUseConnected:a=!1,placeholder:o=`0x123... or vitalik.eth`})=>{let[s,c]=X(e),l=Y(void 0);q(()=>{c(e)},[e]),q(()=>(l.current!==void 0&&window.clearTimeout(l.current),l.current=window.setTimeout(()=>{s!==e&&t(s)},300),()=>{l.current!==void 0&&window.clearTimeout(l.current)}),[s,e,t]);let u=s.trim(),d=bn(u)||ut(u);return Q(`div`,{children:[Z(`label`,{htmlFor:`recipient-input`,className:`block text-xs text-gray-500 dark:text-gray-400 mb-2`,children:`Address or ENS name`}),Q(`div`,{className:`relative`,children:[Z(`input`,{type:`text`,id:`recipient-input`,value:s,onChange:e=>c(e.target.value),placeholder:o,className:`w-full px-4 py-4 rounded-xl border trails-border-primary bg-transparent trails-text-primary placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-grey-500 focus:border-transparent text-xs`}),!d&&a&&i&&s.length<12&&Z(`button`,{type:`button`,onClick:i,className:`absolute right-3 top-1/2 -translate-y-1/2 text-xs font-medium text-polygon-500 hover:text-polygon-600 transition-colors cursor-pointer`,children:`Use connected`})]}),n&&Z(`p`,{className:`text-xs ${r} text-left mt-2 ml-2`,children:n})]})};function YD(e,t){return`${e?.trim()||`Wallet`} ${t}`}const XD=({address:e,walletLabel:t,children:n})=>Q(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[Q(`div`,{className:`flex items-center space-x-1`,children:[Z(cw,{address:e,className:`text-sm font-medium trails-text-primary`}),n]}),Z(`div`,{className:`text-xs text-gray-400 truncate`,children:t})]}),ZD=e=>e!==null&&e!==`recipients`,QD={pay:`send-form`,fund:`fund-form`,earn:`earn`,swap:`swap`,withdraw:`withdraw`};function $D(e,t){return Zl(e,t)?!1:bn(e)?t.mode===`earn`?tu(e,t):!0:tu(e,t)}const eO=({onBack:e,selectedRecipient:t=``,onRecipientSelect:n})=>{let{navigate:r,mode:i,backScreen:a}=y_(),{setSelectedRecipient:o}=cu(),{selectedToken:c}=xl(),{selectedToken:l}=ul(),u=qu(),d=J(()=>({mode:i,destinationChainId:c?.chainId,originChainId:l?.chainId}),[c?.chainId,i,l?.chainId]),f=$l(d),p=u?.connected&&u.publicKey?u.publicKey.toBase58():null,m=p!==null&&Zl(p,d),h=m?`Solana-to-Solana transfers are not supported`:void 0,{recentRecipients:g,addRecentRecipient:_,clearRecentRecipients:v}=qD(),[y,b]=X(t),{address:x,connectionId:S}=Kr(),{chainId:C}=Yr(),w=Xr(),T=Jr(),E=J(()=>T.filter(e=>et(e.address)),[T]),{setConnectionContext:D}=$o(),O=a===`withdraw`,k=J(()=>{let e=E.map(e=>e.address);return p&&e.push(p),e},[E,p]),A=J(()=>g.filter(e=>!(!$D(e.address,d)||!O&&k.some(t=>at(t,e.address)))),[g,d,k,O]),j=y.trim(),M=Xl(j),{ensAddress:N,isLoading:P,isFetching:F}=Py({textInput:j}),{ensName:I}=Fy({address:bn(j)?j:``}),ee=M&&!N&&(P||F),te=J(()=>j?ut(j)?$D(j,d):bn(j)?!0:M?!!N:!1:!1,[j,M,N,d]),ne=K(()=>ZD(a)?a:QD[i],[i,a]),re=Y(!1),ie=K(e=>{s.console.log(`[trails-sdk] Auto-selecting entered recipient:`,e),o(e),n?.(e),r(ne())},[o,n,r,ne]);q(()=>{let e=setTimeout(async()=>{if(j){if(ut(j)){if(!$D(j,d))return;await _(j,j),re.current&&ie(j);return}if(bn(j)){I?await _(j,j,I):await _(j,j),re.current&&$D(j,d)&&ie(j);return}M&&N&&(await _(j,N,j),re.current&&$D(N,d)&&ie(N))}},300);return()=>clearTimeout(e)},[_,ie,N,I,M,j,d]);let L=K(e=>{re.current=!0,b(e)},[]),R=K(()=>{if(re.current=!0,x){b(x);return}f&&p&&b(p)},[x,f,p]),ae=K(e=>{$D(e.address,d)&&(s.console.log(`[trails-sdk] Selected recent recipient:`,e),o(e.address),n?.(e.address),r(ne()))},[o,n,r,ne,d]),z=K(e=>{$D(e,d)&&(s.console.log(`[trails-sdk] Selected connected wallet:`,e),o(e),n?.(e),r(ne()))},[o,n,r,ne,d]),B=()=>au(y,d,{isValidAddress:te,isLoadingEns:ee,resolvedEnsAddress:M?N:void 0}),V=()=>{let e=B();return e?e===`Resolving ENS name...`?`text-blue-500`:`text-red-500`:te?`text-green-500`:y.trim()?`text-red-500`:`text-gray-500`},oe=f?`0x... or Solana address`:`0x... or vitalik.eth`;return Q(`div`,{className:`space-y-4`,children:[Z(M_,{onBack:e,headerContent:O?`Withdraw to`:`Select recipient address`,headerContentAlign:`center`}),Q(`div`,{className:`space-y-4`,children:[!y.trim()&&!O&&Q(`div`,{className:`space-y-2`,children:[Q(`div`,{className:`mb-2 flex items-center justify-between gap-2 px-1`,children:[Z(`p`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:`Connected wallets`}),Q(`button`,{type:`button`,onClick:()=>{D(`recipient-selection`,ne(),x,S),r(`wallet-list`,{backTarget:`recipients`})},className:`inline-flex items-center gap-1 rounded-full px-2 py-1 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700 cursor-pointer`,"aria-label":`Connect additional wallet`,children:[Z(ji,{"aria-hidden":`true`,className:`h-3.5 w-3.5`}),Z(`span`,{children:`Add wallet`})]})]}),E.map(e=>Z(`button`,{type:`button`,className:`w-full text-left px-4 py-2 text-sm flex items-center cursor-pointer transition-colors rounded-xl hover:bg-gray-100 dark:hover:bg-gray-700`,onClick:()=>z(e.address),children:Q(`div`,{className:`flex items-center gap-3`,children:[Z(gw,{walletAddress:e.address,walletId:e.walletId,connector:e.connector,icon:e.icon,iconAlt:e.name??`Wallet`,chainId:dw(e,w,C),networks:[`evm`],size:30}),Z(XD,{address:e.address,walletLabel:YD(e.name,`EVM`),children:Z(U,{text:e.address,stopPropagation:!0,className:`p-0.5 z-10 relative`,size:`sm`,as:`span`})})]})},e.address)),(f||m)&&p&&Z(`button`,{type:`button`,"aria-disabled":m||void 0,"data-disabled-reason":h,title:h,className:`w-full text-left px-4 py-2 text-sm flex items-center transition-colors rounded-xl ${m?`opacity-50 cursor-not-allowed hover:bg-transparent dark:hover:bg-transparent`:`cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700`}`,onClick:()=>{m||z(p)},children:Q(`div`,{className:`flex items-center gap-3`,children:[Z(gw,{walletAddress:p,walletId:u?.walletId,icon:u?.walletIcon,iconAlt:u?.walletName??`Solana`,networks:[`solana`],size:30}),Z(XD,{address:p,walletLabel:YD(u?.walletName,`SVM`),children:Z(U,{text:p,stopPropagation:!0,className:`p-0.5 z-10 relative`,size:`sm`,as:`span`})})]})},p)]}),!y.trim()&&!O&&Z(`div`,{className:`border-b border-gray-200 dark:border-gray-700`}),Z(`div`,{className:`space-y-2`,children:O?Z(JD,{recipientInput:y,onChange:L,validationMessage:B(),validationColor:V(),onUseConnected:R,canUseConnected:!!(x||f&&p),placeholder:oe}):Q(hi,{children:[Z(`input`,{type:`text`,value:y,onChange:e=>L(e.target.value),placeholder:oe,className:`w-full px-4 py-4 text-sm rounded-xl border trails-border-primary bg-transparent trails-text-primary placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-grey-500 focus:border-transparent`}),B()&&Z(`p`,{className:`text-xs ${V()} text-left`,children:B()})]})}),A.length>0&&Q(`div`,{className:`space-y-2`,children:[Q(`div`,{className:`flex items-center justify-between`,children:[Z(`div`,{className:`text-sm font-medium text-gray-900 dark:text-gray-100 text-left`,children:`Recent recipient addresses`}),Q(`button`,{type:`button`,onClick:v,className:`flex items-center gap-1 px-2 py-1 text-xs font-medium text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors cursor-pointer`,children:[`Clear`,Z(ra,{className:`w-3 h-3`})]})]}),Z(`div`,{className:`trails-border-radius-container max-h-56 overflow-y-auto overscroll-contain`,children:A.map(e=>{let t=y.trim();return Z(`div`,{children:Z(`button`,{type:`button`,className:`w-full text-left px-4 py-3 text-sm flex items-center justify-between cursor-pointer transition-colors rounded-xl ${t&&(bn(t)||ut(t))&&at(e.address,t)?`bg-gray-100 dark:bg-gray-700`:`trails-text-primary trails-hover-bg`}`,onClick:()=>ae(e),"aria-label":`Select recipient ${e.ensName||e.address}`,children:Q(`div`,{className:`flex items-center gap-3`,children:[Z(GE,{address:e.address,size:28,useEnsAvatar:!0}),Q(`div`,{className:`text-left`,children:[Q(`div`,{className:`flex items-center space-x-1`,children:[Z(`span`,{className:`text-sm font-medium`,children:wt(e.address,6,4)}),Z(U,{text:e.address,stopPropagation:!0,className:`p-0.5 z-10 relative`,size:`sm`,as:`span`})]}),e.ensName&&Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:e.ensName})]})]})})},e.address)})})]})]})]})},tO=({quoteError:t})=>!t||!e(t)?null:Z(`div`,{className:`mb-2 p-3 rounded-lg bg-red-50 border border-red-200 dark:bg-red-900/20 dark:border-red-800`,children:Q(`div`,{className:`flex items-start gap-2`,children:[Z(`svg`,{className:`w-4 h-4 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5`,fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z`})}),Q(`div`,{className:`flex-1 min-w-0`,children:[Z(`p`,{className:`text-xs font-medium text-red-700 dark:text-red-300`,children:`Quote Unavailable — High Price Impact`}),Z(`p`,{className:`text-xs text-red-600 dark:text-red-400 mt-0.5`,children:`This transfer has a price impact over 30% on an amount over $100. Try a smaller amount or a different route.`})]})]})}),nO=({quoteError:e})=>!e||!S(e)?null:Z(`div`,{className:`mb-2 p-3 rounded-lg bg-amber-50 border border-amber-200 dark:bg-amber-900/20 dark:border-amber-800`,children:Q(`div`,{className:`flex items-start gap-2`,children:[Z(ea,{className:`w-4 h-4 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5`}),Q(`div`,{className:`flex-1 min-w-0`,children:[Z(`p`,{className:`text-xs font-medium text-amber-800 dark:text-amber-200`,children:`Amount too low for this route`}),Z(`p`,{className:`text-xs text-amber-700 dark:text-amber-300 mt-0.5`,children:`Network and execution fees exceed your swap amount. Try a higher amount or another token.`})]})]})});function rO({token:e,ownerBase58:t}){return ev(e,t,{withPrices:!0}),null}function iO(){let e=Nt(101),t=qu()?.publicKey?.toBase58?.()??null,n=e?.getOriginTokens()??[];return!t||n.length===0?null:Z(hi,{children:n.map(e=>Z(rO,{token:e,ownerBase58:t},e.contractAddress))})}const aO=({selectedToken:e,onSend:t,onBack:n,onConfirm:r,onComplete:i,account:o,toRecipient:l,toAmount:u,toChainId:d,toToken:f,toCalldata:p,walletClient:m,onTransactionStateChange:h,onError:g,onWaitingForWalletConfirm:_,onWaitingForOnrampConfirm:v,setWalletConfirmRetryHandler:y,swapProvider:b,bridgeProvider:x,swapProviderFallback:S,bridgeProviderFallback:C,fundMethod:w,onAmountUpdate:E,checkoutOnHandlers:D,recentTokens:O,onTrackToken:k,title:A=`Swap`,isSequenceWallet:j=!1,exactInputOnly:M=!1})=>{let{fundOptions:N,fromToken:P,fromChainId:F,supportedChains:I,supportedTokensByChain:ee}=wo(),te=To({fromToken:P,fromChainId:F}),{mode:ne,navigate:re}=y_(),{isBalanceVisible:ie}=vu(),{selectedToken:L,setSelectedToken:R,hasManualSelection:ae,setHasManualSelection:z}=ul(),{selectedToken:B,setSelectedToken:V,hasManualSelection:oe,setHasManualSelection:H,isControlledByProps:se,availableDestinationTokens:ce,availableDestinationTokenKeys:U,availableDestinationTokenRestrictedChainIds:le,availableDestinationChainIds:ue}=xl(),{destinationEdgePlugin:de,isEdgeDestinationSupported:fe,destinationChainIds:pe,destinationChainList:me,destinationChainListExtras:he,destinationCatalogSupplementTokens:ge}=rD(ue),{selectedRecipient:_e,setSelectedRecipient:ye}=cu(),be=qu(),{selectedCurrency:xe,setSelectedCurrency:Se,hasManualSelection:Ce,setHasManualSelection:we,fiatAmount:Te,setFiatAmount:Ee}=wl(),[De,Oe]=X(!1),[ke,Ae]=X(!1),[je,Me]=X(null),[Ne,Fe]=X(!1),[Ie,Le]=X(null),Re=w===`onramp-meld`,ze=Il(w),{countryCode:Be,defaultCurrencyCode:Ve,isLoading:He}=Vw({enabled:Re}),Ue=je||Be,{fiatCurrencies:We,isLoading:Ge}=kE({countryCode:Ue||`US`,enabled:Re&&!!Ue});q(()=>{if(Re&&!xe&&We.length>0&&!He&&!Ge&&!Ce){let e=Ve||`USD`,t=We.find(t=>t.currencyCode===e);t&&(s.console.log(`[ClassicSwap] Auto-selecting default currency:`,t,Ve?`(detected)`:`(fallback to USD)`),Se(t))}},[Re,xe,Ve,We,He,Ge,Ce,Se]);let Ke=Y(null);q(()=>{Re||(Ke.current=null)},[Re]),q(()=>{if(!Re||Ge||We.length===0)return;let e=N?.fiatCurrency?.trim()||``,t=N?.fiatAmount?.trim()||``,n=`${e.toUpperCase()}|${t}`;if(Ke.current!==n){if(Ke.current=n,e){let t=We.find(t=>t.currencyCode.toUpperCase()===e.toUpperCase());t&&(Se(t),we(!0))}t&&Ee(t)}},[Re,Ge,We,N?.fiatCurrency,N?.fiatAmount,Se,we,Ee]);let qe=N?.fiatCurrency?.trim().toUpperCase()||null,Je=!!qe&&!!xe&&xe.currencyCode.toUpperCase()===qe,Ye=Re&&Je,Xe=Re&&!!N?.fiatAmount,Ze=Y({hasManualDestinationSelection:!1,lastOriginSelectionTime:0,lastDestinationSelectionTime:0}),{defaultOriginToken:Qe,isLoading:$e}=XT(),{defaultDestinationToken:et,isLoading:tt}=OE(L),[nt,rt]=X(e?.chainId||L?.chainId);q(()=>{let e=L?.chainId;e!=null&&nt!==e?rt(e):e==null&&nt!=null&&rt(null)},[nt,L?.chainId]);let{tradeType:it,setTradeType:at,sellAmount:ot,setSellAmount:st,buyAmount:ct,setBuyAmount:lt,resetSwapState:dt,enterFormMode:G}=d_();q(()=>{G(`swap`)},[]);let ft=it||ln.EXACT_INPUT,pt=W(L?.chainId??0),mt=W(B?.chainId??0),ht=QE({fundMethod:w,allowedChainIds:null,disabledChains:J(()=>mt?[101]:void 0,[mt])}),gt=J(()=>ZE({recipient:_e,allowedChainIds:pe,disabledChains:pt?[101]:void 0}),[_e,pe,pt]),[_t,vt]=X(B?.chainId??null),[yt,bt]=X(L?.chainId??null),xt=J(()=>be&&(!w||w===`wallet`)?[Ra]:void 0,[w,be]);q(()=>{mt&&(pt||_e||!be?.connected||!be.publicKey||ye(be.publicKey.toBase58()))},[mt,pt,_e,ye,be?.connected,be?.publicKey]);let[St,Ct]=X(!1),[wt,Tt]=X(null),Et=K(e=>{Ee(``),dt(),i(e)},[i,dt,Ee]);q(()=>{s.console.log(`[trails-sdk] ClassicSwap toRecipient prop effect:`,{toRecipient:l,selectedRecipient:_e,accountAddress:o?.address}),l&&(s.console.log(`[trails-sdk] ClassicSwap Setting selectedRecipient to toRecipient:`,l),ye(l))},[l,ye]);let Dt=mt?_e||l||void 0:_e||l||o?.address,Ot=be?.connected?be.publicKey?.toBase58?.()??null:null,kt=K(e=>{let t=XE({destinationChainId:e.chainId,originChainId:L?.chainId,selectedRecipient:_e,connectedSolanaAddress:Ot,evmFallbackAddress:l&&bn(l)?l:o?.address});t!==void 0&&t!==_e&&ye(t)},[o?.address,L?.chainId,_e,ye,Ot,l]),At=!!(Dt&&!Pe(Dt,o?.address)&&!(Ot&&ut(Dt)&&Dt.trim()===Ot.trim()))||!!f||I!=null||ee!=null||!!P,jt=Re?`onramp-meld`:w,Mt=jt===`onramp-meld`||jt===`direct-transfer`||jt===`onramp-mesh`,Nt=ZT(L,o?.address),Pt=ZT(B,o?.address),{quotes:Ft,selectedQuote:It,isLoading:Lt,error:Rt,onrampTrackingData:zt}=jE({amount:Te,sourceCurrencyCode:xe?.currencyCode,destinationCurrencyCode:`USDC_BASE`,countryCode:Ue||void 0,walletAddress:o?.address||``,enabled:Re&&!!Te&&!!xe&&!!Ue&&!!Dt}),{amount:Bt,amountRaw:Vt,amountUsdDisplay:Ht,amountUsdLocaleDisplay:Ut,balanceFormatted:Wt,balanceRaw:Gt,tokenDecimals:Kt,handleSubmit:qt,isSubmitting:Jt,isLoadingQuote:Yt,selectedDestinationChain:Xt,selectedDestToken:Zt,setSelectedDestinationChain:Qt,setSelectedDestToken:$t,buttonText:en,toAmountDisplay:tn,destinationTokenAddress:nn,isValidCustomToken:rn,prepareSendQuote:an,quoteError:on,isOriginFundingWalletMismatch:sn,processedFeeOptions:cn,selectedFeeOption:un,setSelectedFeeOption:dn,sendFn:fn}=nE({account:o,toAmount:ft===ln.EXACT_OUTPUT?ct:u,fromAmount:ft===ln.EXACT_INPUT?ot:void 0,toRecipient:Dt,toChainId:d,toToken:f,toCalldata:p,walletClient:m,onTransactionStateChange:h,onError:g,onWaitingForWalletConfirm:_,onWaitingForOnrampConfirm:v,onSend:t,onConfirm:r,onComplete:Et,selectedToken:L??void 0,setWalletConfirmRetryHandler:y,tradeType:ft,swapProvider:b,bridgeProvider:x,swapProviderFallback:S,bridgeProviderFallback:C,fundMethod:jt,mode:ne,checkoutOnHandlers:D,onrampTrackingData:Re?zt:null,skipFeeBalanceFetch:jt===`onramp-meld`||jt===`direct-transfer`||jt===`onramp-mesh`}),pn=J(()=>de?.getDestinationTokens?.()[0]??null,[de]);nD({modeLabel:`Swap`,selectedRecipient:_e,destinationToken:B,originChainId:L?.chainId,defaultSolanaToken:pn,defaultEvmDestinationToken:et,availableDestinationTokens:ce,setDestinationToken:V,setSelectedDestToken:$t,setSelectedDestinationChain:Qt,setHasManualDestinationSelection:H,setDestinationChainFilterId:vt}),jd({fundMethod:w,setOriginChainId:rt,setSourceChainFilterId:bt}),q(()=>{if(!pt||!mt||f&&d||!et||W(et.chainId??0))return;V(et),$t(et),vt(et.chainId??null);let e=$(et.chainId);e&&Qt(e),H(!1),Ze.current.hasManualDestinationSelection=!1},[et,mt,pt,V,H,$t,Qt,d,f]);let mn=Ie||It,{exchangeRate:hn,isLoading:gn}=Pu({fromCurrency:`USD`,toCurrency:mn?.sourceCurrencyCode||`USD`,disabled:!mn||mn?.sourceCurrencyCode===`USD`}),{createWidgetSession:_n,isLoading:vn,error:yn}=AE();q(()=>{if(Re){let e=c;s.console.log(`[ClassicSwap] Setting origin token to USDC on Base:`,e),R(e),rt(Mn.id),at(ln.EXACT_INPUT)}},[Re,R,at]);let{token:xn}=ev(B,Pt,{disabled:Mt}),{token:Sn,isLoadingBalance:Cn}=ev(L,Nt,{disabled:Mt,withPrices:!0}),wn=Rl({originToken:Sn??L,originTokenBalance:Sn?.balance??L?.balance,originTokenAmount:ot,isLoadingBalance:Cn}),Tn=!!un&&!!wn&&Bl(un,wn),En=J(()=>{if(!xn)return`0.00`;try{return Xs(xn.balance||`0`,xn.decimals??18)}catch(e){return s.console.error(`[trails-sdk] balance format failed`,e),`0.00`}},[xn]),Dn=K(e=>{Tt(null),Ee(e)},[Ee]),On=K(e=>{let t=e;e.length>1&&e.startsWith(`0`)&&e[1]!==`.`&&(t=e.replace(/^0+/,``)||`0`),at(ln.EXACT_INPUT),st(t)},[at,st]),kn=K(()=>{ft===ln.EXACT_OUTPUT&&an?.originAmountDisplay&&!ot&&st(an.originAmountDisplay)},[ft,an?.originAmountDisplay,ot,st]),An=K(e=>{if(Re||M)return;let t=e;e.length>1&&e.startsWith(`0`)&&e[1]!==`.`&&(t=e.replace(/^0+/,``)||`0`),at(ln.EXACT_OUTPUT),lt(t)},[Re,M,at,lt]),jn=K(()=>{Re||M||ft===ln.EXACT_INPUT&&tn&&!ct&&lt(tn)},[ft,tn,ct,Re,M,lt]);q(()=>{if(Re&&mn&&L?.contractAddress){let e=Number(mn.destinationAmount),t=Math.max(0,e-.25);s.console.log(`[trails-sdk] Adjusting onramp amount for fees:`,{originalAmount:e,adjustedAmount:t,feeSubtracted:.25}),st(t.toString()),at(ln.EXACT_INPUT)}},[Re,mn,L,st,at]),q(()=>{an&&(ft===ln.EXACT_OUTPUT&&an.originAmountDisplay?st(an.originAmountDisplay):ft===ln.EXACT_INPUT&&an.destinationAmountDisplay&&lt(an.destinationAmountDisplay))},[an,ft,st,lt]),q(()=>{E&&E(Vt)},[Vt,E]),q(()=>{ae&&!L&&!$e&&(s.console.log(`[trails-sdk] Resetting hasManualOriginSelection - token was cleared`),z(!1))},[ae,L,$e,z]),q(()=>{if(te||$e||!Qe||ae)return;let e=!!L&&Ad(L)&&!ws(L)&&ws(Qe);(!L||e)&&(s.console.log(`[trails-sdk] Auto-selecting origin token:`,Qe),R(Qe,{manual:!1}),rt(Qe.chainId))},[L,$e,Qe,R,ae,te]),q(()=>{let e=ae||ve(Ze.current.lastOriginSelectionTime,1e3),t=Ze.current.hasManualDestinationSelection||oe||ve(Ze.current.lastDestinationSelectionTime,1e3);if(!(f&&d)&&!B&&!tt&&et&&!t&&!e){s.console.log(`[trails-sdk] Auto-selecting destination token:`,et),V(et),$t(et);let e=$(et.chainId);e&&Qt(e)}},[B,tt,et,oe,ae,V,$t,Qt,f,d]),q(()=>{Nn.current&&Nn.current.focus()},[]);let Nn=Y(null),[Pn,Fn]=X(!1),[In,Ln]=X(!1),Rn=K(()=>{bt(L?.chainId??null),Fn(!0)},[L?.chainId]),zn=K(()=>{vt(Zt?.chainId??B?.chainId??null),Ln(!0)},[B?.chainId,Zt?.chainId]),[Bn,Vn]=X(!1),[Hn,Un]=X(!1);q(()=>{f&&d||B&&(s.console.log(`[trails-sdk] Syncing destination token to useSendForm:`,B),$t(B))},[B,$t,f,d]),q(()=>{if(!se||!Zt||!f)return;let e=Zt.chainId===Number(d),t=Zt.contractAddress?.toLowerCase()===f.toLowerCase()||Zt.symbol?.toLowerCase()===f.toLowerCase();e&&t&&(B&&B.chainId===Zt.chainId&&B.contractAddress?.toLowerCase()===Zt.contractAddress?.toLowerCase()||(s.console.log(`[trails-sdk] ClassicSwap: Syncing resolved token from useSendForm to global provider:`,Zt.symbol),V(Zt)))},[se,Zt,B,V,f,d]);let Wn=K(()=>{if(!Xt||!L||!Zt)return!1;Oe(!De);let e=L,t=nt,n=ct||tn||``,r=ot||Bt||``;R(Zt),V(e),rt(Zt?.chainId),$t(e),vt(t??null),bt(Zt?.chainId??null);let i=$(t??void 0);return i&&Qt(i),(ae||oe)&&(z(!0),H(!0)),M?(st(r),lt(``),at(ln.EXACT_INPUT)):ft===ln.EXACT_INPUT?(lt(r),st(``),at(ln.EXACT_OUTPUT)):(st(n),lt(``),at(ln.EXACT_INPUT)),!0},[L,Xt,Zt,nt,R,V,$t,Qt,De,ae,oe,z,H,M,ft,tn,ot,ct,Bt,st,lt,at]),Gn=K(()=>{At||pt||Wn()},[Wn,At,pt]),Kn=K(e=>{if(e.contractAddress===B?.contractAddress&&e.chainId===B?.chainId){Gn(),Fn(!1);return}if(W(e.chainId??0)&&W(B?.chainId??Zt?.chainId??0)){if(!Wn()){s.console.warn(`[trails-sdk] Solana-to-Solana swaps are not supported; ignoring origin token selection`,e);return}R(e),rt(e.chainId),Fn(!1),z(!0),H(!0),Ze.current.lastOriginSelectionTime=Date.now(),Ze.current.hasManualDestinationSelection=!0,k?.(e),s.console.log(`[trails-sdk] Solana on both sides — flipped and set origin token`,e);return}(!L||L.symbol!==e.symbol)&&(st(``),lt(``),at(ln.EXACT_INPUT)),R(e),rt(e.chainId),Fn(!1),z(!0),Ze.current.lastOriginSelectionTime=Date.now(),k?.(e),s.console.log(`[trails-sdk] selected origin token`,e)},[Wn,R,z,H,k,L,Gn,B,Zt?.chainId,st,lt,at]),qn=K(e=>{if(e.contractAddress===L?.contractAddress&&e.chainId===L?.chainId){Gn(),Ln(!1);return}if(kt(e),W(e.chainId??0)&&W(L?.chainId??0)){if(!Wn()){s.console.warn(`[trails-sdk] Solana-to-Solana swaps are not supported; ignoring destination token selection`,e);return}V(e),$t(e);let t=$(e.chainId);t&&Qt(t),vt(e.chainId??null),Ln(!1),z(!0),H(!0),Ze.current.hasManualDestinationSelection=!0,Ze.current.lastDestinationSelectionTime=Date.now(),k?.(e),s.console.log(`[trails-sdk] Solana on both sides — flipped and set destination token`,e);return}V(e),$t(e),vt(e.chainId??null);let t=$(e.chainId);t&&Qt(t),Ln(!1),H(!0),Ze.current.hasManualDestinationSelection=!0,Ze.current.lastDestinationSelectionTime=Date.now(),k?.(e),s.console.log(`[trails-sdk] selected destination token`,e)},[Wn,V,$t,Qt,z,H,k,L,Gn,kt]),Jn=K(e=>{bt(e),Vn(!1),Fn(!0)},[]),Yn=K(e=>{vt(e),Un(!1),Ln(!0),e!=null&&W(e)&&W(L?.chainId??0)&&L&&B&&(Wn(),z(!0),H(!0))},[Wn,B,L,H,z]),Xn=K(e=>{e.contractAddress===L?.contractAddress&&e.chainId===L?.chainId&&Gn(),Pn?Kn(e):In&&qn(e)},[Pn,In,Kn,qn,L?.contractAddress,L?.chainId,Gn]);return Ne?Z(Nw,{onBack:()=>Fe(!1),onSelectProvider:e=>{Le(e),Fe(!1)},selectedProvider:mn,providers:Ft,isLoading:Lt}):ke?Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>Ae(!1),headerContent:`Select Currency`,headerContentAlign:`left`}),Z(FE,{onCurrencySelect:e=>{Se(e),Ae(!1),we(!0)},onAutoSelect:e=>{Se(e)},onSelectCountry:e=>{Me(e)},onError:g,selectedCurrency:xe})]}):Bn?Z(cb,{extraChains:xt,disabledChains:ht.disabledChains,onChainSelect:Jn,onBack:()=>{Vn(!1),Fn(!0)}}):Pn?Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>Fn(!1),headerContent:`Select From Token`,headerContentAlign:`left`,customActions:pt?void 0:Z(lb,{onError:g,fundMethod:w})}),Z(ib,{onTokenSelect:Kn,onError:g,showContinueButton:!1,compactMode:!1,allSupportedTokens:!1,fundMethod:w??`wallet`,allowedChainIds:ht.allowedChainIds,disabledChains:ht.disabledChains,chainFilterChainId:yt,onChainFilterChange:bt,includeSolanaChainFilter:!!de||!!be,chainListScreen:!0,onNavigateToChainList:()=>{Fn(!1),Vn(!0)},recentTokens:O,onRecentTokenSelect:Xn})]}):Hn?Z(cb,{chains:me,extraChains:he,disabledChains:gt.disabledChains,onChainSelect:Yn,onBack:()=>{Un(!1),Ln(!0)}}):In?Q(`div`,{className:`space-y-2`,children:[Z(M_,{onBack:()=>Ln(!1),headerContent:`Select destination token`,headerContentAlign:`left`,customActions:mt?void 0:Z(lb,{onError:g,fundMethod:w,allSupportedTokens:!0,accountAddress:Dt})}),Z(ib,{onTokenSelect:qn,onError:g,allowedTokens:ce,allowedTokenKeys:U,allowedTokenRestrictedChainIds:le,allowedChainIds:gt.allowedChainIds,catalogSupplementTokens:ge,showContinueButton:!1,compactMode:!1,allSupportedTokens:!0,accountAddress:Dt,accountHeaderLabel:`Receiver`,fundMethod:w,disabledChains:gt.disabledChains,chainFilterChainId:_t,onChainFilterChange:vt,includeSolanaChainFilter:fe,chainListScreen:!0,onNavigateToChainList:()=>{Ln(!1),Un(!0)},recentTokens:O,onRecentTokenSelect:Xn})]}):Q(`div`,{className:`space-y-2`,children:[pt&&Z(iO,{}),Z(M_,{onBack:ne===`fund`?()=>re(`fund-form`):ne===`earn`?()=>re(`earn`):ne===`pay`?()=>re(`send-form`):ne===`withdraw`?()=>re(`withdraw`):n,headerContent:A,headerContentAlign:`left`,showAccountActions:!0}),Q(`form`,{onSubmit:async e=>{if(e.preventDefault(),s.console.log(`[trails-sdk] Creating widget session`,Re),Re&&mn&&xe){let{popup:t,blocked:n,error:r}=Uw(`meld-widget`,450,700);if(n){Tt(r||`Popup blocked. Please allow popups for this site.`),g(r||`Popup blocked`);return}try{if(Ct(!0),Tt(null),s.console.log(`[trails-sdk] prepareSendQuote`,an),fn){s.console.log(`[trails-sdk] Committing intent for onramp-meld flow`);try{await fn({selectedFeeOption:un??null}),s.console.log(`[trails-sdk] Intent committed for onramp-meld`)}catch(e){s.console.error(`[trails-sdk] Failed to commit intent:`,e)}}let n=await _n({depositAddress:an?.originDepositAddress||``,userAddress:o?.address||``,countryCode:Ue||``,sourceCurrencyCode:xe.currencyCode,sourceAmount:Te,destinationCurrencyCode:`USDC_BASE`,serviceProvider:mn.serviceProvider,paymentMethodType:mn.paymentMethodType,lockFields:[`cryptoCurrency`,`destinationCurrencyCode`,`sourceCurrencyCode`,`walletAddress`]});s.console.log(`[ClassicSwap] Widget session response:`,n);let{widgetUrl:r,id:i,externalSessionId:a}=n;if(Tf({sessionId:zt?.sessionId||a,provider:mn?.serviceProvider||`Meld`,widgetUrl:r,depositAddress:an?.originDepositAddress||``,userAddress:o?.address?.toLowerCase()||``,countryCode:Ue||``,sourceCurrencyCode:xe?.currencyCode||``,sourceAmount:Te,destinationCurrencyCode:`USDC_BASE`,paymentMethodType:mn?.paymentMethodType||``}),!Ww(t,r))throw Error(`Payment window was closed. Please try again.`);s.console.log(`[ClassicSwap] Opened onramp widget in popup`,{widgetUrl:r,meldTransactionId:i}),v&&an&&(s.console.log(`[ClassicSwap] Calling onWaitingForOnrampConfirm with externalSessionId:`,a),v(an,mn,{depositAddress:an?.originDepositAddress||``,userAddress:o?.address?.toLowerCase()||``,countryCode:Ue||``,sourceCurrencyCode:xe.currencyCode,sourceAmount:Te,destinationCurrencyCode:`USDC_BASE`,serviceProvider:mn.serviceProvider,paymentMethodType:mn.paymentMethodType},a,t)),await qt(e)}catch(e){Gw(t),s.console.error(`[ClassicSwap] Error creating widget session`,e);let n=a(e)||`Failed to create widget session`;Tt(n),g(n)}finally{Ct(!1)}return}s.console.log(`[trails-sdk] Calling handleSubmit from ClassicSwap`),qt(e)},className:`space-y-1`,children:[Q(`div`,{className:`pt-4 pb-4 trails-bg-secondary trails-bg-secondary-hover trails-border-radius-container p-3 group transition-all duration-200 border border-transparent focus-within:bg-white! dark:focus-within:bg-gray-800! trails-focus-border-secondary min-h-[120px] flex flex-col`,children:[Q(`div`,{className:`mb-4 flex justify-between items-center`,children:[Z(`div`,{className:`text-sm font-medium trails-text-secondary text-left m-0`,children:ne===`fund`?`Payment method`:`Sell`}),Z(hE,{})]}),Q(`div`,{className:`flex items-center space-x-2 flex-1`,children:[Z(`div`,{className:`flex-1`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Z(pb,{ref:Nn,value:Re?Te:ot,disabled:Xe,onChange:e=>{Re?Dn(e.target.value):On(e.target.value)},onFocus:kn,isLoading:Yt&&ft===ln.EXACT_OUTPUT,variant:`default`}),Yt&&ft===ln.EXACT_OUTPUT&&Z(Tw,{})]})}),Z(`div`,{className:`relative`,children:Re?Z(IE,{currency:xe,onSelect:()=>Ae(!0),unselectable:Ye}):Z(gE,{token:L,chainId:nt,onSelect:Rn})})]}),Q(`div`,{className:`mt-4 flex justify-between items-center`,children:[Re&&mn&&hn&&mn&&!gn?(()=>{let e=mn.sourceCurrencyCode===`USD`?mn.sourceAmount:mn.sourceAmount/hn;return Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,title:Ks(e||0),children:Q(`span`,{className:`notranslate`,translate:`no`,children:[`≈ `,qs(e||0)]})})})():Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:Q(`span`,{className:`notranslate`,translate:`no`,children:[`≈`,` `,ft===ln.EXACT_INPUT?an?.originAmountUsdLocaleDisplay||Ut||Ht||qs(0):Yt?``:an?.originAmountUsdLocaleDisplay||an?.originAmountUsdDisplay||``]})}),L&&!Re&&ze&&Q(`div`,{className:`flex items-center space-x-2`,children:[Q(`div`,{className:`flex items-center space-x-1`,children:[Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400 notranslate`,translate:`no`,children:`Balance:`}),Z(`button`,{type:`button`,className:`text-xs text-gray-500 dark:text-gray-400 cursor-pointer hover:text-gray-700 dark:hover:text-gray-200 transition-colors bg-transparent border-none p-0`,onClick:()=>{if(Wt){let e=parseFloat(Wt);_s(e)&&(at(ln.EXACT_INPUT),st(e.toFixed(6)),lt(``))}},onKeyDown:e=>{if((e.key===`Enter`||e.key===` `)&&(e.preventDefault(),Wt)){let e=parseFloat(Wt);_s(e)&&(at(ln.EXACT_INPUT),st(e.toFixed(6)),lt(``))}},title:`Click to use full balance`,disabled:!Wt,children:Z(`span`,{className:`notranslate`,translate:`no`,children:ie?Sn?.balanceLocaleDisplay||L?.balanceLocaleDisplay||Sn?.balanceDisplay||L?.balanceDisplay||Wt||`0.00`:`••••••`})})]}),Wt&&Z(vT,{userBalance:Wt,userBalanceRaw:Gt,decimals:Kt,isNativeToken:L.isNativeToken??!1,gasCostFormatted:an?.gasCostFormatted,chainId:nt||void 0,onAmountSelect:e=>{at(ln.EXACT_INPUT),st(e),lt(``)},className:`opacity-100`})]})]})]}),Z(`div`,{className:`relative`,children:Z(`button`,{type:`button`,onClick:Gn,disabled:At,className:`absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 p-1.5 trails-border-radius-button trails-bg-tertiary hover:trails-hover-bg transition-colors border-2 border-white dark:border-gray-800 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:trails-bg-tertiary ${pt?`cursor-default`:`cursor-pointer`}`,children:Z(yi,{className:`w-5 h-5 text-gray-900 dark:text-white`,strokeWidth:2.5})})}),Q(`div`,{className:`pt-4 pb-4 trails-bg-secondary trails-bg-secondary-hover trails-border-radius-container p-3 transition-all duration-200 border border-transparent focus-within:bg-white! dark:focus-within:bg-gray-800! trails-focus-border-secondary min-h-[120px] flex flex-col mb-4`,children:[Q(`div`,{className:`mb-4 flex justify-between items-center mb-2`,children:[Z(`div`,{className:`text-sm font-medium trails-text-secondary text-left m-0`,children:ne===`fund`?`Recipient`:`Buy`}),l?Q(`div`,{className:`flex items-center space-x-2 text-black dark:text-white`,children:[Z(Wy,{walletAddress:l}),Z(cw,{address:l,startChars:4,endChars:4,className:`text-sm font-medium`})]}):Z(KE,{selectedRecipient:_e,showChainBadge:!1})]}),Q(`div`,{className:`flex items-center space-x-2 flex-1`,children:[Z(`div`,{className:`flex-1`,children:Q(`div`,{className:`flex items-center space-x-2`,children:[Z(pb,{value:ft===ln.EXACT_OUTPUT?ct:ct||tn||``,onChange:M?void 0:e=>An(e.target.value),onFocus:M?void 0:jn,isLoading:Yt&&ft===ln.EXACT_INPUT,readOnly:Re||M||ft===ln.EXACT_INPUT&&Yt||!!u,disabled:M,showPlaceholderStyle:!Bt,variant:`default`}),Yt&&ft===ln.EXACT_INPUT&&Z(Tw,{})]})}),Z(`div`,{className:`relative`,children:Z(gE,{token:Zt,chainId:Zt?.chainId,onSelect:zn,unselectable:!!f})})]}),Q(`div`,{className:`mt-4 flex items-center justify-between`,children:[Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:(an?.destinationAmountUsdDisplay||ft===ln.EXACT_OUTPUT&&(Ut||Ht)||Yt&&ft===ln.EXACT_INPUT)&&Q(`span`,{className:`notranslate`,translate:`no`,children:[`≈`,` `,Yt&&ft===ln.EXACT_INPUT?qs(0):an?.destinationAmountUsdLocaleDisplay||an?.destinationAmountUsdDisplay||Ut||Ht]})}),B&&Z(`div`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:Q(`span`,{className:`notranslate`,translate:`no`,children:[`Balance:`,` `,ie?xn?.balanceLocaleDisplay||B?.balanceLocaleDisplay||xn?.balanceDisplay||B?.balanceDisplay||En||`-`:`••••••`]})})]})]}),Z(JE,{fundMethod:w,isSenderContractOnOrigin:!1,isSenderContractOnDestination:!1,isSequenceWallet:j}),an&&Z(`div`,{children:Z(wb,{quote:an,fiatToUsdExchangeRate:hn,onRampQuote:mn,showContent:!0,swapMode:!0,isRefetching:Yt,isPassthrough:jg(an.passthroughEligible,un,cn)})}),Z(aD,{active:sn}),Z(tO,{quoteError:on}),Z(nO,{quoteError:on}),Re&&!Lt&&!Yt&&an&&Ft&&Ft.length>0&&Z(LE,{providers:Ft,selectedProvider:mn,trailsQuote:an,setSelectedProvider:e=>{Le(e)},isRefetching:Lt}),Re&&Rt&&Z(`div`,{className:`mt-4`,children:Z(XC,{errorPrettified:T(Rt,`Error loading quote`),error:a(Rt),severity:`error`})}),!Re&&!pt&&ze&&Z(mE,{processedFeeOptions:cn||[],selectedFeeOption:un,setSelectedFeeOption:dn,chainId:L?.chainId,isRefetching:Yt,originTokenInfo:wn}),Z(`button`,{type:`submit`,disabled:Re?!ot||Jt||St||!xe||!Zt||!Ue||!Dt||Lt||vn||!mn||!!Rt||!!yn||Yt||!an:!Bt||Jt||!nn||!rn||Yt||!an||!Re&&ze&&an?.noSufficientBalance||ze&&Tn,className:`w-full font-semibold py-4 px-4 trails-border-radius-button transition-colors bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white disabled:text-gray-500 disabled:cursor-not-allowed cursor-pointer relative`,children:Jt||St||vn?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Hi,{className:`w-5 h-5 animate-spin mr-2 trails-text-muted`}),Z(`span`,{children:St||vn?`Creating session...`:en})]}):Re&&!an&&!mn&&(Rt||yn||wt)?`Error Loading Quote`:ze&&an?.noSufficientBalance?`Insufficient Balance`:Re&&(Lt||Yt)&&!an&&!It&&!Ft?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:`Getting quote...`})]}):Re&&an?`Continue`:en===`Getting quote...`?Q(`div`,{className:`flex items-center justify-center`,children:[Z(Tw,{className:`mr-2`}),Z(`span`,{children:en})]}):en})]})]})},oO=e=>Z(aO,{...e}),sO=()=>{let{selectedTheme:e}=Su(),{customCss:t,theme:n}=wo();return q(()=>{if(!t){let t=setTimeout(()=>{let t=e||n||`auto`;s.console.log(`[ThemeSyncer] Applying theme - User preference:`,e,`Widget theme:`,n,`Final theme:`,t);let r=new CustomEvent(`applyThemePreference`,{detail:{theme:t}});window.dispatchEvent(r)},0);return()=>clearTimeout(t)}},[e,t,n]),null},cO=({onBack:e})=>{let{isBalanceVisible:t,toggleBalanceVisible:n,resetBalanceVisible:r}=vu(),{selectedTheme:i,setSelectedTheme:a,resetThemePreference:o}=Su(),{selectedLocale:c,setSelectedLocale:l,resetLocalePreference:u,getEffectiveLocale:d}=ku(),{selectedCurrency:f,setSelectedCurrency:p,resetCurrencyPreference:m,getEffectiveCurrency:h}=Ru(),{customCss:g,theme:_}=wo(),[v,y]=X(!1),[b,x]=X(!1),[S,C]=X(``),[w,T]=X(``),E=Y(null),D=Y(null),O=Y(null),k=Y(null),{trackClick:A}=k_(),j=e=>{g||(A({component:`UserPreferences`,action:`change_theme`,label:e,metadata:{previousTheme:i,newTheme:e}}),a(e))};q(()=>{function e(e){E.current&&!E.current.contains(e.target)&&(y(!1),C(``))}if(v)return setTimeout(()=>{O.current?.focus()},10),setTimeout(()=>{document.addEventListener(`click`,e)},0),()=>{document.removeEventListener(`click`,e)}},[v]),q(()=>{function e(e){D.current&&!D.current.contains(e.target)&&(x(!1),T(``))}if(b)return setTimeout(()=>{k.current?.focus()},10),setTimeout(()=>{document.addEventListener(`click`,e)},0),()=>{document.removeEventListener(`click`,e)}},[b]);let M=()=>{try{r(),o(),u(),m(),s.console.log(`[UserPreferences] All preferences have been reset to defaults`)}catch(e){s.console.warn(`[UserPreferences] Failed to reset preferences:`,e)}},N=d();Tu.find(e=>e.code===N)||Tu[0],Tu.filter(e=>e.name.toLowerCase().includes(S.toLowerCase())||e.code.toLowerCase().includes(S.toLowerCase()));let{data:P=[]}=Nu(),F=h(),I=P.find(e=>e.code===F)||P.find(e=>e.code===`USD`)||{code:`USD`,symbol:`$`,name:`US Dollar`,flag:`🇺🇸`,decimals:2},ee=P.filter(e=>e.name.toLowerCase().includes(w.toLowerCase())||e.code.toLowerCase().includes(w.toLowerCase())||e.symbol.toLowerCase().includes(w.toLowerCase()));return Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{headerContent:`User Preferences`,headerContentAlign:`left`,onBack:e}),Q(`div`,{className:`space-y-6`,children:[Z(`div`,{children:Z(Mf,{})}),Q(`div`,{className:`flex items-center justify-between`,children:[Q(`span`,{className:`text-sm font-medium ${g?`text-gray-500 dark:text-gray-500`:`text-gray-900 dark:text-gray-100`}`,children:[`Theme`,g&&Z(`span`,{className:`text-xs text-gray-400 dark:text-gray-500 block`,children:`Controlled by custom CSS`})]}),Q(`div`,{className:`flex items-center gap-2`,children:[Q(`button`,{type:`button`,onClick:()=>j(`light`),disabled:!!g,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${i===`light`||!i&&_===`light`||!i&&!_&&typeof window<`u`&&!window.matchMedia(`(prefers-color-scheme: dark)`).matches?`bg-[#DBEAFE] text-[#2563EB]`:`bg-transparent text-gray-900 dark:text-gray-100 hover:text-gray-700 dark:hover:text-gray-300`} ${g?`cursor-not-allowed opacity-50`:`cursor-pointer`}`,children:[Q(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[Z(`title`,{children:`Light Mode`}),Z(`g`,{clipPath:`url(#clip0_light_icon)`,children:Z(`path`,{d:`M7.33335 14.6665V13.3332C7.33335 12.965 7.63183 12.6665 8.00002 12.6665C8.36821 12.6665 8.66669 12.965 8.66669 13.3332V14.6665C8.66669 15.0347 8.36821 15.3332 8.00002 15.3332C7.63183 15.3332 7.33335 15.0347 7.33335 14.6665ZM3.75523 11.3019C4.01558 11.0416 4.43759 11.0416 4.69794 11.3019C4.95823 11.5623 4.95827 11.9843 4.69794 12.2446L3.75783 13.1847C3.49748 13.4449 3.07541 13.445 2.81512 13.1847C2.55485 12.9245 2.55499 12.5024 2.81512 12.242L3.75523 11.3019ZM11.3021 11.3019C11.5625 11.0416 11.9845 11.0416 12.2448 11.3019L13.1849 12.242C13.445 12.5024 13.4452 12.9245 13.1849 13.1847C12.9247 13.445 12.5026 13.4448 12.2422 13.1847L11.3021 12.2446C11.0418 11.9843 11.0418 11.5623 11.3021 11.3019ZM10 7.99984C10 6.89527 9.10459 5.99984 8.00002 5.99984C6.89545 5.99984 6.00002 6.89527 6.00002 7.99984C6.00002 9.10441 6.89545 9.99984 8.00002 9.99984C9.10459 9.99984 10 9.10441 10 7.99984ZM2.66669 7.33317C3.03488 7.33317 3.33335 7.63165 3.33335 7.99984C3.33335 8.36803 3.03488 8.6665 2.66669 8.6665H1.33335C0.965164 8.6665 0.666687 8.36803 0.666687 7.99984C0.666687 7.63165 0.965164 7.33317 1.33335 7.33317H2.66669ZM14.6667 7.33317C15.0349 7.33317 15.3334 7.63165 15.3334 7.99984C15.3334 8.36803 15.0349 8.6665 14.6667 8.6665H13.3334C12.9652 8.6665 12.6667 8.36803 12.6667 7.99984C12.6667 7.63165 12.9652 7.33317 13.3334 7.33317H14.6667ZM2.81512 2.81494C3.07542 2.55465 3.49747 2.55475 3.75783 2.81494L4.69794 3.75505C4.95829 4.0154 4.95829 4.4374 4.69794 4.69775C4.43759 4.9581 4.01558 4.9581 3.75523 4.69775L2.81512 3.75765C2.55494 3.49729 2.55483 3.07524 2.81512 2.81494ZM12.2422 2.81494C12.5026 2.55481 12.9246 2.55466 13.1849 2.81494C13.4451 3.07522 13.445 3.4973 13.1849 3.75765L12.2448 4.69775C11.9845 4.95809 11.5625 4.95805 11.3021 4.69775C11.0418 4.4374 11.0418 4.0154 11.3021 3.75505L12.2422 2.81494ZM7.33335 2.6665V1.33317C7.33335 0.964981 7.63183 0.666504 8.00002 0.666504C8.36821 0.666504 8.66669 0.964981 8.66669 1.33317V2.6665C8.66669 3.03469 8.36821 3.33317 8.00002 3.33317C7.63183 3.33317 7.33335 3.03469 7.33335 2.6665ZM11.3334 7.99984C11.3334 9.84079 9.84097 11.3332 8.00002 11.3332C6.15907 11.3332 4.66669 9.84079 4.66669 7.99984C4.66669 6.15889 6.15907 4.6665 8.00002 4.6665C9.84097 4.6665 11.3334 6.15889 11.3334 7.99984Z`,fill:`currentColor`})}),Z(`defs`,{children:Z(`clipPath`,{id:`clip0_light_icon`,children:Z(`rect`,{width:`16`,height:`16`,fill:`white`})})})]}),Z(`span`,{children:`Light`})]}),Q(`button`,{type:`button`,onClick:()=>j(`dark`),disabled:!!g,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${i===`dark`||!i&&_===`dark`||!i&&!_&&typeof window<`u`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`bg-[#DBEAFE] text-[#2563EB]`:`bg-transparent text-gray-900 dark:text-gray-100 hover:text-gray-700 dark:hover:text-gray-300`} ${g?`cursor-not-allowed opacity-50`:`cursor-pointer`}`,children:[Q(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[Z(`title`,{children:`Dark Mode`}),Z(`path`,{d:`M7.7207 1.34229C8.12353 1.35288 8.42496 1.60511 8.5651 1.89827C8.70858 2.19855 8.70802 2.57945 8.50781 2.89893L8.50716 2.89827C8.10787 3.53737 7.93751 4.29341 8.02278 5.04216C8.10811 5.79102 8.4449 6.48902 8.97786 7.02197C9.51083 7.55485 10.2088 7.89112 10.9577 7.9764C11.7065 8.06164 12.4624 7.89084 13.1016 7.49137L13.2233 7.42562C13.5135 7.29382 13.8376 7.30794 14.1009 7.43343C14.4146 7.58299 14.6797 7.91693 14.6556 8.36051C14.5861 9.64638 14.1455 10.8847 13.3874 11.9256C12.6291 12.9666 11.5855 13.7658 10.3828 14.2264C9.18016 14.6869 7.8696 14.7895 6.61002 14.5213C5.35045 14.2531 4.19583 13.6253 3.28515 12.7147C2.37445 11.8041 1.74687 10.6494 1.47851 9.38981C1.21017 8.13019 1.3123 6.81977 1.77278 5.61702C2.23329 4.41426 3.03259 3.3708 4.07356 2.61247C5.11452 1.85416 6.35267 1.41314 7.63867 1.34359L7.7207 1.34229ZM7.08072 2.74723C6.28037 2.88708 5.51928 3.20826 4.85807 3.68994C4.02544 4.29656 3.38661 5.13153 3.01822 6.09359C2.64983 7.05577 2.56789 8.10413 2.78255 9.11182C2.99723 10.1195 3.49927 11.0435 4.22786 11.772C4.95644 12.5005 5.88029 13.0027 6.88801 13.2173C7.89573 13.4318 8.94409 13.3495 9.90624 12.981C10.8684 12.6124 11.7033 11.9733 12.3099 11.1405C12.7914 10.4794 13.1115 9.71859 13.2513 8.91846C12.489 9.26194 11.645 9.39674 10.8066 9.30127C9.75813 9.18186 8.7807 8.71088 8.0345 7.96468C7.28837 7.2185 6.81731 6.241 6.69791 5.19255C6.60247 4.354 6.73706 3.50961 7.08072 2.74723Z`,fill:`currentColor`})]}),Z(`span`,{children:`Dark`})]})]})]}),!1,Q(`div`,{className:`flex items-center justify-between`,children:[Q(`span`,{className:`text-sm font-medium text-gray-900 dark:text-gray-100`,children:[`Display Currency`,!f&&Z(`span`,{className:`text-xs text-gray-400 dark:text-gray-500 block`,children:`Default: USD`})]}),Q(`div`,{className:`relative`,ref:D,children:[Q(`button`,{type:`button`,onClick:()=>x(!b),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors text-sm font-medium text-gray-900 dark:text-gray-100`,children:[Q(`span`,{className:`flex items-center gap-1.5`,children:[I?.flag&&Z(`span`,{className:`text-base`,children:I.flag}),Q(`span`,{children:[I?.symbol,` `,I?.code]})]}),Z(Di,{className:`w-4 h-4 transition-transform ${b?`rotate-180`:``}`})]}),b&&Q(`div`,{className:`absolute right-0 mt-2 w-64 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-50`,children:[Z(`div`,{className:`p-2 border-b border-gray-200 dark:border-gray-700`,children:Z(`input`,{ref:k,type:`text`,value:w,onChange:e=>T(e.target.value),placeholder:`Search currencies...`,className:`w-full px-3 py-1.5 text-sm bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400`})}),Z(`div`,{className:`max-h-56 overflow-y-auto trails-scrollbar`,children:ee.length>0?ee.map(e=>Q(`button`,{type:`button`,onClick:()=>{A({component:`UserPreferences`,action:`change_currency`,label:e.code,metadata:{currencyName:e.name,currencySymbol:e.symbol,previousCurrency:f,newCurrency:e.code}}),p(e.code),x(!1),T(``)},className:`w-full px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex items-center justify-between ${e.code===F?`bg-gray-50 dark:bg-gray-700/50`:``}`,children:[Q(`div`,{className:`flex items-center gap-2`,children:[e.flag&&Z(`span`,{className:`text-base`,children:e.flag}),Q(`div`,{className:`flex flex-col items-start`,children:[Q(`span`,{className:`text-sm font-medium text-gray-900 dark:text-gray-100`,children:[e.symbol,` `,e.code]}),Z(`span`,{className:`text-xs text-gray-500 dark:text-gray-400`,children:e.name})]})]}),e.code===F&&Q(`svg`,{className:`w-4 h-4 text-blue-600`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:`3`,children:[Z(`title`,{children:`Selected`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M5 13l4 4L19 7`})]})]},e.code)):Z(`div`,{className:`px-4 py-3 text-sm text-gray-500 dark:text-gray-400 text-center`,children:`No currencies found`})})]})]})]}),Q(`div`,{className:`flex items-center justify-between`,children:[Z(`span`,{className:`text-sm font-medium text-gray-900 dark:text-gray-100`,children:`Hide Balances`}),Z(`button`,{type:`button`,onClick:()=>{A({component:`UserPreferences`,action:`toggle_balance_visibility`,label:t?`hide`:`show`,metadata:{previousState:t.toString(),newState:(!t).toString()}}),n()},className:`relative inline-flex h-8 w-14 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 ${t?`bg-gray-200 dark:bg-gray-700`:`bg-blue-600`}`,children:Z(`span`,{className:`inline-flex items-center justify-center h-6 w-6 transform rounded-full bg-white transition-transform ${t?`translate-x-1`:`translate-x-7`}`,children:!t&&Q(`svg`,{className:`w-3.5 h-3.5 text-blue-600`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:`3`,children:[Z(`title`,{children:`Enabled`}),Z(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M5 13l4 4L19 7`})]})})})]}),Z(`div`,{className:`pt-4 dark:border-gray-700`,children:Q(`button`,{type:`button`,onClick:M,className:`flex items-center gap-1 px-2 py-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 trails-bg-secondary rounded-xl hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors cursor-pointer`,children:[Z(Ki,{className:`w-3 h-3`}),`Reset`]})})]})]})},lO=()=>{let{navigate:e,backScreen:t,mode:n,goHome:r}=y_(),{switchAccount:i}=ai(),{setSelectedFundMethod:a,setSelectedFundingWallet:o}=Vu(),s=Hu(),{selectedToken:c,clearSelectedToken:l,setHasManualSelection:u}=ul(),{fundOptions:d}=wo(),{clearChainFilter:f}=mu(),p=d?.hideWallets??[];return Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:()=>e(t??`fund-methods`),headerContent:`Select a wallet`,headerContentAlign:`left`,rightSideContent:Z(`div`,{className:`w-9`})}),Z(`div`,{className:`flex-1`,children:Z(`div`,{className:`flex flex-col gap-1`,children:Z(xw,{showConnectNewWallet:!0,showDisconnect:!0,showWalletAddress:!1,hiddenWallets:p,disableZeroBalanceWallets:!0,showZeroBalanceMessage:!0,activeFundingWallet:s,onWalletSelect:({groupedWallet:t,evmWallet:s})=>{let d=s?Ju(s):t.selection;s&&i(s.connectionId,s.address),o(d),$u(c?.chainId,d)&&(l(),u(!1),f()),a(`wallet`),n===`fund`?e(`tokens`):r()},backScreen:`fund-methods`})})})]})};function uO(e,t){let n=t?.namespace===`solana`?`solana`:`evm`;return{...te(e,{source:t?.namespace===`solana`?`solana-provider`:`evm-provider`,wallet:t?{ecosystem:n,icon:t.icon,id:t.id,name:t.name,namespace:t.namespace}:void 0}),connectionType:n,walletIcon:t?.icon,walletId:t?.id,walletName:t?.name}}function dO(e,t){return t?e.map(e=>fO(e,t)):[...e]}function fO(e,t){let n=e.variants?.map(e=>fO(e,t)),r=n?{...e,variants:n}:e,i=t(r),a=n?.length?n.every(e=>e.disabledReason)?i??n.find(e=>e.disabledReason)?.disabledReason:void 0:i;if(!a){let{disabledReason:e,...t}=r;return t}return{...r,disabledReason:a}}function pO(e){return e?.activeAccount?.address??e?.accounts.find(t=>t.namespace===e.namespace)?.address??e?.accounts[0]?.address}function mO(e,t,n){let r=n?e.connections.find(e=>e.namespace===t&&(e.walletId===n||e.walletGroupId===n||e.id===n)):void 0,i=e.activeConnection?.namespace===t?e.activeConnection:void 0,a=e.connections.find(e=>e.namespace===t);return pO(r??i??a)}function hO(e){return e.namespace??(e.ecosystem===`solana`?`solana`:`eip155`)}function gO(e){return`${hO(e)}:${e.id}`}function _O(e){return`family:${e.familyId||e.id}`}function vO(e){let t=e.variants?.length?e.variants:[e],n=new Map;for(let e of t)n.set(gO(e),e);return[...n.values()]}function yO(e,t){let n=hO(t),r=new Set([t.id,t.familyId].filter(Boolean));return e.connections.find(e=>e.namespace===n&&(r.has(e.walletId)||e.walletGroupId&&r.has(e.walletGroupId)||r.has(e.id)))}function bO(e){return!e||e.managedBy===`host`?!1:(e.showDisconnect??e.ui?.showDisconnect)===!0}function xO({solanaWallet:e,wallet:t,walletSession:n}){if(!t.connected)return!1;let r=yO(n,t);return r?bO(r):hO(t)===`solana`&&!!(e?.connected&&e.disconnect)}const SO=({className:e,hideBackButton:t=!0,onBack:n,onClose:r,initialView:i=`list`,initialWalletId:a,initialPendingWallet:o,initialError:s=null,initialIsConnecting:c,getWalletDisabledReason:l,onConnected:u,onError:d,showFooter:f=!0})=>{let[p,m]=X(i),[h,g]=X(s),[_,v]=X(o??(a?{connectionType:`evm`,id:a,name:i===`walletconnect`?`WalletConnect`:void 0}:null)),[y,b]=X(null),[S,C]=X(c??i===`pending`),[T,E]=X(o?.id??a??null),[D,k]=X(null),A=li(),j=di(),{connect:N,disconnect:P}=ai(),F=qu(),I=n_(),ee=!!F&&I,te=K((e,t)=>{let n=uO(e,t);g(n),C(!1),m(`error`),d?.(n)},[d]),ne=K(async e=>{let t=_O(e),n=vO(e).filter(e=>xO({solanaWallet:F,wallet:e,walletSession:j}));if(n.length){k(t),g(null);try{for(let e of n){let t=yO(j,e);if(t){if(!bO(t))continue;await P(t.id);continue}if(hO(e)===`solana`&&F?.disconnect){await Promise.resolve(F.disconnect());continue}throw Error(`No connected ${e.name} wallet found to disconnect`)}b(null),m(`list`)}catch(t){let r=n[0];te(t,{id:e.id,name:e.name,namespace:r?hO(r):void 0})}finally{k(e=>e===t?null:e)}}},[P,te,F,j]),ie=K(e=>vO(e).some(e=>xO({solanaWallet:F,wallet:e,walletSession:j})),[F,j]),L=K(e=>D===_O(e),[D]),R=K(async e=>{let t=e.namespace===`solana`?`solana`:`evm`;if(E(e.id),v({connectionType:t,icon:e.icon,id:e.id,name:e.name}),e.connected){let t=e.namespace??`eip155`;g(null),C(!1),u?.({address:mO(j,t,e.id),namespace:t,walletId:e.id});return}if(e.flow===`walletconnect`){g(null),C(!1),m(`walletconnect`);return}C(!0),m(`pending`);try{let t=await N(e.id);C(!1),u?.(t)}catch(t){te(t,e)}},[N,te,u,j]),ae=K(async e=>{let t=A.find(t=>t.id===e&&t.namespace!==`solana`);if(t){await R(t);return}te(Error(`No EVM wallet provider available`),{id:e})},[R,te,A]),B=K(async e=>{if(E(e.walletId),v({connectionType:`solana`,externalSolanaWallet:e,icon:e.walletIcon,id:e.walletId,name:e.walletName}),e.connected){g(null),C(!1),u?.({address:F?.publicKey?.toBase58(),namespace:`solana`,walletId:e.walletId});return}if(!F?.connect){te(Error(`No Solana wallet provider available`),{id:e.walletId,name:e.walletName,namespace:`solana`});return}C(!0),m(`pending`);try{let t=(await Promise.resolve(F.connect(e.walletId)))?.publicKey?.toBase58()??F.publicKey?.toBase58();C(!1),u?.({address:t,namespace:`solana`,walletId:e.walletId})}catch(t){te(t,{id:e.walletId,name:e.walletName,namespace:`solana`})}},[te,u,F]),oe=J(()=>w(dO(z({includeInstallableSolanaWallets:ee,onSolanaWalletSelect:B,onWalletSelect:R,solanaWallets:ee?F?.availableWallets:void 0,walletOptions:A}),l)),[B,R,l,ee,F?.availableWallets,A]),H=J(()=>y?oe.find(e=>e.id===y.id||e.familyId===y.familyId)??y:null,[oe,y]),se=()=>{if(p===`list`){n?.();return}m(`list`)},U=r??n;return Z(`div`,{className:e,children:(()=>{switch(p){case`all-wallets`:return Z(V,{onBack:se,onClose:U,onWalletVariantsSelect:e=>{b(e),m(`wallet-variants`)},walletOptions:oe});case`wallet-variants`:return H?Z(M,{canDisconnectWallet:ie,isWalletDisconnecting:L,onBack:se,onClose:U,onWalletDisconnect:ne,wallet:H}):null;case`walletconnect`:return Z(ce,{onBack:se,onClose:U,onContinue:()=>{let e=_?.id??`walletconnect`;C(!1),u?.({address:mO(j,`eip155`,e),namespace:`eip155`,walletId:e})},selectedWalletId:T??_?.id??void 0});case`pending`:return Z(O,{error:h?.message??null,isConnecting:S,onBack:se,onRetry:()=>{if(_?.connectionType===`solana`){if(_.externalSolanaWallet)B(_.externalSolanaWallet);else{let e=A.find(e=>e.id===_.id&&e.namespace===`solana`);e&&R(e)}return}_?.id&&ae(_.id)},selectedWalletIcon:_?.icon,selectedWalletId:_?.id??T??``,selectedWalletName:_?.name,showRetry:!!h});case`error`:return Z(re,{error:h,onBack:se,onClose:U,onChooseAnotherWallet:()=>m(`list`),onRetry:_?.id?()=>{if(_.connectionType===`solana`){if(_.externalSolanaWallet)B(_.externalSolanaWallet);else{let e=A.find(e=>e.id===_.id&&e.namespace===`solana`);e&&R(e)}return}let e=A.find(e=>e.id===_.id);e&&R(e)}:void 0});default:return Z(x,{hideBackButton:t,onBack:n,onClose:U,onMoreWallets:()=>m(`all-wallets`),onWalletVariantsSelect:e=>{b(e),m(`wallet-variants`)},showFooter:f,walletOptions:oe})}})()})};function CO({onStart:e,onQuote:t,onSignatureRequest:n,onSignatureConfirmed:r,onSignatureRejected:i,onApprovalRequest:a,onApprovalConfirmed:o,onApprovalRejected:c,onComplete:l,onError:u,onStatusUpdate:d}){let f=Y(Df()),p=K(()=>{f.current=Df()},[]),m=K(()=>{if(e&&f.current)try{e({sessionId:f.current})}catch(e){s.console.error(`[trails-sdk] Error calling onStart:`,e)}},[e]),g=K(e=>{if(t&&f.current)try{t({sessionId:f.current,quote:e})}catch(e){s.console.error(`[trails-sdk] Error calling onQuote:`,e)}},[t]),_=K(()=>{if(n&&f.current)try{n({sessionId:f.current})}catch(e){s.console.error(`[trails-sdk] Error calling onSignatureRequest:`,e)}},[n]),v=K(()=>{if(r&&f.current)try{r({sessionId:f.current})}catch(e){s.console.error(`[trails-sdk] Error calling onSignatureConfirmed:`,e)}},[r]),y=K(e=>{if(i&&f.current)try{i({sessionId:f.current,error:e})}catch(e){s.console.error(`[trails-sdk] Error calling onSignatureRejected:`,e)}},[i]),b=K(()=>{if(a&&f.current)try{a({sessionId:f.current})}catch(e){s.console.error(`[trails-sdk] Error calling onApprovalRequest:`,e)}},[a]),x=K(e=>{if(o&&f.current)try{o({sessionId:f.current,transactionHash:e})}catch(e){s.console.error(`[trails-sdk] Error calling onApprovalConfirmed:`,e)}},[o]),S=K(e=>{if(c&&f.current)try{c({sessionId:f.current,error:e})}catch(e){s.console.error(`[trails-sdk] Error calling onApprovalRejected:`,e)}},[c]),C=K((e,t)=>{if(l&&f.current)try{l({sessionId:f.current})}catch(e){s.console.error(`[trails-sdk] Error calling onComplete:`,e)}e===`success`?(Vo(),zo(`Transaction Complete`,`Your transaction has been successfully processed`,`success`,5*Ee)):Bo(`Transaction Failed`,`Your transaction failed or was refunded`,`error`)},[l]),w=K(e=>{let t=e;if(F(e)&&(t=new h(ae(e)),y(t)),u&&f.current)try{u({sessionId:f.current,error:t})}catch(e){s.console.error(`[trails-sdk] Error calling onError:`,e)}Bo(`Transaction Failed`,T(t,`An error occurred while processing your transaction`),`error`)},[u,y]),E=K(e=>{if(d&&f.current)try{d({sessionId:f.current,transactionStates:e})}catch(e){s.console.error(`[trails-sdk] Error calling onStatusUpdate:`,e)}},[d]);return{sessionId:f.current,startCheckout:p,checkoutOnHandlers:{triggerCheckoutStart:m,triggerCheckoutQuote:g,triggerCheckoutSignatureRequest:_,triggerCheckoutSignatureConfirmed:v,triggerCheckoutSignatureRejected:y,triggerCheckoutApprovalRequest:b,triggerCheckoutApprovalConfirmed:x,triggerCheckoutApprovalRejected:S,triggerCheckoutComplete:C,triggerCheckoutError:w,triggerCheckoutStatusUpdate:E}}}const wO=({setSelectedToken:e,setTransactionStates:t,setPrepareSendQuote:n,setShowWalletConfirmRetry:r,setError:i,isEvmConnected:a})=>{let o=Vx(),{navigate:s,overrideMode:c}=y_();return{handleDebugScreenSelect:K(async l=>{i(null);let u={id:1,name:`USD Coin`,symbol:`USDC`,balance:Sn(`1.99`,6)?.toString(),imageUrl:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48/logo.png`,chainId:1,contractAddress:`0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48`,contractInfo:{decimals:6,symbol:`USDC`,name:`USD Coin`}},d=await Up({originDepositAddress:`0x5A0fb747531bC369367CB031472b89ea4D5c6Df7`,destinationDepositAddress:`0x5A0fb747531bC369367CB031472b89ea4D5c6Df7`,originAmount:Sn(`1`,6)?.toString(),originTokenAddress:`0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48`,originChainId:1,originTokenPriceUsd:`1`,destinationChainId:137,destinationTokenAddress:`0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359`,destinationAmount:Sn(`0.97`,6)?.toString(),destinationTokenPriceUsd:`1`,trailsApiKey:o.trailsApiKey,trailsApiUrl:o.trailsApiUrl,sequenceMetadataUrl:o.sequenceMetadataUrl});switch(l){case`connect`:e(null),t([]),s(`connect`);break;case`tokens`:a&&(e(null),t([]),s(`tokens`));break;case`select-origin-token`:s(`select-origin-token`);break;case`select-origin-amount`:s(`select-origin-amount`);break;case`chain-list`:e(null),t([]),s(`chain-list`);break;case`send-form`:c(`pay`),e(u),t([]),s(`send-form`);break;case`fund-form`:c(`fund`),e(u),t([]),s(`fund-form`);break;case`recipients`:s(`recipients`);break;case`wallet-confirmation`:e(u),n(d),t([]),r(!1),s(`wallet-confirmation`);break;case`qr-code-wallet-select`:n(d),s(`qr-code-wallet-select`);break;case`wallet-confirmation-retry`:e(u),n(d),t([]),r(!0),s(`wallet-confirmation`);break;case`pending-1-item-0-confirmed`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`pending`,label:`Swap`}]),n(d),s(`pending`);break;case`pending-1-item-1-confirmed`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`confirmed`,label:`Swap`}]),n(d),s(`pending`);break;case`pending-2-item-0-confirmed`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`pending`,label:`Deposit`},{transactionHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,explorerUrl:`https://polygonscan.com/tx/0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,chainId:137,state:`pending`,label:`Swap`}]),n(d),s(`pending`);break;case`pending-2-item-1-confirmed`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`confirmed`,label:`Deposit`},{transactionHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,explorerUrl:`https://polygonscan.com/tx/0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,chainId:137,state:`pending`,label:`Swap`}]),n(d),s(`pending`);break;case`pending-2-item-2-confirmed`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`confirmed`,label:`Deposit`},{transactionHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,explorerUrl:`https://polygonscan.com/tx/0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,chainId:137,state:`confirmed`,label:`Swap`}]),n(d),s(`pending`);break;case`pending-3-item-0-confirmed`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`pending`,label:`Deposit`},{transactionHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,explorerUrl:`https://polygonscan.com/tx/0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,chainId:137,state:`pending`,label:`Swap & Bridge`},{transactionHash:`0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,explorerUrl:`https://arbiscan.io/tx/0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,chainId:42161,state:`pending`,label:`Execute`}]),n(d),s(`pending`);break;case`pending-3-item-1-confirmed`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`confirmed`,label:`Deposit`},{transactionHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,explorerUrl:`https://polygonscan.com/tx/0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,chainId:137,state:`pending`,label:`Swap & Bridge`},{transactionHash:`0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,explorerUrl:`https://arbiscan.io/tx/0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,chainId:42161,state:`pending`,label:`Execute`}]),n(d),s(`pending`);break;case`pending-3-item-2-confirmed`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`confirmed`,label:`Deposit`},{transactionHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,explorerUrl:`https://polygonscan.com/tx/0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,chainId:137,state:`confirmed`,label:`Swap & Bridge`},{transactionHash:`0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,explorerUrl:`https://arbiscan.io/tx/0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,chainId:42161,state:`pending`,label:`Execute`}]),n(d),s(`pending`);break;case`pending-3-item-3-confirmed`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`confirmed`,label:`Deposit`},{transactionHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,explorerUrl:`https://polygonscan.com/tx/0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,chainId:137,state:`confirmed`,label:`Swap & Bridge`},{transactionHash:`0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,explorerUrl:`https://arbiscan.io/tx/0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,chainId:42161,state:`confirmed`,label:`Execute`}]),n(d),s(`pending`);break;case`pending-3-item-2-confirmed-with-error`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`confirmed`,label:`Deposit`},{transactionHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,explorerUrl:`https://polygonscan.com/tx/0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,chainId:137,state:`confirmed`,label:`Swap & Bridge`,decodedGuestModuleEvents:[{type:`CallFailed`,opHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,index:BigInt(1),returnData:`0x`}]},{transactionHash:`0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,explorerUrl:`https://arbiscan.io/tx/0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,chainId:42161,state:`pending`,label:`Execute`}]),n(d),s(`pending`);break;case`receipt`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`confirmed`,label:`Deposit`},{transactionHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,explorerUrl:`https://polygonscan.com/tx/0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,chainId:137,state:`confirmed`,label:`Swap & Bridge`},{transactionHash:`0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,explorerUrl:`https://arbiscan.io/tx/0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,chainId:42161,state:`confirmed`,label:`Execute`}]),s(`receipt`);break;case`receipt-failed`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`confirmed`,label:`Deposit`},{transactionHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,explorerUrl:`https://polygonscan.com/tx/0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,chainId:137,state:`confirmed`,label:`Swap & Bridge`},{transactionHash:``,explorerUrl:``,chainId:42161,state:`failed`,label:`Execute`}]),s(`receipt`);break;case`receipt-refunded`:t([{transactionHash:`0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,explorerUrl:`https://polygonscan.com/tx/0x45bb2259631e73f32841a6058b0a4008c75bca296942bec6326d188978d5353d`,chainId:137,state:`confirmed`,label:`Deposit`},{transactionHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,explorerUrl:`https://polygonscan.com/tx/0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,chainId:137,state:`confirmed`,label:`Swap & Bridge`},{transactionHash:`0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,explorerUrl:`https://arbiscan.io/tx/0xf3b172111d2e64e9d4940d91097f04a0bbd0acc816e2cf49eec664c6f8fcaf76`,chainId:42161,state:`confirmed`,label:`Execute`,decodedGuestModuleEvents:[{type:`CallFailed`,opHash:`0x6ff30196ca0d4998cc6928bca2ec282766eb3c3997535e0a61e0d69c9c9b16b8`,index:BigInt(1),returnData:`0x`}],decodedTokenSweeperEvents:[{type:`Sweep`,token:Cn,recipient:Cn,amount:BigInt(0xde0b6b3a7640000)}],refunded:!0}]),s(`receipt`);break;case`onramp`:s(`onramp-meld`);break;case`wallet-connect`:s(`wallet-connect`);break;case`wallet-list`:s(`wallet-list`);break;case`wallet-connection-pending`:s(`wallet-connection-pending`,{data:{connectionType:`evm`,walletId:`metamask`,walletName:`MetaMask`}});break;case`wallet-connection-pending-retry`:s(`wallet-connection-pending`,{data:{connectionType:`evm`,errorMessage:`Debug wallet connection failed`,walletId:`metamask`,walletName:`MetaMask`}});break;case`fund-methods`:s(`fund-methods`);break;case`payment-methods`:s(`payment-methods`);break;case`earn`:c(`earn`),s(`earn`);break;case`earn-pools`:s(`earn-pools`);break;case`swap`:c(`swap`),e(null),t([]),s(`swap`);break;case`account-history`:s(`account-history`);break;case`account-settings`:s(`account-settings`);break;case`user-preferences`:s(`user-preferences`);break}},[s,e,t,n,r,c,i,a,o.trailsApiKey,o.trailsApiUrl,o.sequenceMetadataUrl])}},TO=(e,t,n)=>{let[r,i]=X(``),[a,o]=X(null),[c,l]=X(``),[u,d]=X(null),[f,p]=X([]),[m,h]=X(!1),[g,_]=X(!1);return q(()=>{if(e&&r&&a&&!m){try{e({txHash:r,chainId:a,sessionId:Df()})}catch(e){s.console.error(`[trails-sdk] Error calling onOriginConfirmation:`,e)}h(!0)}},[r,a,m,e]),q(()=>{if(t&&c&&u&&!g){try{t({txHash:c,chainId:u,sessionId:Df()})}catch(e){s.console.error(`[trails-sdk] Error calling onDestinationConfirmation:`,e)}_(!0)}},[c,u,g,t]),q(()=>{!f||f.length===0||f.every(e=>e.state===`confirmed`)&&n&&(s.console.log(`[trails-sdk] All transactions confirmed, triggering completion`),n({transactionStates:f}))},[f,n]),{originTxHash:r,setOriginTxHash:K(e=>{i(e),e===``&&h(!1)},[]),originChainId:a,setOriginChainId:o,destinationTxHash:c,setDestinationTxHash:K(e=>{l(e),e===``&&_(!1)},[]),destinationChainId:u,setDestinationChainId:d,transactionStates:f,setTransactionStates:p}};function EO(e){let{enabled:t,intentId:n,fallbackTransactionStates:r,setTransactionStates:i,onStatusUpdate:a,onFundingObserved:o}=e,c=gs(),{intentReceipt:l}=Zx(t?n:void 0,c);q(()=>{l&&(i(e=>{let t=e.length>0?e:r??[];if(t.length===0)return e;let{transactionStates:i,changed:o}=Eg({currentStates:t,receipt:l});return o&&(s.console.log(`[trails-sdk] External funding receipt sync updated transaction states`,{intentId:n,status:l.status}),a?.(i)),o?i:e}),Dg(l)&&o?.())},[r,n,l,o,a,i])}function DO(e,t,n){return e===t?!1:(n.clearSelectedToken(),n.setSellAmount(``),n.setBuyAmount(``),n.setPrepareSendQuote(null),n.setSelectedMeshExchange(null),n.setSelectedBluvoExchange?.(null),n.setSelectedMeshAccessTokens?.([]),n.clearSelectedBluvoFunding?.(),!0)}const OO=e=>{let t=e?.trim();return!!(!t||t.length>0&&t.length<=5||bn(t)||ut(t))},kO={Wallet:`wallet`,CryptoTransfer:`crypto-transfer`,Onramp:`onramp`,OnrampExchange:`onramp-exchange`},AO=({onBack:e,onSelectQrCode:t})=>{let{switchAccount:n}=ai(),{mode:r,goHome:i}=y_(),{setSelectedFundMethod:a,setSelectedFundingWallet:o,setPaymentMethod:c}=Vu(),{fundOptions:l}=wo(),u=l?.hideWallets??[],{paymentMethods:d,isLoading:f,error:p}=SD({enabled:!0});return Q(`div`,{className:`flex flex-col h-full`,children:[Z(M_,{onBack:e,headerContent:`Payment methods`,headerContentAlign:`left`,rightSideContent:Z(`div`,{className:`w-9`})}),Z(`div`,{className:`flex-1`,children:Q(`div`,{className:`space-y-4`,children:[Z(xw,{showConnectNewWallet:!0,onWalletSelect:({groupedWallet:e,evmWallet:t})=>{try{t?(n(t.connectionId,t.address),s.console.log(`[trails-sdk] Switched to wallet: ${t.address}`),o(Ju(t))):o(e.selection),a(`wallet`),i()}catch(e){s.console.error(`[trails-sdk] Failed to switch wallet:`,e)}},backScreen:`payment-methods`,hiddenWallets:u}),Q(`div`,{className:`relative flex items-center justify-center`,children:[Z(`div`,{className:`flex-1 border-t border-gray-200 dark:border-gray-700`}),Z(`span`,{className:`px-4 text-sm text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-900`,children:`or`}),Z(`div`,{className:`flex-1 border-t border-gray-200 dark:border-gray-700`})]}),Q(`div`,{className:`trails-border-radius-container border trails-border-primary`,children:[r!==`pay`&&Q(hi,{children:[f?Q(hi,{children:[Z(`div`,{className:`border-b border-gray-200 dark:border-gray-700`}),Z(`div`,{className:`px-3 py-4 text-sm text-gray-500 dark:text-gray-400`,children:`Loading payment methods...`})]}):p?Q(hi,{children:[Z(`div`,{className:`border-b border-gray-200 dark:border-gray-700`}),Z(`div`,{className:`px-3 py-4 text-sm text-red-500 dark:text-red-400`,children:`Failed to load payment methods`})]}):d.map(e=>Z(or.Fragment,{children:Q(`button`,{type:`button`,onClick:()=>{a(`onramp-meld`),c({id:e.paymentMethod,name:e.name}),i()},className:`w-full text-left px-3 py-4 text-sm flex items-center justify-between cursor-pointer transition-colors trails-text-primary trails-hover-bg`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(`img`,{src:e.logos?.light||e.logos?.dark||``,alt:e.name,className:`w-6 h-6`}),Z(`span`,{className:`text-sm font-bold`,children:e.name})]}),Z(ki,{className:`w-5 h-5 text-gray-400`})]})},e.paymentMethod)),Z(`div`,{className:`border-b border-gray-200 dark:border-gray-700`}),Q(`button`,{type:`button`,onClick:()=>{a(`onramp-mesh`),i()},className:`w-full text-left px-3 py-4 text-sm flex items-center justify-between cursor-pointer transition-colors trails-text-primary trails-hover-bg`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(xi,{className:`w-4 h-4`}),Z(`span`,{className:`text-sm font-bold`,children:`Send from Exchange`})]}),Z(ki,{className:`w-5 h-5 text-gray-400`})]})]}),r!==`pay`&&Z(`div`,{className:`border-b border-gray-200 dark:border-gray-700`}),Q(`button`,{type:`button`,onClick:t,className:`w-full text-left px-3 py-4 text-sm flex items-center justify-between cursor-pointer transition-colors trails-text-primary trails-hover-bg`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(Wi,{className:`w-4 h-4`}),Z(`span`,{className:`text-sm font-bold`,children:`Pay with QR Code`})]}),Z(ki,{className:`w-5 h-5 text-gray-400`})]})]})]})})]})},jO=new Set([`connect`,`wallet-connect`,`wallet-connection-pending`,`wallet-list`,`connect-all-wallets`,`connect-wallet-variants`,`connect-error`]),MO=new Set([`direct-transfer-screen`,`wallet-confirmation`,`onramp-confirmation`,`onramp-mesh`,`onramp-bluvo`,`pending`,`receipt`]);function NO(e,t){return!e&&!jO.has(t)}function PO(e,t){return e===`direct-transfer-screen`&&t!==`pending`&&t!==`receipt`&&t!==`qr-code-wallet-select`||e===`fund-form`&&!MO.has(t)}function FO({currentMode:e,hasFromToken:t,selectedFundMethod:n}){if(e===`fund`&&(n===`wallet`||n===`direct-transfer`)){let e=t?`fund-form`:`tokens`;return{screen:e,options:e===`fund-form`?{backTarget:`fund-methods`}:void 0}}return e===`swap`?{screen:`swap`}:e===`earn`?{screen:`earn`}:e===`fund`?{screen:`fund-methods`}:e===`pay`?{screen:`send-form`}:{screen:`account-settings`}}function IO(e){return e===`direct-transfer`?`wallet`:e}function LO(e){return e===`fund`}function RO(e){let{enabled:t=!0,environment:n,integrationId:r,accessTokens:i=[]}=e,a=gv(),{data:o=0,isLoading:s}=Or({queryKey:[`mesh-session-account-balance-usd`,n,r,J(()=>i.map(e=>`${e.accountId}:${e.accessToken}`).join(`|`),[i])],queryFn:async()=>{let e=await a.getMeshSupportedTokens({environment:n,integrationId:r,accessTokens:i.length>0?i:void 0}),t=Number(e.totalBalanceUsd||`0`);if(Number.isFinite(t)&&t>=0)return t;let o=(e.tokens||[]).reduce((e,t)=>{let n=Number(t.balanceUsd||`0`);return e+(Number.isFinite(n)?n:0)},0);return Number.isFinite(o)?o:0},enabled:t&&!!r,staleTime:3e4,gcTime:300*1e3,refetchOnMount:!0,refetchOnWindowFocus:!1,refetchOnReconnect:!1});return{balanceUsd:o,balanceUsdDisplay:J(()=>new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`,minimumFractionDigits:2,maximumFractionDigits:2}).format(o||0),[o]),isLoading:s}}function zO(e){let t=K(t=>qv({environment:e,integrationId:t}),[e]);return{getStoredMeshAccessTokensForIntegration:K(e=>$v(t(e)),[t]),clearStoredMeshAccessTokensForIntegration:K(e=>{ty(t(e))},[t]),clearStoredMeshUserIdForIntegration:K(e=>{Qv(t(e))},[t])}}function BO(e,t){let[n,r]=X({});return{meshExchangeAccessTokens:n,sessionScreenMeshAccessTokens:J(()=>e?.integrationId?n[e.integrationId]??t:t,[n,t,e?.integrationId]),resolveAccessTokens:K(r=>{if(r?.integrationId){let i=n[r.integrationId];return i&&i.length>0?i:e?.integrationId===r.integrationId&&t.length>0?t:void 0}return t.length>0?t:void 0},[n,t,e?.integrationId]),setAccessTokensForIntegration:K((e,t)=>{r(n=>({...n,[e]:t}))},[]),clearAccessTokensForIntegration:K(e=>{r(t=>({...t,[e]:[]}))},[])}}function VO(e){let{selectedMeshExchange:t,selectedMeshAccessTokens:n,meshEnvironment:r,screen:i,trailsApiUrl:a,trailsApiKey:o}=e,[s,c]=X(null),{sessionScreenMeshAccessTokens:l,resolveAccessTokens:u,setAccessTokensForIntegration:d,clearAccessTokensForIntegration:f}=BO(t,n),{balanceUsd:p,balanceUsdDisplay:m,isLoading:h}=RO({enabled:i===`mesh-session-options`&&!!a&&!!o,environment:r,integrationId:t?.integrationId,accessTokens:l}),{getStoredMeshAccessTokensForIntegration:g,clearStoredMeshAccessTokensForIntegration:_,clearStoredMeshUserIdForIntegration:v}=zO(r);return{onrampProps:s,setOnrampProps:c,resolveAccessTokens:u,setAccessTokensForIntegration:d,clearAccessTokensForIntegration:f,meshSessionAccountBalanceUsd:p,meshSessionAccountBalanceUsdDisplay:m,isLoadingMeshSessionAccountBalanceUsd:h,getStoredMeshAccessTokensForIntegration:g,clearStoredMeshAccessTokensForIntegration:_,clearStoredMeshUserIdForIntegration:v}}function HO(e){let{meshEnvironment:t,trailsApiKey:n,trailsApiUrl:r,selectedToken:i,selectedMeshExchange:a,selectedMeshAccessTokens:o,onrampProps:c,onrampClient:l,navigate:u,address:d,setError:f,setOnrampProps:p,setSelectedFundMethod:m,setSelectedMeshExchange:h,clearSelectedMeshAccessTokens:g,replaceSelectedMeshAccessTokens:_,resolveAccessTokens:v,setAccessTokensForIntegration:y,clearAccessTokensForIntegration:b,getStoredMeshAccessTokensForIntegration:x,clearStoredMeshAccessTokensForIntegration:S,clearStoredMeshUserIdForIntegration:C,clearSelectedToken:w,setSellAmount:T,setBuyAmount:E,setPrepareSendQuote:D,onCompleteNonAuthOnramp:O}=e,k=K(()=>{w(),T(``),E(``),D(null)},[w,E,D,T]),A=K(e=>{m(`onramp-mesh`),h(e);let t=v(e)??[],n=x(e.integrationId),r=t.length>0?t:n;if(_(r),n.length>0&&t.length===0&&y(e.integrationId,n),r.length>0){u(`mesh-session-options`,{backTarget:`mesh-exchanges`});return}u(`mesh-exchange-confirmation`,{backTarget:`mesh-exchanges`})},[x,u,_,v,y,m,h]),j=K(async()=>{let e=a;if(!e){f(`No exchange selected`);return}if(i&&i.chainId!==void 0&&n&&r)try{((await l.getMeshSupportedTokens({environment:t,integrationId:e.integrationId,chainIds:[i.chainId.toString()]})).tokens||[]).some(e=>Number(e.chainId)===i.chainId&&e.symbol?.toUpperCase()===i.symbol?.toUpperCase())||k()}catch(e){s.console.warn(`[trails-sdk] Failed to validate Mesh exchange token support, clearing selected token:`,e),k()}let o=v(e)??[],c=x(e.integrationId),m=o.length>0?o:c;if(_(m),c.length>0&&o.length===0&&y(e.integrationId,c),!d){f(`Connect a wallet before linking an exchange account`);return}if(m.length>0){u(`mesh-session-options`,{backTarget:`mesh-exchange-confirmation`});return}p({authOnly:!0,toRecipientAddress:d}),u(`onramp-mesh`,{backTarget:`mesh-exchange-confirmation`})},[d,k,x,t,u,l,_,v,a,i,y,f,p,n,r]),M=J(()=>{let e=a,t=(v(e||void 0)??o)?.[0];return{resolvedSelectedExchange:e,connectedAccountLabel:t?.accountName||`Connected account`,connectedBrokerName:t?.brokerName||e?.exchangeName||`Exchange`,connectedBrokerImageUrl:e?.imageUrl,connectedBrokerExchangeKey:e?.exchangeKey}},[v,o,a]),N=K(()=>{p(null),u(`fund-form`,{backTarget:`mesh-exchanges`})},[u,p]),P=K(()=>{let e=M.resolvedSelectedExchange?.integrationId;if(!e){f(`No exchange selected`);return}if(S(e),C(e),g(),b(e),!d){f(`Connect a wallet before linking an exchange account`);return}p({authOnly:!0,toRecipientAddress:d,selectedExchange:M.resolvedSelectedExchange||void 0}),u(`onramp-mesh`,{backTarget:`mesh-exchanges`})},[d,b,g,S,C,u,M.resolvedSelectedExchange,f,p]),F=J(()=>{let e=c?.selectedExchange||a||void 0;return{resolvedSelectedExchange:e,resolvedAccessTokens:v(e)}},[c?.selectedExchange,v,a]);return{handleMeshExchangeSelect:A,handleMeshExchangeContinue:j,sessionViewModel:M,handleMeshSessionContinue:N,handleMeshSessionLogout:P,onrampSelection:F,handleMeshOnrampComplete:K(e=>{if(c?.authOnly){let t=e;F.resolvedSelectedExchange?.integrationId&&t.accessTokens&&t.accessTokens.length>0&&(_(t.accessTokens),y(F.resolvedSelectedExchange.integrationId,t.accessTokens)),p(null),u(`fund-form`,{backTarget:`mesh-exchanges`});return}O(e)},[u,O,c?.authOnly,F.resolvedSelectedExchange,_,y,p]),handleMeshOnrampError:K(e=>{s.console.error(`[trails-sdk] Onramp error:`,e);let t=String(e||``).toLowerCase();(t.includes(`token expired`)||t.includes(`expired token`)||t.includes(`access token expired`)||t.includes(`unable to initiate transfer`))&&!c?.authOnly&&F.resolvedSelectedExchange?.integrationId&&(S(F.resolvedSelectedExchange.integrationId),C(F.resolvedSelectedExchange.integrationId),g(),b(F.resolvedSelectedExchange.integrationId),p({authOnly:!0,toRecipientAddress:d||c?.toRecipientAddress,selectedExchange:F.resolvedSelectedExchange}))},[d,b,g,S,C,c?.authOnly,c?.toRecipientAddress,F.resolvedSelectedExchange,p])}}function UO(e){return e?`accounts`in e?e.activeAccount?.namespace===`eip155`?e.activeAccount.address:e.accounts.find(e=>e.namespace===`eip155`)?.address??null:e.address??null:null}function WO(e){if(e)return`namespace`in e?e.namespace:void 0}const GO=pr(()=>import(`./BluvoExchangeSelection.lazy-D6ynQVSb.js`)),KO=pr(()=>import(`./BluvoOnrampFlow.lazy-BcDqhGLi.js`)),qO=fr((e,t)=>{let{toAddress:n,toAmount:r,toChainId:i,toToken:c,defaultToChainId:l,defaultToToken:d,toCalldata:f,fromToken:p,fromChainId:m,fromAmount:h,fromAccount:g,children:_,renderInline:y=!1,onOriginConfirmation:b,onDestinationConfirmation:x,onStart:S,onQuote:C,onSignRequest:w,onSign:E,onSignReject:D,onApproveRequest:O,onApprove:k,onApproveReject:A,onSuccess:j,onError:M,onStatus:N,onOpen:P,onClose:I,buttonText:ee,swapProvider:te,bridgeProvider:ne,swapProviderFallback:re,bridgeProviderFallback:ie,priceImpactWarningThresholdBps:L,priceImpactWarningMessage:R,priceImpactFallbackBridgeUrl:ae,defaultInputMode:z,fundMethod:B,fundTradeType:V,exchangeProvider:H,fundOptions:se}=wo(),ce=Zr(),U=Lr(ce),le=qr()?.connector,ue=ce.activeAccount?.address,de=ce.activeAccount?.chainId,{trailsApiKey:fe,trailsApiUrl:pe}=Vx(),me=Ao(),he=qu(),ge=Oo(),_e=Ia(),ve=gv(),ye=J(()=>la(),[]),be=$r(),Se=li(),Ce=J(()=>Se.filter(e=>e.namespace===`eip155`),[Se]),{connect:we,disconnect:Te,switchAccount:Ee}=ai(),De=Ce.some(Rr),Oe=(ge===`adapter`||ge===`parent`)&&!U&&!De;q(()=>{Oe&&s.console.warn(`[trails-sdk] No widget-selectable wallet options are available while disconnected. The widget will stay mounted and the wallet list will show setup guidance. Common fix: add WalletConnect or explicit wallet descriptors instead of exposing only a generic injected connector.`)},[Oe]);let{recentTokens:Ae,addRecentToken:je}=mx(ue),{selectedToken:Me,setSelectedToken:Ne,clearSelectedToken:Fe,availableOriginTokensError:Ie}=ul(),{selectedToken:Le,availableDestinationTokensError:ze}=xl(),{onramp:Be}=wo(),Ve=uy(Be),He=typeof Be==`function`?Be:Ve?ly({config:Ve}):void 0,Ue=Ve?.mesh?.environment??`production`,We=Ve?.bluvo?.environment??`production`,{isModalOpen:Ge,openModal:Ke,closeModal:qe,setHandleCloseModal:Je,pendingSelection:Ye,setPendingSelection:Xe,hostTransactionState:Ze,setHostTransactionState:Qe,hostTransactionQuote:$e,hostTransactionStates:et,hostTransactionTimestamp:tt,resetHostTransactionState:nt,receiptActionButtonText:rt,onReceiptAction:it,retryTransactionRef:at}=wx(),{createWidgetSession:ot}=AE();US({address:ue,chainId:de,connectorName:le?.name,isEvmConnected:U}),ii({onDisconnect(){s.console.log(`[trails-sdk] [TrailsWidget] account disconnected via useAccountEffect`),s.console.log(`[trails-sdk] [TrailsWidget] window.ethereum exists:`,`ethereum`in window)},onConnect(e){s.console.log(`[trails-sdk] [TrailsWidget] account connected via useAccountEffect`,e)}});let st=Y(!1);q(()=>{if(st.current||!g||!ce.connections.length)return;if(ue&&Pe(ue,g)){st.current=!0;return}let e=ce.connections.find(e=>e.accounts.some(e=>Pe(e.address,g)));e?(s.console.log(`[trails-sdk] [TrailsWidget] Switching to fromAccount:`,g,`via connection:`,e.walletName),Ee(e.id,g),st.current=!0):s.console.log(`[trails-sdk] [TrailsWidget] fromAccount not found in connected wallets:`,g)},[g,ce.connections,ue,Ee]),q(()=>{s.console.log(`[trails-sdk] [TrailsWidget] isModalOpen changed:`,Ge)},[Ge]);let{mode:ct,configuredMode:lt,resetMode:ut,screen:dt,navigate:G,goBack:ft,goHome:pt,canGoBack:mt,backScreen:ht,state:gt}=y_(),{setSellAmount:_t,setBuyAmount:vt}=d_();b_(({from:e,to:t})=>{PO(e,t)&&($a.abortAll(),sn(null)),t===`fund-methods`&&(Ht.current=jt)});let{connectionContext:yt,clearConnectionContext:xt,isRecipientSelection:Ct,isFundMethodSelection:wt}=$o(),{setSelectedRecipient:Tt}=cu(),Et=Nt(101),Dt=Y(!!he?.connected),Ot=()=>{nn(null),wn(!1),mt?ft():pt()},[kt,At]=X(ue),{selectedFundMethod:jt,selectedMeshExchange:Mt,selectedMeshAccessTokens:Pt,selectedBluvoExchange:Ft,clearSelectedBluvoFunding:It,replaceSelectedMeshAccessTokens:Lt,clearSelectedMeshAccessTokens:Rt,setSelectedFundMethod:zt,setSelectedMeshExchange:Bt,setSelectedBluvoExchange:Vt}=eD(),Ht=Y(jt),Ut=K(e=>{let t=Ht.current;DO(t,e,{clearSelectedToken:Fe,setSellAmount:_t,setBuyAmount:vt,setPrepareSendQuote:sn,setSelectedMeshExchange:Bt,setSelectedBluvoExchange:Vt,setSelectedMeshAccessTokens:()=>Rt(),clearSelectedBluvoFunding:It})&&(Ht.current=e)},[Fe,_t,vt,Bt,Vt,Rt,It]),{selectedPool:Wt,setSelectedPool:Gt}=zd(),Kt=(ge===`builtin-evm`?Fa(_e):[])[0]??_e.activeWalletId??null,[qt,Jt]=X(Kt);q(()=>{let e=ce.activeConnection?.walletId??Kt;e&&Jt(t=>t??e)},[Kt,ce.activeConnection?.walletId]);let[Yt,Xt]=X(!1),[Zt,Qt]=X(!1),[$t,en]=X(void 0),[tn,nn]=X(null),[rn,an]=X(null),[on,sn]=X(null),[cn,ln]=X(null),[un,dn]=X(null),[fn,pn]=X(null),[mn,hn]=X(null);q(()=>{s.console.log(`[widget] externalSessionId state changed to:`,fn)},[fn]);let[gn,_n]=X(null),[vn,yn]=X(null),[bn,xn]=X(!1),[Sn,wn]=X(!1),[Tn,En]=X(null),[Dn,On]=X(null),kn=H??`mesh`,An=Y(null);q(()=>{y||Ge||(An.current=null)},[y,Ge]),q(()=>{if(!(y||Ge)||ct===`swap`)return;let e=null;B===kO.Wallet?e=`wallet`:B===kO.CryptoTransfer?e=`direct-transfer`:B===kO.Onramp&&ct!==`pay`&&ct!==`earn`?e=`onramp-meld`:B===kO.OnrampExchange&&ct!==`pay`&&(e=kn===`bluvo`?`onramp-bluvo`:`onramp-mesh`),e&&jt!==e&&zt(e)},[B,jt,zt,y,Ge,ct,kn]),q(()=>{let e=y||Ge;if(!e||!U||ct!==`fund`)return;if(!B){if(p){let t=`implicit-wallet:${ct}:${e}`;if(An.current===t)return;An.current=t,zt(`wallet`),G(`fund-form`)}return}let t=`${B}:${ct}:${e}`;if(An.current!==t){if(An.current=t,B===kO.Onramp)zt(`onramp-meld`),G(`fund-form`);else if(B===kO.Wallet)zt(`wallet`),G(p?`fund-form`:`tokens`);else if(B===kO.CryptoTransfer)zt(`direct-transfer`),G(`fund-form`);else if(B===kO.OnrampExchange)if(kn===`bluvo`)zt(`onramp-bluvo`),G(`onramp-bluvo`);else{zt(`onramp-mesh`);let e=se?.meshExchangeKey;e?(Bt({integrationId:e,exchangeKey:e,exchangeName:e,imageUrl:void 0}),G(`fund-form`)):G(`mesh-exchanges`)}}},[ct,U,B,p,se?.meshExchangeKey,y,Ge,G,kn,zt,Bt]),q(()=>{!U||dt!==`connect`||ct===`fund`&&B||pt()},[U,dt,ct,B,pt]);let jn=Y(!1);q(()=>{jn.current||h&&(jn.current=!0,_t(String(h)))},[h,_t]),x_(NO(U,dt),`connect`),q(()=>{let e=Dt.current,t=!!he?.connected;if(Dt.current=t,!e||t)return;let n=Me?.chainId;ct===`fund`&&dt===`fund-form`&&jt===`wallet`&&typeof n==`number`&&W(n)&&(s.console.log(`[trails-sdk] Solana wallet disconnected during fund form, returning to fund methods`),G(`fund-methods`))},[ct,G,dt,jt,Me?.chainId,he?.connected]);let Mn={fund:`Fund`,swap:`Swap`,earn:`Earn`,pay:`Pay`,withdraw:`Withdraw`}[ct]??`Pay`,Nn=J(()=>{let e=Ts(r),t=Es(i),a=OO(c),o=ru(n??``,i);if(!e)return s.console.error(`[trails-sdk] Invalid toAmount prop: must be numeric. Received:`,r),`Invalid toAmount: must be a numeric value`;if(!t)return s.console.error(`[trails-sdk] Invalid toChainId prop: must be numeric. Received:`,i),`Invalid toChainId: must be a numeric value`;if(!a)return s.console.error(`[trails-sdk] Invalid toToken prop: must be a valid token symbol or a valid hex address. Received:`,c),`Invalid toToken: must be a valid token symbol or a valid hex address`;if(!o)return s.console.error(`[trails-sdk] Invalid toAddress prop: must be a valid EVM or Solana address. Received:`,n),iu(n??``,i)??`Recipient is not a valid wallet address`;if(ct===`pay`){if(d||l)return`defaultToToken and defaultToChainId are not supported in pay mode`;if(!c)return`toToken is required in pay mode`}return ct===`fund`&&r?`toAmount is not allowed in fund mode`:null},[r,i,c,d,ct,n,l])||Ie||ze||tn,{data:Pn}=si(),Fn=K(e=>{Jt(e)},[]),In=K(()=>{Fe(),_t(``),vt(``),sn(null),Bt(null),Rt(),Ht.current=`wallet`,zt(`wallet`);let e=Et?.getOriginTokens()[0]??null;e&&Ne(e),ct===`fund`?G(`fund-form`,{backTarget:`fund-methods`}):pt()},[Rt,Fe,ct,pt,G,vt,zt,Bt,Ne,_t,Et]),Ln=K(async e=>{if(he?.connect){nn(null),Qt(!1),Xt(!0),G(`wallet-connection-pending`,{backTarget:`connect`,data:{connectionType:`solana`,walletIcon:e.icon,walletId:e.id,walletName:e.name}});try{await Promise.resolve(he.connect(e.id)),Xt(!1),U?In():G(`connect`)}catch(t){s.console.error(`[trails-sdk] Error connecting Solana wallet`,t);let n=uO(t,{...e,namespace:`solana`});an(n),Xt(!1),Qt(!0),nn(T(t)||n.message),G(`connect-error`)}}},[U,G,In,he]),{onrampProps:Rn,setOnrampProps:zn,resolveAccessTokens:Bn,setAccessTokensForIntegration:Vn,clearAccessTokensForIntegration:Hn,meshSessionAccountBalanceUsd:Un,meshSessionAccountBalanceUsdDisplay:Wn,isLoadingMeshSessionAccountBalanceUsd:Gn,getStoredMeshAccessTokensForIntegration:Kn,clearStoredMeshAccessTokensForIntegration:qn,clearStoredMeshUserIdForIntegration:Jn}=VO({selectedMeshExchange:Mt,selectedMeshAccessTokens:Pt,meshEnvironment:Ue,screen:dt,trailsApiUrl:pe,trailsApiKey:fe}),[Yn,Xn]=X(null),[Zn,Qn]=X(!1),[$n,er]=X(null),{handleMeshExchangeSelect:tr,handleMeshExchangeContinue:nr,sessionViewModel:rr,handleMeshSessionContinue:ir,handleMeshSessionLogout:ar,onrampSelection:or,handleMeshOnrampComplete:sr,handleMeshOnrampError:cr}=HO({meshEnvironment:Ue,trailsApiKey:fe,trailsApiUrl:pe,selectedToken:Me,selectedMeshExchange:Mt,selectedMeshAccessTokens:Pt,onrampProps:Rn,onrampClient:ve,navigate:G,address:ue,setError:nn,setOnrampProps:zn,setSelectedFundMethod:zt,setSelectedMeshExchange:Bt,clearSelectedMeshAccessTokens:Rt,replaceSelectedMeshAccessTokens:Lt,resolveAccessTokens:Bn,setAccessTokensForIntegration:Vn,clearAccessTokensForIntegration:Hn,getStoredMeshAccessTokensForIntegration:Kn,clearStoredMeshAccessTokensForIntegration:qn,clearStoredMeshUserIdForIntegration:Jn,clearSelectedToken:Fe,setSellAmount:_t,setBuyAmount:vt,setPrepareSendQuote:sn,onCompleteNonAuthOnramp:e=>{Xr(e)}});((e,t,n,r)=>{let{data:i,loading:a}=qS({enabled:e===`earn`});return q(()=>{if(e===`earn`&&t&&n&&r&&i&&i.length>0&&(!Wt||Wt.chainId!==n||!Pe(Wt.token.address,r)&&Wt.token.symbol.toLowerCase()!==r.toLowerCase())){let a=typeof n==`string`?parseInt(n,10):n,o=i.find(e=>{let n=Pe(e.depositAddress,t),i=e.chainId===a,o=r.startsWith(`0x`)?Pe(e.token.address,r):e.token.symbol.toLowerCase()===r.toLowerCase();return!o&&e.protocol.toLowerCase()===`aave`&&(bt(r)||r===`ETH`)&&(o=e.token.symbol===`WETH`||e.token.address.toLowerCase()===Re(a)?.toLowerCase(),n||(n=e.wrappedTokenGatewayAddress?.toLowerCase()===St(t))),n&&i&&o});o?(s.console.log(`[trails-sdk] Auto-selected pool for ${e} mode toAddress:`,t,`toChainId:`,a,`toToken:`,r,o),Gt(o)):s._enabled&&s.console.log(`[trails-sdk] No matching pool found for ${e} mode toAddress:`,t,`toChainId:`,a,`toToken:`,r,`available pools:`,i.map(e=>({depositAddress:e.depositAddress,tokenAddress:e.token.address,tokenSymbol:e.token.symbol,chainId:e.chainId,protocol:e.protocol})))}},[e,t,n,r,i]),{poolsLoading:a}})(ct,n,i,c);let{setOriginTxHash:ur,setDestinationTxHash:dr,setDestinationChainId:fr,setOriginChainId:pr,transactionStates:mr,setTransactionStates:hr}=TO(b,x,Yr),gr=$e??on,_r=et.length>0?et:mr,yr=J(()=>Ze.status!==`success`||!tt?null:Math.max(0,xe(ke(tt))),[Ze.status,tt])??Dn,br=Cb(_r);x_(dt===`pending`&&br,`receipt`);let{checkoutOnHandlers:xr}=CO({onStart:S,onQuote:C,onSignatureRequest:w,onSignatureConfirmed:E,onSignatureRejected:D,onApprovalRequest:O,onApprovalConfirmed:k,onApprovalRejected:A,onComplete:j,onError:M,onStatusUpdate:N}),{clearSelectedFeeOption:Sr}=Yl();EO({enabled:_p(jt)&&!!gr?.intentId&&(dt===`direct-transfer-screen`||dt===`onramp-confirmation`||dt===`pending`),intentId:gr?.intentId??void 0,fallbackTransactionStates:gr?.transactionStates,setTransactionStates:hr,onStatusUpdate:xr?.triggerCheckoutStatusUpdate,onFundingObserved:()=>{(dt===`direct-transfer-screen`||dt===`onramp-confirmation`)&&G(`pending`)}});let{handleDebugScreenSelect:Cr}=wO({setSelectedToken:Ne,setTransactionStates:hr,setPrepareSendQuote:sn,setShowWalletConfirmRetry:xn,setError:nn,isEvmConnected:U}),wr=ct===`fund`?`fund-form`:`send-form`;x_(!!Wt&&(dt===`send-form`||dt===`fund-form`)&&dt!==wr,wr),q(()=>{let e=Ze.status;if(e!==`idle`)switch(Ge||Ke(),e){case`awaiting-origin`:G(`select-origin-token`);break;case`awaiting-amount`:G(`select-origin-amount`);break;case`quoting`:case`confirmation`:G(`wallet-confirmation`);break;case`pending`:G(`pending`);break;case`success`:case`error`:et.length>0?G(`receipt`):G(`pending`);break;default:G(`pending`);break}},[Ze.status,et.length,Ge,Ke,G]),q(()=>{if(kt&&ue&&kt!==ue){s.console.log(`[trails-sdk] Account changed from`,kt,`to`,ue);try{localStorage.removeItem(`trails-fee-option-preference`)}catch{}if([`send-form`,`fund-form`,`swap`,`withdraw`,`wallet-confirmation`,`earn`].includes(dt)){if(s.console.log(`[trails-sdk] Resetting to tokens screen due to account change`,dt),!gt.stack.some(e=>e.screen===`select-funding-wallet`)){let e=f_(ct);G(e),Fe()}nn(null),sn(null),xn(!1),wn(!1)}}At(ue)},[ue,kt,dt,ct,Fe,G,gt.stack]),q(()=>{Wt&&ct===`earn`&&$t&&s.console.log(`Earn mode: Pool selected, calldata ready for amount updates`)},[Wt,ct,$t]);let Tr=async e=>{try{nn(null),Xt(!0);let t=Ce.find(t=>t.id===e);if(!t){nn(`No wallet option available for wallet: ${e}`),Xt(!1);return}let n=t.name;if(s.console.log(`[trails-sdk] Initiating connection to wallet`,e,t.flow),t.flow!==`walletconnect`){let t=ce.activeConnection;s.console.log(`[trails-sdk] Initiating connection to walletId`,e);let r=await we(e);if(s.console.log(`[trails-sdk] Successfully connected to ${n}`,r),Fn(e),Ct){let e=UO(r);if(s.console.log(`[trails-sdk] Connected wallet for recipient selection, setting as recipient:`,e),e&&Tt(e),t?.id)try{s.console.log(`[trails-sdk] Switching back to original active wallet:`,t.activeAccount?.address),Ee(t.id,t.activeAccount?.address)}catch(e){s.console.error(`[trails-sdk] Failed to switch back to original wallet:`,e)}xt();let n=yt.originScreen;G(n||`recipients`)}else wt?(s.console.log(`[trails-sdk] Wallet connected from funding flow, selecting as fund method`),zt(`wallet`),xt(),ct===`fund`?G(`tokens`):pt()):(s.console.log(`[trails-sdk] Normal wallet connection, switching active wallet`),xt(),s.console.log(`[trails-sdk] Wallet connected, going home`),pt())}else{ce.activeConnection&&ce.activeConnection.walletId!==`walletconnect`&&yn({address:ce.activeConnection.activeAccount?.address,connectionId:ce.activeConnection.id,walletId:ce.activeConnection.walletId}),G(`wallet-connect`),Xt(!1);return}Xt(!1)}catch(t){s.console.error(`[trails-sdk] Failed to connect:`,t);let n=uO(t,Ce.find(t=>t.id===e));an(n),nn(n.message),Qt(!0),Xt(!1),G(`connect-error`)}};K(e=>{if(e.namespace===`solana`){let t=he?.availableWallets?.find(t=>t.walletId===e.id);if(t){Ln({id:t.walletId,name:t.walletName,icon:t.walletIcon});return}nn(null),Xt(!0),G(`wallet-connection-pending`,{backTarget:`connect`,data:{connectionType:`solana`,walletIcon:e.icon,walletId:e.id,walletName:e.name}}),we(e.id).then(()=>{Xt(!1),U?In():G(`connect`)}).catch(t=>{let n=uO(t,e);an(n),nn(n.message),Qt(!0),Xt(!1),G(`connect-error`)});return}Fn(e.id);let t=Ce.find(t=>t.id===e.id);if(me&&t?.flow===`walletconnect`){G(`wallet-connect`);return}let n=ht;G(`wallet-connection-pending`,{backTarget:(n===`wallet-confirmation`?void 0:n)||void 0}),setTimeout(()=>{Tr(e.id)},100)},[ht,Ce,we,Ln,U,G,In,he?.availableWallets,me,Fn]);let Er=async()=>{nn(null);try{s.console.log(`[trails-sdk] Disconnecting all connected wallets:`,ce.connections.length),await Te(),await he?.disconnect?.()}catch(e){s.console.error(`[trails-sdk] Failed to disconnect:`,e)}G(`connect`)},Dr=K(e=>{if(!Ct||!e)return;let t=Me?.chainId??(m==null?void 0:Number(m)),n=Le?.chainId??(i==null?void 0:Number(i))??(l==null?void 0:Number(l)),r=t!=null&&W(t),a=n!=null&&W(n);if(e===`solana`)return r?`Solana-to-Solana transfers are not supported`:ct!==`swap`&&!a?`Solana recipients are only available when the destination is Solana`:void 0;if(ct!==`swap`&&a)return`Recipient must be a Solana address when the destination is Solana`},[ct,l,m,Ct,Le?.chainId,Me?.chainId,i]),Or=K(e=>{let t=e.namespace??(e.ecosystem===`solana`?`solana`:`eip155`);return Dr(t)},[Dr]),kr=async e=>{if(Ct){s.console.log(`[trails-sdk] WalletConnect completed for recipient selection, setting as recipient:`,UO(e)??ue);let t=UO(e)??(WO(e)===`solana`?he?.publicKey?.toBase58():null),n=WO(e),r=Dr(n);t&&!r?Tt(t):r?nn(r):n===`solana`?nn(`Solana wallet connected, but no Solana address was returned.`):ue&&Tt(ue);let i=yt.originalActiveConnectionId,a=yt.originalActiveWalletAddress;if(i&&a)try{s.console.log(`[trails-sdk] Switching back to original active wallet after WalletConnect:`,a),Ee(i,a)}catch(e){s.console.error(`[trails-sdk] Failed to switch back to original wallet after WalletConnect:`,e)}xt();let o=yt.originScreen;G(o||`recipients`)}else if(wt)s.console.log(`[trails-sdk] WalletConnect completed from funding flow, selecting as fund method`),xt(),WO(e)===`solana`?U?In():G(`connect`):(zt(`wallet`),ct===`fund`?G(`tokens`):pt());else{if(WO(e)===`solana`){U?In():G(`connect`);return}zt(`wallet`),Me?.chainId&&W(Me.chainId)&&(Fe(),_t(``),vt(``),sn(null));let t=FO({currentMode:ct,hasFromToken:!!p,selectedFundMethod:`wallet`});G(t.screen,t.options)}},Ar=e=>{try{if(nn(null),Ne(e),Ye){if(Ye.requireAmountInput){Qe(e=>({...e,status:`awaiting-amount`})),Mr(e);return}let t=e.contractAddress||Cn,n=e.chainId??0;try{Ye.resolve({fromTokenAddress:t,fromChainId:n})}catch(e){s.console.error(`[trails-sdk] Error resolving pending selection:`,e),Ye.reject(e)}finally{Xe(void 0)}Mr(e);return}G(ct===`earn`?n&&i||Wt?`send-form`:`earn-pools`:ct===`swap`?`swap`:ct===`fund`?`fund-form`:`send-form`),Mr(e)}catch(e){nn(e instanceof Error?e.message:`An unknown error occurred`)}},jr=e=>{Ar(e)},Mr=e=>{let t=$(e.chainId),n=e.decimals||18,r={symbol:e.symbol,name:e.name,decimals:n,contractAddress:e.contractAddress,tokenId:`${e.symbol}-${t?.name||e.chainId}`,chainId:e.chainId,chainName:t?.name||`Chain ${e.chainId}`,imageUrl:e.imageUrl};je(r)},Nr=e=>{if(Ye&&Me)try{Ye.resolve({fromTokenAddress:Me.contractAddress||Cn,fromChainId:Me.chainId??0,fromAmount:e}),Xe(void 0)}catch(e){s.console.error(`[trails-sdk] Error resolving pending selection amount:`,e),Ye.reject(e),Xe(void 0)}},Pr=async(e,t)=>{if(s.console.log(`[trails-sdk] handleOnSend`,e,t),Ye&&Me)try{let t=e;Ye.resolve({fromTokenAddress:Me.contractAddress||Cn,fromChainId:Me.chainId??0,fromAmount:t}),Xe(void 0);return}catch(e){s.console.error(`[trails-sdk] Error resolving pending selection:`,e),Ye&&(Ye.reject(e),Xe(void 0));return}return Promise.resolve()},Fr=()=>{$a.abortAll(),Lh(),Ir()},Ir=K(()=>{nn(null),zt(`wallet`),Gt(null),Jt(null),Xt(!1),Qt(!1),en(void 0),ur(``),pr(null),dr(``),fr(null),hr([]),sn(null),On(null),Sr(),nt(),pt()},[zt,dr,fr,hr,ur,pr,Gt,pt,Sr,nt]);q(()=>{Ye&&(Ge||Ke(),dt!==`select-origin-token`&&G(`select-origin-token`))},[Ye,Ge,dt,G,Ke]);let zr=Y(P);zr.current=P;let Br=Y(I);Br.current=I;let Vr=Y(Ye);Vr.current=Ye;let Hr=Y(on);Hr.current=on;let Ur=Y(dt);Ur.current=dt;let Wr=K(()=>{Vr.current||Ir(),Ke(),zr.current?.()},[Ke,Ir]),Gr=K(()=>{let e=Vr.current;e?(s.console.log(`[trails-sdk] handleCloseModal called, rejecting pending selection`),e.reject(Error(`Modal closed by user`)),Xe(void 0)):s.console.log(`[trails-sdk] handleCloseModal called, no pending selection`),s.console.log(`[trails-sdk] handleCloseModal called, closing modal`),$a.abortAll(),qe(),Ir(),nt(),Br.current?.()},[qe,Ir,nt,Xe]);q(()=>(Je(Gr),()=>{Je(null)}),[Gr,Je]),q(()=>()=>{$a.abortAll()},[]),vr(t,()=>({openModal:Wr,closeModal:Gr,isModalOpen:Ge}),[Ge,Wr,Gr]);let Kr=K(()=>{nn(null),G(`pending`)},[G]);function Jr(e=0){On(e)}function Yr({transactionStates:e}){s.console.log(`[trails-sdk] handleTransferComplete called`,e),nn(null);let t=e[0],n=e[e.length-1];t?.transactionHash&&t?.chainId&&(ur(t.transactionHash),pr(t.chainId)),(n?.transactionHash||n?.txnHash&&n?.chainId)&&(dr(n?.transactionHash||n?.txnHash||``),fr(n?.chainId)),G(`receipt`)}async function Xr(e){if(s.console.log(`[trails-sdk] Onramp transfer completed:`,e),s.console.log(`[trails-sdk] Using real transaction states from prepareSendQuote`),s.console.log(`[trails-sdk] handleOnrampComplete state:`,{hasOnrampContinueSend:!!Yn,hasPrepareSendQuote:!!gr,screen:dt,onrampContinueSendInProgress:Zn}),s.console.log(`[CACHE-FLOW] Onramp completed, invalidating token balances cache`),Lh(),Zn){s.console.warn(`[trails-sdk] onrampContinueSend already in progress, ignoring duplicate call`);return}if(s.console.log(`[trails-sdk] Navigating away from onramp screen`),G(`pending`),Yn){s.console.log(`[trails-sdk] Continuing send flow after onramp completion`),Qn(!0);try{await Yn(),s.console.log(`[trails-sdk] onrampContinueSend completed successfully`)}catch(e){s.console.error(`[trails-sdk] Error continuing send after onramp:`,e),ni(e)}finally{Xn(null),Qn(!1)}}else s.console.log(`[trails-sdk] No onrampContinueSend callback, showing pending screen`),gr&&(s.console.log(`[trails-sdk] Setting transaction states from prepareSendQuote`),hr(gr.transactionStates))}function Qr(e){s.console.log(`[trails-sdk] transactionStates from widget`,e),hr([...e])}let ei=()=>{me&&(ce.activeConnection&&ce.activeConnection.walletId!==`walletconnect`&&yn({address:ce.activeConnection.activeAccount?.address,connectionId:ce.activeConnection.id,walletId:ce.activeConnection.walletId}),Jt(null),G(`wallet-connect`))},ti=(e,t)=>{try{if(s.console.log(`Generating deposit calldata for ${e.protocol} pool:`,e.name),!Pn)throw Error(`Wallet client not found`);switch(e.protocol.toLowerCase()){case`aave`:return JS(Pn,e,t);case`morpho`:return YS(Pn,t);default:s.console.warn(`Unsupported protocol: ${e.protocol}`);return}}catch(e){s.console.error(`Error generating deposit calldata:`,e);return}},ni=e=>{e&&s.console.error(`[trails-sdk] Error sending transaction`,e);let t=o(e),n=a(e),r=F(e),i=u(e),c=v(e);oe(e)||(t===`quote-expired`?(nn(null),xn(!1),wn(!0)):r?(wn(!1),xn(!0)):i||c?(wn(!1),xn(!0),nn(n)):(wn(!1),nn(n)))},ri=e=>{e&&s.console.error(`[trails-sdk] Error selecting token`,e),nn(e instanceof Error?e.message:e)},oi=(e,t)=>{if(xn(!1),wn(!1),sn(e??null),jt===`direct-transfer`){if(!t){ni(`Unable to continue: direct-transfer send function is missing.`);return}nn(null),(async()=>{try{await t(),G(`direct-transfer-screen`,{backTarget:dt})}catch(e){ni(e)}})();return}jt===`onramp-mesh`||jt===`onramp-bluvo`||G(`wallet-confirmation`)},ci=(e,t,n,r,i)=>{s.console.log(`[trails-sdk] handleWaitingOnrampConfirm called with sessionId:`,r),sn(e??null),ln(t??null),hn(i??null),n&&dn(n),r?(s.console.log(`[trails-sdk] Using provided sessionId:`,r),pn(r)):(s.console.error(`[trails-sdk] No sessionId provided - this should never happen for onramp flows`),pn(null)),G(`onramp-confirmation`)};async function ui(){if(Tn)try{nn(null),xn(!1),wn(!1),await Tn()}catch(e){s.console.error(`[trails-sdk] Error retrying wallet confirmation`,e)}}let{targetAmountUsd:di,targetAmountUsdFormatted:fi}=KT(),pi=Ce.find(e=>e.flow===`walletconnect`)?.id??`walletconnect`,mi=[`connect`,`wallet-list`,`connect-all-wallets`,`connect-wallet-variants`,`wallet-connect`,`connect-error`,`wallet-connection-pending`].includes(dt),hi=()=>{let e=dt===`wallet-connection-pending`?gt.screenData:null,t=e?.walletId??qt??`metamask`,a=e?.errorMessage?uO(Error(e.errorMessage),{icon:e.walletIcon,id:t,name:e.walletName,namespace:e.connectionType===`solana`?`solana`:`eip155`}):rn;switch(dt){case`connect`:case`wallet-list`:case`connect-all-wallets`:case`connect-wallet-variants`:case`wallet-connect`:case`connect-error`:case`wallet-connection-pending`:return Z(SO,{hideBackButton:!U,initialView:dt===`wallet-connect`?`walletconnect`:dt===`wallet-connection-pending`?`pending`:dt===`connect-error`?`error`:`list`,initialError:a,initialIsConnecting:dt===`wallet-connection-pending`?!e?.errorMessage:void 0,initialPendingWallet:dt===`wallet-connection-pending`?{connectionType:e?.connectionType??`evm`,icon:e?.walletIcon,id:t,name:e?.walletName}:void 0,initialWalletId:dt===`wallet-connect`?pi:void 0,getWalletDisabledReason:Or,onBack:Ot,onClose:Gr,onConnected:e=>{`walletId`in e&&e.walletId&&Fn(e.walletId),kr(e)},onError:e=>{an(e)}},gt.stack.at(-1)?.key??dt);case`fund-methods`:return Z(gD,{headerContent:ct===`pay`||ct===`earn`?`Choose a payment method`:`Choose a funding method`,onBack:()=>{if(ct!==lt){ut();return}if(mt){ft();return}pt()},onramp:He,onSelectWalletConnect:ei,onSelectConnectedAccount:()=>{Me&&W(Me.chainId??0)&&(Fe(),_t(``),vt(``),sn(null),Bt(null)),Ut(`wallet`),zt(`wallet`),ct===`fund`?p?G(`fund-form`,{backTarget:`fund-methods`}):G(`tokens`):pt()},onSelectTransferCrypto:()=>{Ut(`direct-transfer`),zt(`direct-transfer`),ei()},onSelectOnrampMeld:()=>{Ut(`onramp-meld`),ct===`fund`?G(`fund-form`):pt()},onSelectOnrampExchange:()=>{Fe(),_t(``),vt(``),sn(null),Bt(null),Vt(null),It();let e=kn===`bluvo`?`onramp-bluvo`:`onramp-mesh`;Ut(e),zt(e),ct===`fund`?G(kn===`bluvo`?`onramp-bluvo`:`mesh-exchanges`):pt()}});case`mesh-exchanges`:return Z(_D,{onBack:()=>G(`fund-methods`),onSelectExchange:tr});case`mesh-exchange-confirmation`:return Z(vD,{exchangeName:Mt?.exchangeName,exchangeKey:Mt?.exchangeKey,exchangeImageUrl:Mt?.imageUrl,onBack:Ot,onContinue:()=>{nr()}});case`mesh-session-options`:return Z(yD,{connectedBrokerName:rr.connectedBrokerName,connectedBrokerImageUrl:rr.connectedBrokerImageUrl,connectedBrokerExchangeKey:rr.connectedBrokerExchangeKey,connectedAccountLabel:rr.connectedAccountLabel,isLoadingBalance:Gn,balanceUsd:Un,balanceUsdDisplay:Wn,onBack:Ot,onContinue:ir,onLogout:ar});case`payment-methods`:return Z(AO,{onBack:()=>pt(),onSelectWalletConnect:ei,onSelectConnectedAccount:()=>{Ut(`wallet`),zt(`wallet`),pt()},onSelectQrCode:()=>{G(`qrcode-options`,{backTarget:`payment-methods`})}});case`select-funding-wallet`:return Z(lO,{});case`onramp-payment-methods`:return Z(CD,{onBack:()=>G(`fund-methods`)});case`qrcode-options`:return Z(LD,{onBack:Ot,onSelectWalletConnect:ei,onSelectQRCode:()=>{Ut(`direct-transfer`),zt(`direct-transfer`),ct===`fund`?G(`fund-form`):pt()}});case`tokens`:return Z(db,{onContinue:Ar,onBack:LO(ct)?pt:Ot,targetAmountUsd:di,targetAmountUsdFormatted:fi,onError:ri,recentTokens:Ae,onRecentTokenSelect:jr,fundMethod:IO(jt),renderInline:y,onNavigateToFundMethods:()=>G(`fund-methods`),onNavigateToSwitchWallet:()=>G(`select-funding-wallet`,{backTarget:`tokens`})});case`select-origin-token`:return Z(db,{onContinue:Ar,onBack:Ot,targetAmountUsd:null,targetAmountUsdFormatted:null,onError:ri,recentTokens:Ae,onRecentTokenSelect:jr,fundMethod:null,renderInline:!1});case`select-origin-amount`:return Z(mb,{token:Me,onBack:()=>G(`select-origin-token`),onCancel:Gr,onSubmit:Nr});case`send-form`:return Z(DD,{onBack:void 0,selectedToken:Me,onSend:Pr,onWaitingForWalletConfirm:oi,onConfirm:Kr,onComplete:Yr,account:Pn?.account,toRecipient:Wt?Wt.depositAddress:n||void 0,toAmount:r||void 0,toChainId:Wt?Wt.chainId:i?Number(i):void 0,toToken:Wt?Wt.token.address:c||void 0,toCalldata:Wt?$t:f||void 0,walletClient:Pn??void 0,isSequenceWallet:be,onTransactionStateChange:Qr,onError:ni,setWalletConfirmRetryHandler:En,swapProvider:te,bridgeProvider:ne,swapProviderFallback:re,bridgeProviderFallback:ie,fundMethod:jt,onAmountUpdate:e=>{if(Wt&&ct===`earn`&&e&&e!==``)try{let t=ti(Wt,e);s.console.log(`Updated calldata:`,t,e),en(t)}catch(e){s.console.error(`Error updating calldata:`,e),en(void 0)}else en(void 0)},checkoutOnHandlers:xr,recentTokens:Ae,onRecentTokenSelect:jr,onTrackToken:Mr});case`fund-form`:return Z(sD,{selectedToken:Me,onSend:Pr,onWaitingForWalletConfirm:oi,onrampPropsCallback:zn,screenNavigationCallback:G,onWaitingForOnrampConfirm:ci,onConfirm:Kr,onComplete:Yr,account:Pn?.account,toAmount:r||void 0,toRecipient:n||void 0,toChainId:i?Number(i):void 0,toToken:c||void 0,toCalldata:f||void 0,walletClient:Pn??void 0,isSequenceWallet:be,onTransactionStateChange:Qr,onError:ni,setWalletConfirmRetryHandler:En,swapProvider:te,bridgeProvider:ne,swapProviderFallback:re,bridgeProviderFallback:ie,fundMethod:jt,checkoutOnHandlers:xr,recentTokens:Ae,onRecentTokenSelect:jr,onTrackToken:Mr,tradeType:V,defaultInputMode:z});case`onramp-confirmation`:return Z(ID,{onBack:Ot,onRetry:()=>{G(`fund-form`)},onIntentExecuted:()=>{G(`pending`)},quote:gr,onRampQuote:cn,widgetCreationParams:un,onCreateWidgetSession:ot,externalSessionId:fn,popupWindowRef:mn});case`wallet-confirmation`:{let e=Ze.status!==`idle`,t=e?Ze.retryEnabled??!1:bn;return Z(Rb,{onBack:Ot,retryEnabled:t,expiredQuoteEnabled:!e&&Sn,onRetry:e?()=>{at.current&&(Qe(e=>({...e,retryEnabled:!1})),at.current())}:ui,quote:gr,onRampQuote:cn,originToken:Ze.details?.originToken??Me,isQuoting:Ze.status===`quoting`})}case`qr-code-wallet-select`:return Z(RD,{onBack:Ot,onSelect:e=>{_n(e),G(`direct-transfer-screen`)},selectedWalletId:gn});case`direct-transfer-screen`:return Z(AD,{onBack:()=>{ct===`fund`?G(`fund-form`):pt()},onChangeWallet:()=>G(`qr-code-wallet-select`),quote:gr,selectedWalletId:gn,walletOptions:ye,onIntentExecuted:()=>G(`pending`)});case`pending`:return Z($b,{onElapsedTime:Jr,transactionStates:_r,quote:gr,onRampQuote:cn,fundMethod:jt,timestamp:tt??void 0,onContinue:()=>{s.console.log(`[trails-sdk] onContinue called`),G(`receipt`)}});case`receipt`:{let e=Ze.status!==`idle`;return Z(cx,{onSendAnother:e?it??void 0:Fr,onClose:Gr,renderInline:y,transactionStates:_r,totalCompletionSeconds:yr??void 0,quote:gr,showCloseButton:!1,actionButtonText:e?rt??void 0:void 0,onRampQuote:cn})}case`onramp-mesh`:if(s.console.log(`[trails-sdk] Rendering onramp screen`,{onrampFactory:!!He,onrampProps:Rn}),!He)return Q(`div`,{className:`flex flex-col h-full p-4`,children:[Q(`div`,{className:`flex items-center mb-4`,children:[Z(`button`,{type:`button`,onClick:Ot,className:`flex h-8 w-8 justify-center items-center rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600 mr-2`,title:`Back`,children:`←`}),Z(`h2`,{className:`text-lg font-semibold text-gray-900 dark:text-white`,children:`Exchange Funding`})]}),Z(`div`,{className:`flex-1 flex items-center justify-center`,children:Q(`div`,{className:`text-center p-4 border border-solid border-gray-200 dark:border-gray-700 rounded-lg`,children:[Z(`p`,{className:`text-gray-600 dark:text-gray-400 mb-2`,children:`Exchange funding is not available.`}),Z(`p`,{className:`text-sm text-gray-500 dark:text-gray-500`,children:`Please provide an onramp factory function to enable this feature.`})]})})]});try{return Q(`div`,{className:`flex flex-col h-full`,children:[Z(`div`,{className:`flex-1 min-h-0`,children:He({setCurrentScreen:e=>{G(e)},onComplete:sr,onError:cr,onBack:Ot,authOnly:Rn?.authOnly,accessTokens:or.resolvedAccessTokens,toTokenSymbol:Rn?.toTokenSymbol,toTokenAmount:Rn?.toTokenAmount,toChainId:Rn?.toChainId,toRecipientAddress:Rn?.toRecipientAddress,toAmountUsd:Rn?.toAmountUsd,selectedExchange:or.resolvedSelectedExchange,apiKey:fe,hostname:pe})}),gr&&Z(`div`,{className:`mt-4`,children:Z(wb,{quote:gr,showContent:!0,compact:!0})})]})}catch(e){return s.console.error(`[trails-sdk] Error rendering onramp:`,e),Q(`div`,{className:`flex flex-col h-full p-4`,children:[Q(`div`,{className:`flex items-center mb-4`,children:[Z(`button`,{type:`button`,onClick:Ot,className:`flex h-8 w-8 justify-center items-center rounded-full bg-gray-50 dark:bg-gray-700 cursor-pointer transition-colors text-gray-900 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600 mr-2`,title:`Back`,children:`←`}),Z(`h2`,{className:`text-lg font-semibold text-gray-900 dark:text-white`,children:`Exchange Funding`})]}),Z(`div`,{className:`flex-1 flex items-center justify-center`,children:Q(`div`,{className:`text-center p-4 border border-solid border-red-200 dark:border-red-700 rounded-lg`,children:[Z(`p`,{className:`text-red-600 dark:text-red-400 mb-2`,children:`Error loading exchange funding.`}),Z(`p`,{className:`text-sm text-red-500 dark:text-red-500`,children:e instanceof Error?e.message:`Unknown error`})]})})]})}case`onramp-bluvo`:return Ft?Z(lr,{fallback:Z(`div`,{className:`flex h-full min-h-[320px] items-center justify-center`,children:Z(Tw,{className:`h-8 w-8`})}),children:Z(KO,{address:ue,environment:We,exchange:Ft,quote:gr,onBack:()=>{It(),Vt(null),G(`onramp-bluvo`)},onContinue:()=>G(`fund-form`,{backTarget:`onramp-bluvo`}),onSubmitted:()=>{nn(null),G(`pending`)}})}):Z(lr,{fallback:Z(`div`,{className:`flex h-full min-h-[320px] items-center justify-center`,children:Z(Tw,{className:`h-8 w-8`})}),children:Z(GO,{environment:We,onBack:()=>G(`fund-methods`),onSelectExchange:e=>{zt(`onramp-bluvo`),It(),Vt({id:e.id,name:e.name,logoUrl:e.logoUrl}),G(`onramp-bluvo`)}})});case`onramp-meld`:return Z(lT,{onBack:Ot});case`earn`:return Z(yE,{onContinue:()=>G(`send-form`),account:Pn?.account,walletClient:Pn??void 0,onTransactionStateChange:Qr,onError:ni,onWaitingForWalletConfirm:oi,onConfirm:Kr,onComplete:Yr,onSend:Pr,setWalletConfirmRetryHandler:En,swapProvider:te,bridgeProvider:ne,swapProviderFallback:re,bridgeProviderFallback:ie,fundMethod:jt,checkoutOnHandlers:xr,recentTokens:Ae,onRecentTokenSelect:jr,onTrackToken:Mr});case`earn-pools`:return Z(xE,{onBack:Ot,onPoolSelect:e=>{s.console.log(`Selected pool:`,e),Gt(e),G(`send-form`)}});case`swap`:return Z(oO,{onSend:Pr,onWaitingForWalletConfirm:oi,onWaitingForOnrampConfirm:ci,onConfirm:Kr,onComplete:Yr,selectedToken:Me,account:Pn?.account,toRecipient:n||void 0,toAmount:r||void 0,toChainId:i?Number(i):void 0,toToken:c||void 0,toCalldata:f||void 0,walletClient:Pn??void 0,isSequenceWallet:be,onTransactionStateChange:Qr,onError:ni,setWalletConfirmRetryHandler:En,swapProvider:te,bridgeProvider:ne,swapProviderFallback:re,bridgeProviderFallback:ie,fundMethod:jt,onAmountUpdate:void 0,checkoutOnHandlers:xr,recentTokens:Ae,onRecentTokenSelect:jr,onTrackToken:Mr});case`withdraw`:return Z(cD,{onSend:Pr,onWaitingForWalletConfirm:oi,onConfirm:Kr,onComplete:Yr,selectedToken:Me,account:Pn?.account,toRecipient:n||void 0,toAmount:r||void 0,toChainId:i?Number(i):void 0,toToken:c||void 0,toCalldata:f||void 0,fromToken:p||void 0,fromChainId:m?Number(m):void 0,walletClient:Pn??void 0,isSequenceWallet:be,onTransactionStateChange:Qr,onError:ni,setWalletConfirmRetryHandler:En,swapProvider:te,bridgeProvider:ne,swapProviderFallback:re,bridgeProviderFallback:ie,checkoutOnHandlers:xr,recentTokens:Ae,onTrackToken:Mr,defaultInputMode:z});case`account-history`:return Z(sw,{accountAddress:ue,onBack:Ot,onRecoverIntent:e=>{G(`recover`,{backTarget:`account-history`,data:e})}});case`recover`:return Z(GD,{data:gt.screenData??null,onBack:Ot});case`meld-history`:return Z(hT,{limit:20,autoRefetch:!1,onBack:Ot});case`account-settings`:return Z(ww,{onBack:Ot});case`user-preferences`:return Z(cO,{onBack:Ot});case`chain-list`:return Z(cb,{onBack:()=>G(`tokens`)});case`recipients`:return Z(eO,{onBack:Ot});case`disconnect`:return Z(gT,{onBack:Ot,disconnectHandler:Er})}throw Error(`[trails-sdk] Unhandled screen state: ${dt}`)},gi=()=>Z(yb,{value:{thresholdBps:L,warningMessage:R,fallbackBridgeUrl:ae},children:Q(`div`,{className:mi?`w-[365px] rounded-[22px] border trails-border-primary trails-bg-primary p-6 shadow-xl trails-text-primary trails-font trails-fade-slide-in`:`flex flex-col min-h-[400px] shadow-xl p-4 sm:p-6 relative w-full max-w-[400px] min-w-0 sm:w-[400px] mx-auto custom-scrollbar trails-bg-primary trails-text-primary trails-font trails-border-radius-widget trails-widget-border trails-fade-slide-in`,children:[Q(`div`,{className:`flex-1 flex flex-col w-full min-w-0 trails-fade-slide-in-fast`,children:[hi(),Nn&&dt!==`connect-error`&&Z(`div`,{className:`mt-2`,children:Z(XC,{errorPrettified:T(Nn,`An error occurred`),error:Nn,severity:`error`})})]},dt),mi?null:Z(DE,{onDebugScreenSelect:Cr})]})});return y?gi():Q(`div`,{className:`flex flex-col items-center justify-center space-y-8 py-12`,children:[_?Z(`div`,{className:`flex flex-col items-center justify-center transition-transform duration-150 ease-out hover:scale-[1.02] active:scale-[0.98]`,onClick:Wr,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),Wr())},role:`button`,tabIndex:0,children:_}):Z(`button`,{type:`button`,onClick:Wr,className:`trails-modal-button cursor-pointer font-semibold py-3 px-6 trails-font transition-transform duration-150 ease-out hover:scale-[1.02] active:scale-[0.98]`,children:ee||Mn}),Ge&&Z(w_,{isOpen:Ge,onClose:Gr,children:gi()})]})}),JO=fr(({resolvedWalletRuntimeMode:e,...t},n)=>Q(C_,{props:t,walletRuntimeMode:e,children:[Z(sO,{}),Z(qO,{ref:n})]})),YO=fr((e,t)=>{let n=or.useContext(zx),r=n?.config??null,i=r!==null,a=Qr(),o=r?.hasAdapters??!1,c=e.walletConnectProjectId??(n?.hasExplicitWalletConnectProjectId?n.config.walletConnectProjectId:void 0),u=or.useMemo(()=>Ix({adapters:e.adapters,owner:`TrailsWidget adapters`,walletConnectProjectId:c}),[e.adapters,c]),d=!!u?.Provider;if(!e.apiKey&&!r)throw Error(`apiKey is required when TrailsWidget is mounted without a parent TrailsProvider`);if(o&&e.adapters)throw Error(`[trails-sdk] Provide adapters either via the parent TrailsProvider or the TrailsWidget instance, not both.`);if(a&&e.adapters)throw Error(`[trails-sdk] TrailsWidget adapters cannot be used inside an existing parent wallet context.`);let f=xo({hasWalletContext:a,hasWidgetAdapterProvider:d}),p=i&&!!e.adapters,m=or.useMemo(()=>({trailsApiKey:e.apiKey??r?.trailsApiKey??``,trailsApiUrl:e.trailsApiUrl??r?.trailsApiUrl,trailsAppUrl:e.trailsAppUrl??r?.trailsAppUrl,sequenceApiUrl:e.sequenceApiUrl??r?.sequenceApiUrl,sequenceIndexerUrl:e.sequenceIndexerUrl??r?.sequenceIndexerUrl,sequenceNodeGatewayUrl:e.sequenceNodeGatewayUrl??r?.sequenceNodeGatewayUrl,sequenceMetadataUrl:e.sequenceMetadataUrl??r?.sequenceMetadataUrl,walletConnectProjectId:e.walletConnectProjectId??r?.walletConnectProjectId,slippageTolerance:e.slippageTolerance?String(e.slippageTolerance):r?.slippageTolerance,debug:e.debug??r?.debug,adapters:u?[u]:void 0}),[e.apiKey,e.trailsApiUrl,e.trailsAppUrl,e.sequenceApiUrl,e.sequenceIndexerUrl,e.sequenceNodeGatewayUrl,e.sequenceMetadataUrl,e.walletConnectProjectId,e.slippageTolerance,e.debug,r,u]);s.console.log(`trailsConfig`,m),s.console.log(`[trails-sdk] [TrailsWidget] wallet runtime mode`,{walletRuntimeMode:f,hasTrailsContext:i,hasWalletContext:a,hasWidgetAdapterProvider:d,parentHasAdapters:o,shouldNestTrailsProvider:p});let h=Z(HS,{widgetContent:Z(C,{initialTheme:e.theme,children:Z(JO,{...e,resolvedWalletRuntimeMode:f,ref:t})}),trailsConfig:m,walletRuntimeMode:f,shouldNestTrailsProvider:p}),g=e.customCss instanceof Object?WS(e.customCss):e.customCss;return e.disableCss?Z(cr,{children:h}):Z(l,{customCss:g,children:Z(cr,{children:h})})}),XO=e=>({openModal:()=>e.current?.openModal?.(),closeModal:()=>e.current?.closeModal?.(),isModalOpen:e.current?.isModalOpen??!1}),ZO=({onClose:e,onConnected:t,open:n,...r})=>(q(()=>{if(!n)return;let t=t=>{t.key===`Escape`&&e()};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,n]),n?Q(`div`,{className:`fixed inset-0 z-40 flex items-center justify-center bg-black/50 px-4`,children:[Z(`button`,{type:`button`,"aria-label":`Close wallet connect`,className:`absolute inset-0 cursor-default`,onClick:e}),Z(l,{hostClassName:`relative z-10 block`,children:Z(C,{initialTheme:`light`,children:Z(H,{children:Z(SO,{...r,onBack:e,onClose:e,onConnected:n=>{t?.(n),e()}})})})})]}):null);function QO(e,t){let n=fr((e,n)=>Z(YO,{ref:n,...t(e)}));return n.displayName=e,n}function $O(e){let{appMetadata:t,dev:n,intentProtocolVersion:r,...i}=e;return{...i,intentProtocolVersion:r,appName:t?.name,appUrl:t?.url,appImageUrl:t?.imageUrl,appDescription:t?.description,debug:n?.debug,toast:n?.toast,sequenceIndexerUrl:n?.sequenceIndexerUrl,trailsApiUrl:n?.trailsApiUrl,trailsAppUrl:n?.trailsAppUrl,sequenceNodeGatewayUrl:n?.sequenceNodeGatewayUrl,sequenceMetadataUrl:n?.sequenceMetadataUrl,sequenceApiUrl:n?.sequenceApiUrl}}const ek={wallet:`wallet`,"fiat-onramp":`onramp`,"exchange-onramp":`onramp-exchange`,"crypto-transfer":`crypto-transfer`};function tk(e){return ek[e]}const nk={CONNECTED_WALLET:{fundingMethod:`wallet`},EXCHANGE:{fundingMethod:`exchange-onramp`},CRYPTO_TRANSFER:{fundingMethod:`crypto-transfer`},CREDIT_DEBIT_CARD:{fundingMethod:`fiat-onramp`,meldPaymentMethodType:`CREDIT_DEBIT_CARD`}};function rk(e){return nk[e]}function ik(e,t){let n=e?rk(e):void 0,r=n?.fundingMethod===`fiat-onramp`,i=n?.fundingMethod===`exchange-onramp`,a={paymentMethodType:n?.meldPaymentMethodType};r&&t?.currency&&(a.fiatCurrency=t.currency),r&&t?.amount!==void 0&&(a.fiatAmount=String(t.amount)),i&&t?.exchange&&(a.meshExchangeKey=t.exchange);let o,s,c,l;return!r&&t&&(t.chain&&(o=dt(t.chain)),t.token&&(s=t.token),t.amount!==void 0&&(c=String(t.amount)),t.walletAddress&&(l=t.walletAddress)),{fundMethod:n?tk(n.fundingMethod):void 0,fundOptions:a,fromChainId:o,fromToken:s,fromAmount:c,fromAccount:l,isOnramp:r}}function ak({paymentMethod:e,from:t}){let{fundMethod:n,fundOptions:r,fromChainId:i,fromToken:a,fromAmount:o,fromAccount:s,isOnramp:c}=ik(e,t);return{widgetProps:{fundMethod:n,fundOptions:r,fromChainId:i,fromToken:a,fromAmount:o,fromAccount:s},isOnramp:c}}function ok(e){let{apiKey:t,paymentMethod:n,to:r,from:i,onramp:a,onSwapSuccess:o,onSwapStart:s,onSwapError:c,...l}=e,u=r?.chain?dt(r.chain):void 0,d=r?.defaultChain?dt(r.defaultChain):void 0,{widgetProps:f,isOnramp:p}=ak({paymentMethod:n,from:i}),{fundMethod:m,...h}=f,g=!p&&h.fromToken?`fiat`:void 0;return{apiKey:t,mode:`swap`,fundMethod:m??`wallet`,toToken:r?.token??void 0,toChainId:u,toAmount:r?.amount===void 0?void 0:String(r.amount),toCalldata:r?.calldata,defaultToToken:r?.defaultToken,defaultToChainId:d,supportedChains:r?.supportedChains,supportedTokensByChain:r?.supportedTokensByChain,...h,defaultInputMode:g,onramp:a,onSuccess:o,onStart:s,onError:c,...$O(l)}}const sk=QO(`Swap`,ok);function ck(e){let{apiKey:t,from:n,to:r,onWithdrawSuccess:i,onWithdrawStart:a,onWithdrawError:o,...s}=e,c=r?.chain?dt(r.chain):void 0,l=r?.defaultChain?dt(r.defaultChain):void 0,u=n?.chain?dt(n.chain):void 0;return{apiKey:t,mode:`withdraw`,fundMethod:`wallet`,toAddress:r?.recipient,toToken:r?.token??void 0,toChainId:c,toAmount:r?.amount===void 0?void 0:String(r.amount),toCalldata:r?.calldata,defaultToToken:r?.defaultToken,defaultToChainId:l,originSupportedChains:n?.supportedChains,originSupportedTokensByChain:n?.supportedTokensByChain,fromToken:n?.token??void 0,fromChainId:u,fromAmount:n?.amount===void 0?void 0:String(n.amount),fromAccount:n?.walletAddress,onSuccess:i,onStart:a,onError:o,...$O(s)}}const lk=fr((e,t)=>Z(YO,{ref:t,...ck(e)}));lk.displayName=`Withdraw`;function uk(e){let{apiKey:t,paymentMethod:n,to:r,from:i,defaultInputMode:a,type:o,hideSwap:s,hideWallets:c,fundMethodsList:l,hideUnlistedFundMethods:u,onramp:d,onFundingSuccess:f,onFundingStart:p,onFundingError:m,...h}=e,g=r?.chain?dt(r.chain):void 0,_=r?.defaultChain?dt(r.defaultChain):void 0,{widgetProps:v,isOnramp:y}=ak({paymentMethod:n,from:i}),{fundMethod:b,fundOptions:x,...S}=v,C={...x,hideSwap:s,hideWallets:c,fundMethodsList:l,hideUnlistedFundMethods:u},w=a??(!y&&S.fromToken?`fiat`:void 0);return{apiKey:t,mode:`fund`,fundMethod:b,toAddress:r?.recipient,toToken:r?.token??void 0,toChainId:g,toCalldata:r?.calldata,defaultToToken:r?.defaultToken,defaultToChainId:_,supportedChains:r?.supportedChains,supportedTokensByChain:r?.supportedTokensByChain,...S,defaultInputMode:w,fundTradeType:o,fundOptions:C,onramp:d,onSuccess:f,onStart:p,onError:m,...$O(h)}}const dk=QO(`Fund`,uk);function fk(e){let{apiKey:t,paymentMethod:n,to:r,from:i,payMessage:a,onramp:o,onPaymentSuccess:s,onPaymentStart:c,onPaymentError:l,...u}=e,d=r.chain?dt(r.chain):void 0,{widgetProps:f}=ak({paymentMethod:n,from:i}),{fundMethod:p,...m}=f;return{apiKey:t,mode:`pay`,fundMethod:p,toAddress:r.recipient,toToken:r.token,toChainId:d,toAmount:String(r.amount),toCalldata:r.calldata,supportedChains:r.supportedChains,supportedTokensByChain:r.supportedTokensByChain,...m,payMessage:a,onramp:o,onSuccess:s,onStart:c,onError:l,...$O(u)}}const pk=QO(`Pay`,fk);function mk(e){let{apiKey:t,paymentMethod:n,to:r,from:i,onramp:a,onEarnSuccess:o,onEarnStart:s,onEarnError:c,...l}=e,u=r?.chain?dt(r.chain):void 0,d=r?.defaultChain?dt(r.defaultChain):void 0,{widgetProps:f}=ak({paymentMethod:n,from:i}),{fundMethod:p,...m}=f;return{apiKey:t,mode:`earn`,fundMethod:p??`wallet`,toAddress:r?.recipient,toToken:r?.token??void 0,toChainId:u,toAmount:r?.amount===void 0?void 0:String(r.amount),toCalldata:r?.calldata,defaultToToken:r?.defaultToken,defaultToChainId:d,supportedChains:r?.supportedChains,supportedTokensByChain:r?.supportedTokensByChain,...m,onramp:a,onSuccess:o,onStart:s,onError:c,...$O(l)}}const hk=QO(`Earn`,mk);function gk(e,t){if(bn(e))return e;let n=e.trim().toUpperCase(),r=qe.find(e=>e.symbol.trim().toUpperCase()===n&&e.chainId===t);if(r?.contractAddress)return r.contractAddress;throw Error(`[trails-sdk] Token "${e}" not found on chain ${t}. Use the contract address instead.`)}const _k=({onNavigateToOnramp:e})=>{let t=fv(),n=t?.config.mesh?.exchanges&&t.config.mesh.exchanges.length>0;return pv(t?.config)?n?e?Q(hi,{children:[Z(`div`,{className:`border-b border-gray-200 dark:border-gray-700`}),Q(`button`,{type:`button`,onClick:e,className:`w-full text-left px-3 py-4 text-sm flex items-center justify-between cursor-pointer transition-colors trails-text-primary trails-hover-bg`,children:[Q(`div`,{className:`flex items-center gap-3`,children:[Z(xi,{className:`w-4 h-4`}),Z(`span`,{className:`text-sm font-bold`,children:`Send from Exchange`})]}),Z(ki,{className:`w-5 h-5 text-gray-400`})]})]}):null:Q(hi,{children:[Z(`div`,{className:`border-b border-gray-200 dark:border-gray-700`}),Z(`div`,{className:`px-3 py-4 text-sm`,children:Q(`div`,{className:`flex items-center gap-3 text-amber-600 dark:text-amber-400`,children:[Z(gi,{className:`w-4 h-4 flex-shrink-0`}),Q(`div`,{className:`flex-1`,children:[Z(`p`,{className:`font-medium`,children:`Exchange list not configured`}),Z(`p`,{className:`text-xs mt-1 text-amber-500 dark:text-amber-500`,children:`Please configure at least one exchange in the onramp settings.`})]})]})})]}):null};export{Xx as $,tc as $n,$h as $t,eD as A,ru as An,cv as At,IS as B,Ec as Bn,M_ as Bt,ZO as C,Gu as Cn,qa as Cr,bv as Ct,SO as D,Nu as Dn,mv as Dt,kO as E,Pu as En,dv as Et,JC as F,Uc as Fn,tv as Ft,pS as G,ic as Gn,Jg as Gt,DS as H,xc as Hn,s_ as Ht,YC as I,Bc as In,nv as It,rS as J,ec as Jn,Wg as Jt,mS as K,nc as Kn,Yg as Kt,qC as L,Fc as Ln,Q_ as Lt,XC as M,Vc as Mn,ov as Mt,bC as N,Rc as Nn,X_ as Nt,zD as O,Mu as On,pv as Ot,yC as P,zc as Pn,rv as Pt,Yx as Q,$s as Qn,ag as Qt,zS as R,Pc as Rn,$_ as Rt,sk as S,rp as Sn,Va as Sr,Iv as St,XO as T,qu as Tn,gv as Tt,ES as U,Tc as Un,a_ as Ut,PS as V,Dc as Vn,sn as Vt,_S as W,Sc as Wn,Zg as Wt,Qx as X,Js as Xn,ig as Xt,nS as Y,rc as Yn,dg as Yt,Zx as Z,qs as Zn,rg as Zt,gk as _,ln as _n,so as _r,Nv as _t,fa as a,Lh as an,wo as ar,Bx as at,dk as b,op as bn,Xa as br,jv as bt,Br as c,Nm as cn,ho as cr,wx as ct,Ur as d,Mm as dn,uo as dr,cy as dt,Hh as en,Es as er,Jx as et,Gr as f,Fm as fn,po as fr,sy as ft,fi as g,Sp as gn,oo as gr,Fv as gt,_k as h,Dm as hn,co as hr,ay as ht,ua as i,zh as in,gs as ir,Hx as it,Tw as j,Hc as jn,sv as jt,UD as k,tu as kn,fv as kt,_a as l,Im as ln,mo as lr,xx as lt,mi as m,km as mn,lo as mr,oy as mt,ca as n,Bh as nn,ms as nr,Wx as nt,pa as o,Mh as on,_o as or,Vx as ot,ba as p,Om as pn,io as pr,ly as pt,fS as q,Qs as qn,Hg as qt,Pr as r,Rh as rn,hs as rr,Ux as rt,ha as s,Lm as sn,go as sr,Cx as st,Yt as t,Ih as tn,Ts as tr,Kx as tt,Vr as u,jm as un,fo as ur,wb as ut,hk as v,lp as vn,eo as vr,Pv as vt,YO as w,Ku as wn,hv as wt,lk as x,ip as xn,$ as xr,Av as xt,pk as y,ap as yn,$a as yr,Mv as yt,FS as z,oc as zn,L_ as zt};