@sodax/dapp-kit 2.4.0-rc.1 → 2.4.0-rc.3

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 (288) hide show
  1. package/README.md +11 -3
  2. package/dist/index.d.ts +395 -2413
  3. package/dist/index.mjs +206 -31
  4. package/package.json +2 -2
  5. package/src/hooks/_apiKeyWire.test.ts +4 -29
  6. package/src/hooks/_mutationContract.test.ts +2 -8
  7. package/src/hooks/backend/index.ts +0 -13
  8. package/src/hooks/backend/useBackendAllMoneyMarketAssets.ts +0 -6
  9. package/src/hooks/backend/useBackendAllMoneyMarketBorrowers.ts +0 -10
  10. package/src/hooks/backend/useBackendIntentByHash.ts +0 -6
  11. package/src/hooks/backend/useBackendIntentByTxHash.ts +1 -10
  12. package/src/hooks/backend/useBackendMoneyMarketAsset.ts +0 -6
  13. package/src/hooks/backend/useBackendMoneyMarketAssetBorrowers.ts +0 -8
  14. package/src/hooks/backend/useBackendMoneyMarketAssetSuppliers.ts +0 -8
  15. package/src/hooks/backend/useBackendMoneyMarketPosition.ts +0 -6
  16. package/src/hooks/backend/useBackendOracleCandles.ts +1 -9
  17. package/src/hooks/backend/useBackendOracleMarkets.ts +1 -7
  18. package/src/hooks/backend/useBackendOrderbook.ts +0 -6
  19. package/src/hooks/backend/useBackendUserIntents.ts +0 -8
  20. package/src/hooks/bitcoin/resolveBtcReadAddress.test.ts +1 -3
  21. package/src/hooks/bitcoin/resolveBtcReadAddress.ts +2 -12
  22. package/src/hooks/bitcoin/useBitcoinBalance.ts +1 -7
  23. package/src/hooks/bitcoin/useBitcoinTradingSetup.ts +2 -4
  24. package/src/hooks/bitcoin/useEnsureRadfiAccessToken.ts +2 -13
  25. package/src/hooks/bitcoin/useFundTradingWallet.ts +0 -6
  26. package/src/hooks/bitcoin/useRadfiAuth.ts +1 -6
  27. package/src/hooks/bitcoin/useRadfiSession.ts +0 -1
  28. package/src/hooks/bitcoin/useRadfiWithdraw.ts +0 -6
  29. package/src/hooks/bitcoin/useRenewUtxos.ts +0 -5
  30. package/src/hooks/bitcoin/useTradingWallet.ts +1 -4
  31. package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.test.ts +1 -7
  32. package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.ts +7 -21
  33. package/src/hooks/bridge/useBridge.test.ts +1 -11
  34. package/src/hooks/bridge/useBridge.ts +2 -12
  35. package/src/hooks/bridge/useBridgeAllowance.ts +1 -2
  36. package/src/hooks/bridge/useBridgeApprovalStrategy.ts +2 -6
  37. package/src/hooks/bridge/useBridgeApprove.ts +2 -14
  38. package/src/hooks/bridge/useBridgeDetailedStatus.test.ts +2 -11
  39. package/src/hooks/bridge/useBridgeDetailedStatus.ts +3 -23
  40. package/src/hooks/bridge/useBridgeWithApproval.ts +2 -11
  41. package/src/hooks/bridgeApi/getBridgeSubmitTxStatusRefetchInterval.test.ts +2 -7
  42. package/src/hooks/bridgeApi/getBridgeSubmitTxStatusRefetchInterval.ts +2 -13
  43. package/src/hooks/bridgeApi/index.ts +11 -14
  44. package/src/hooks/bridgeApi/useBridgeApiAllowance.ts +1 -9
  45. package/src/hooks/bridgeApi/useBridgeApiApprove.ts +2 -17
  46. package/src/hooks/bridgeApi/useBridgeApiApproveAndBroadcast.test.ts +2 -13
  47. package/src/hooks/bridgeApi/useBridgeApiApproveAndBroadcast.ts +3 -20
  48. package/src/hooks/bridgeApi/useBridgeApiBridgeableAmount.ts +1 -12
  49. package/src/hooks/bridgeApi/useBridgeApiCreateBridgeIntent.ts +1 -14
  50. package/src/hooks/bridgeApi/useBridgeApiFee.ts +2 -11
  51. package/src/hooks/bridgeApi/useBridgeApiIsBridgeable.ts +1 -12
  52. package/src/hooks/bridgeApi/useBridgeApiSubmitTx.ts +2 -23
  53. package/src/hooks/bridgeApi/useBridgeApiSubmitTxStatus.test.ts +1 -9
  54. package/src/hooks/bridgeApi/useBridgeApiSubmitTxStatus.ts +1 -19
  55. package/src/hooks/bridgeApi/useBridgeApiTokens.ts +0 -8
  56. package/src/hooks/bridgeApi/useBridgeApiTokensByChain.ts +0 -7
  57. package/src/hooks/dex/useClaimRewards.ts +1 -12
  58. package/src/hooks/dex/useCreateDecreaseLiquidityParams.ts +1 -5
  59. package/src/hooks/dex/useCreateDepositParams.ts +1 -5
  60. package/src/hooks/dex/useCreateSupplyLiquidityParams.ts +1 -10
  61. package/src/hooks/dex/useCreateWithdrawParams.ts +1 -5
  62. package/src/hooks/dex/useDecreaseLiquidity.ts +2 -15
  63. package/src/hooks/dex/useDexAllowance.ts +1 -5
  64. package/src/hooks/dex/useDexApprove.ts +1 -12
  65. package/src/hooks/dex/useDexDeposit.ts +1 -23
  66. package/src/hooks/dex/useDexWithdraw.ts +1 -13
  67. package/src/hooks/dex/useLiquidityAmounts.ts +1 -4
  68. package/src/hooks/dex/usePoolBalances.ts +0 -4
  69. package/src/hooks/dex/usePoolData.ts +1 -4
  70. package/src/hooks/dex/usePools.ts +1 -4
  71. package/src/hooks/dex/usePositionInfo.ts +1 -4
  72. package/src/hooks/dex/useSupplyLiquidity.ts +3 -20
  73. package/src/hooks/leverageYield/useApproveLeveragePositionFunding.ts +2 -8
  74. package/src/hooks/leverageYield/useLeveragePositionAccount.ts +2 -13
  75. package/src/hooks/leverageYield/useLeveragePositionCollateral.ts +2 -14
  76. package/src/hooks/leverageYield/useLeveragePositionFundingAllowance.ts +2 -9
  77. package/src/hooks/leverageYield/useLeveragePositionInfo.ts +1 -13
  78. package/src/hooks/leverageYield/useLeveragePositionPayoutAddress.ts +3 -15
  79. package/src/hooks/leverageYield/useLeveragePositionPending.ts +2 -16
  80. package/src/hooks/leverageYield/useLeveragePositions.ts +1 -15
  81. package/src/hooks/leverageYield/useLeveragePositionsForUser.ts +1 -15
  82. package/src/hooks/leverageYield/useLeverageYieldApprovalStrategy.ts +1 -6
  83. package/src/hooks/leverageYield/useLeverageYieldDeposit.ts +1 -17
  84. package/src/hooks/leverageYield/useLeverageYieldDetailedStatus.test.ts +3 -14
  85. package/src/hooks/leverageYield/useLeverageYieldDetailedStatus.ts +2 -19
  86. package/src/hooks/leverageYield/useLeverageYieldEffectiveApr.ts +1 -12
  87. package/src/hooks/leverageYield/useLeverageYieldNotifySolver.ts +1 -11
  88. package/src/hooks/leverageYield/useLeverageYieldPosition.ts +1 -13
  89. package/src/hooks/leverageYield/useLeverageYieldPreviewRedeem.ts +1 -12
  90. package/src/hooks/leverageYield/useLeverageYieldQuote.test.ts +3 -13
  91. package/src/hooks/leverageYield/useLeverageYieldQuote.ts +5 -54
  92. package/src/hooks/leverageYield/useLeverageYieldShareBalances.ts +2 -29
  93. package/src/hooks/leverageYield/useLeverageYieldTotalAssets.ts +1 -9
  94. package/src/hooks/leverageYield/useLeverageYieldVaultSwap.ts +2 -25
  95. package/src/hooks/leverageYield/useLeverageYieldVaultSwapWithApproval.ts +1 -11
  96. package/src/hooks/leverageYield/useLeverageYieldWithdraw.ts +1 -17
  97. package/src/hooks/leverageYield/useOpenLeveragePosition.ts +5 -18
  98. package/src/hooks/leverageYield/useRunLeveragePositionOperation.ts +4 -20
  99. package/src/hooks/leverageYield/useSubmitLeveragePositionIntent.ts +3 -15
  100. package/src/hooks/leverageYieldApi/index.ts +0 -15
  101. package/src/hooks/leverageYieldApi/useLeverageYieldApiAllowance.ts +1 -8
  102. package/src/hooks/leverageYieldApi/useLeverageYieldApiApprove.ts +3 -6
  103. package/src/hooks/leverageYieldApi/useLeverageYieldApiApproveAndBroadcast.test.ts +4 -14
  104. package/src/hooks/leverageYieldApi/useLeverageYieldApiApproveAndBroadcast.ts +4 -26
  105. package/src/hooks/leverageYieldApi/useLeverageYieldApiApr.ts +1 -7
  106. package/src/hooks/leverageYieldApi/useLeverageYieldApiAsset.ts +0 -7
  107. package/src/hooks/leverageYieldApi/useLeverageYieldApiCancelIntent.ts +2 -8
  108. package/src/hooks/leverageYieldApi/useLeverageYieldApiCreateDepositIntent.ts +2 -8
  109. package/src/hooks/leverageYieldApi/useLeverageYieldApiCreateWithdrawIntent.ts +2 -8
  110. package/src/hooks/leverageYieldApi/useLeverageYieldApiDeadline.ts +1 -7
  111. package/src/hooks/leverageYieldApi/useLeverageYieldApiDepositQuote.ts +1 -15
  112. package/src/hooks/leverageYieldApi/useLeverageYieldApiEffectiveApr.ts +1 -7
  113. package/src/hooks/leverageYieldApi/useLeverageYieldApiEstimateGas.ts +1 -7
  114. package/src/hooks/leverageYieldApi/useLeverageYieldApiFilledIntent.ts +1 -6
  115. package/src/hooks/leverageYieldApi/useLeverageYieldApiIntent.ts +1 -6
  116. package/src/hooks/leverageYieldApi/useLeverageYieldApiIntentExtraData.ts +1 -8
  117. package/src/hooks/leverageYieldApi/useLeverageYieldApiIntentHash.ts +0 -7
  118. package/src/hooks/leverageYieldApi/useLeverageYieldApiIntentPacket.ts +1 -7
  119. package/src/hooks/leverageYieldApi/useLeverageYieldApiLsdApr.ts +1 -7
  120. package/src/hooks/leverageYieldApi/useLeverageYieldApiMaxWithdraw.ts +1 -7
  121. package/src/hooks/leverageYieldApi/useLeverageYieldApiPartnerFee.ts +1 -7
  122. package/src/hooks/leverageYieldApi/useLeverageYieldApiPosition.ts +0 -7
  123. package/src/hooks/leverageYieldApi/useLeverageYieldApiPreviewDeposit.ts +1 -7
  124. package/src/hooks/leverageYieldApi/useLeverageYieldApiPreviewRedeem.ts +1 -7
  125. package/src/hooks/leverageYieldApi/useLeverageYieldApiPreviewWithdraw.ts +1 -7
  126. package/src/hooks/leverageYieldApi/useLeverageYieldApiShareBalance.ts +0 -7
  127. package/src/hooks/leverageYieldApi/useLeverageYieldApiSolverFee.ts +1 -7
  128. package/src/hooks/leverageYieldApi/useLeverageYieldApiStatus.ts +2 -12
  129. package/src/hooks/leverageYieldApi/useLeverageYieldApiSubmitIntent.ts +2 -8
  130. package/src/hooks/leverageYieldApi/useLeverageYieldApiSubmitTx.ts +2 -8
  131. package/src/hooks/leverageYieldApi/useLeverageYieldApiSubmitTxStatus.ts +2 -17
  132. package/src/hooks/leverageYieldApi/useLeverageYieldApiTotalAssets.ts +0 -7
  133. package/src/hooks/leverageYieldApi/useLeverageYieldApiVault.ts +1 -7
  134. package/src/hooks/leverageYieldApi/useLeverageYieldApiVaults.ts +0 -7
  135. package/src/hooks/leverageYieldApi/useLeverageYieldApiWithdrawQuote.ts +1 -15
  136. package/src/hooks/migrate/useMigrateBaln.ts +1 -8
  137. package/src/hooks/migrate/useMigrateIcxToSoda.ts +1 -12
  138. package/src/hooks/migrate/useMigratebnUSD.ts +1 -12
  139. package/src/hooks/migrate/useMigrationAllowance.ts +3 -19
  140. package/src/hooks/migrate/useMigrationApprove.ts +2 -20
  141. package/src/hooks/migrate/useRevertMigrateSodaToIcx.ts +0 -7
  142. package/src/hooks/mm/useAToken.ts +1 -6
  143. package/src/hooks/mm/useATokensBalances.ts +0 -5
  144. package/src/hooks/mm/useBorrow.ts +1 -13
  145. package/src/hooks/mm/useEModes.ts +2 -13
  146. package/src/hooks/mm/useMMAllowance.test.ts +55 -0
  147. package/src/hooks/mm/useMMAllowance.ts +6 -16
  148. package/src/hooks/mm/useMMApprove.ts +1 -14
  149. package/src/hooks/mm/useRepay.ts +1 -12
  150. package/src/hooks/mm/useReservesData.ts +0 -4
  151. package/src/hooks/mm/useReservesHumanized.ts +0 -4
  152. package/src/hooks/mm/useReservesList.ts +0 -4
  153. package/src/hooks/mm/useReservesUsdFormat.ts +0 -4
  154. package/src/hooks/mm/useSupply.ts +1 -24
  155. package/src/hooks/mm/useUserFormattedSummary.ts +0 -7
  156. package/src/hooks/mm/useUserReservesData.ts +0 -4
  157. package/src/hooks/mm/useWithdraw.ts +1 -13
  158. package/src/hooks/partner/useApproveToken.ts +1 -7
  159. package/src/hooks/partner/useFeeClaimSwap.ts +1 -7
  160. package/src/hooks/partner/useFeeClaimWithdraw.ts +3 -20
  161. package/src/hooks/partner/useFetchAssetsBalances.ts +0 -4
  162. package/src/hooks/partner/useGetAutoSwapPreferences.ts +0 -4
  163. package/src/hooks/partner/useGetIntentDetails.ts +1 -8
  164. package/src/hooks/partner/useGetUserIntent.ts +1 -8
  165. package/src/hooks/partner/useIsTokenApproved.ts +0 -4
  166. package/src/hooks/partner/usePartnerCancelIntent.ts +2 -9
  167. package/src/hooks/partner/useSetSwapPreference.ts +1 -14
  168. package/src/hooks/recovery/useHubAssetBalances.ts +1 -6
  169. package/src/hooks/recovery/useWithdrawHubAsset.ts +1 -13
  170. package/src/hooks/shared/index.ts +4 -0
  171. package/src/hooks/shared/invalidateBalances.ts +2 -10
  172. package/src/hooks/shared/isUserRejectedError.test.ts +0 -3
  173. package/src/hooks/shared/isUserRejectedError.ts +2 -23
  174. package/src/hooks/shared/notFoundStreak.ts +5 -22
  175. package/src/hooks/shared/retryUnlessAuthFailure.test.ts +1 -2
  176. package/src/hooks/shared/retryUnlessAuthFailure.ts +1 -12
  177. package/src/hooks/shared/solverStatusPolicy.test.ts +0 -5
  178. package/src/hooks/shared/solverStatusPolicy.ts +8 -58
  179. package/src/hooks/shared/types.ts +4 -55
  180. package/src/hooks/shared/unwrapResult.ts +1 -8
  181. package/src/hooks/shared/useBalances.ts +6 -39
  182. package/src/hooks/shared/useEstablishTrustline.test.ts +1 -5
  183. package/src/hooks/shared/useEstablishTrustline.ts +3 -13
  184. package/src/hooks/shared/useEstablishXrpTrustline.test.ts +112 -0
  185. package/src/hooks/shared/useEstablishXrpTrustline.ts +63 -0
  186. package/src/hooks/shared/useEstimateGas.ts +0 -1
  187. package/src/hooks/shared/useGetUserHubWalletAddress.ts +1 -18
  188. package/src/hooks/shared/useNearStorageCheck.ts +2 -9
  189. package/src/hooks/shared/useNearStorageGate.ts +5 -15
  190. package/src/hooks/shared/useRegisterNearStorage.ts +2 -10
  191. package/src/hooks/shared/useRequestTrustline.test.ts +1 -7
  192. package/src/hooks/shared/useRequestTrustline.ts +4 -14
  193. package/src/hooks/shared/useSafeMutation.test.ts +0 -3
  194. package/src/hooks/shared/useSafeMutation.ts +2 -26
  195. package/src/hooks/shared/useSodaxContext.ts +0 -6
  196. package/src/hooks/shared/useStellarGate.test.ts +2 -9
  197. package/src/hooks/shared/useStellarGate.ts +3 -9
  198. package/src/hooks/shared/useStellarTrustlineCheck.test.ts +0 -2
  199. package/src/hooks/shared/useStellarTrustlineCheck.ts +1 -4
  200. package/src/hooks/shared/useXBalances.ts +2 -20
  201. package/src/hooks/shared/useXrpDestinationCheck.ts +71 -0
  202. package/src/hooks/shared/useXrpGate.test.ts +116 -0
  203. package/src/hooks/shared/useXrpGate.ts +80 -0
  204. package/src/hooks/shared/useXrpTrustlineReserveCheck.ts +45 -0
  205. package/src/hooks/shared/waitForApiAllowance.test.ts +0 -1
  206. package/src/hooks/shared/waitForApiAllowance.ts +2 -6
  207. package/src/hooks/sponsoring/useActivateStellarAccount.test.ts +1 -2
  208. package/src/hooks/sponsoring/useActivateStellarAccount.ts +1 -5
  209. package/src/hooks/sponsoring/useActivateStellarAccount.wire.test.ts +2 -13
  210. package/src/hooks/sponsoring/useSponsorConfig.ts +0 -1
  211. package/src/hooks/sponsoring/useStellarAccountActive.ts +0 -1
  212. package/src/hooks/sponsoring/useStellarAccountStatus.ts +1 -4
  213. package/src/hooks/staking/index.ts +0 -1
  214. package/src/hooks/staking/useCancelUnstake.ts +1 -7
  215. package/src/hooks/staking/useClaim.ts +1 -7
  216. package/src/hooks/staking/useConvertedAssets.ts +1 -4
  217. package/src/hooks/staking/useInstantUnstake.ts +1 -7
  218. package/src/hooks/staking/useInstantUnstakeAllowance.ts +1 -5
  219. package/src/hooks/staking/useInstantUnstakeApprove.ts +1 -11
  220. package/src/hooks/staking/useInstantUnstakeRatio.ts +1 -4
  221. package/src/hooks/staking/useStake.ts +1 -12
  222. package/src/hooks/staking/useStakeAllowance.ts +1 -5
  223. package/src/hooks/staking/useStakeApprove.ts +1 -11
  224. package/src/hooks/staking/useStakeRatio.ts +1 -4
  225. package/src/hooks/staking/useStakingConfig.ts +1 -4
  226. package/src/hooks/staking/useStakingInfo.ts +1 -5
  227. package/src/hooks/staking/useUnstake.ts +2 -9
  228. package/src/hooks/staking/useUnstakeAllowance.ts +1 -5
  229. package/src/hooks/staking/useUnstakeApprove.ts +1 -10
  230. package/src/hooks/staking/useUnstakingInfo.ts +1 -4
  231. package/src/hooks/staking/useUnstakingInfoWithPenalty.ts +1 -4
  232. package/src/hooks/swap/useCancelLimitOrder.ts +1 -7
  233. package/src/hooks/swap/useCancelSwap.ts +1 -7
  234. package/src/hooks/swap/useCreateLimitOrder.ts +2 -12
  235. package/src/hooks/swap/useDetailedStatus.test.ts +6 -18
  236. package/src/hooks/swap/useDetailedStatus.ts +2 -19
  237. package/src/hooks/swap/useQuote.test.ts +2 -8
  238. package/src/hooks/swap/useQuote.ts +5 -32
  239. package/src/hooks/swap/useStatus.ts +2 -10
  240. package/src/hooks/swap/useSwap.test.ts +1 -11
  241. package/src/hooks/swap/useSwap.ts +2 -12
  242. package/src/hooks/swap/useSwapAllowance.ts +1 -2
  243. package/src/hooks/swap/useSwapApprovalStrategy.ts +2 -7
  244. package/src/hooks/swap/useSwapApprove.ts +2 -14
  245. package/src/hooks/swap/useSwapLifecycle.test.ts +47 -2
  246. package/src/hooks/swap/useSwapLifecycle.ts +36 -30
  247. package/src/hooks/swap/useSwapWithApproval.ts +2 -11
  248. package/src/hooks/swapsApi/index.ts +2 -14
  249. package/src/hooks/swapsApi/isTerminalSwapIntentStatus.test.ts +1 -5
  250. package/src/hooks/swapsApi/isTerminalSwapIntentStatus.ts +1 -7
  251. package/src/hooks/swapsApi/useSwapsApiAllowance.ts +0 -7
  252. package/src/hooks/swapsApi/useSwapsApiApprove.ts +1 -14
  253. package/src/hooks/swapsApi/useSwapsApiApproveAndBroadcast.test.ts +5 -20
  254. package/src/hooks/swapsApi/useSwapsApiApproveAndBroadcast.ts +3 -24
  255. package/src/hooks/swapsApi/useSwapsApiBroadcastWithApproval.test.ts +2 -8
  256. package/src/hooks/swapsApi/useSwapsApiBroadcastWithApproval.ts +6 -41
  257. package/src/hooks/swapsApi/useSwapsApiCancelIntent.ts +0 -13
  258. package/src/hooks/swapsApi/useSwapsApiCreateIntent.ts +0 -13
  259. package/src/hooks/swapsApi/useSwapsApiCreateLimitOrder.ts +1 -13
  260. package/src/hooks/swapsApi/useSwapsApiDeadline.ts +1 -7
  261. package/src/hooks/swapsApi/useSwapsApiEstimateGas.ts +0 -7
  262. package/src/hooks/swapsApi/useSwapsApiFilledIntent.ts +0 -8
  263. package/src/hooks/swapsApi/useSwapsApiIntent.ts +1 -7
  264. package/src/hooks/swapsApi/useSwapsApiIntentExtraData.ts +1 -8
  265. package/src/hooks/swapsApi/useSwapsApiIntentHash.ts +0 -7
  266. package/src/hooks/swapsApi/useSwapsApiIntentPacket.ts +1 -10
  267. package/src/hooks/swapsApi/useSwapsApiPartnerFee.ts +0 -7
  268. package/src/hooks/swapsApi/useSwapsApiQuote.ts +2 -24
  269. package/src/hooks/swapsApi/useSwapsApiSolverFee.ts +0 -7
  270. package/src/hooks/swapsApi/useSwapsApiStatus.ts +1 -11
  271. package/src/hooks/swapsApi/useSwapsApiSubmitIntent.ts +1 -15
  272. package/src/hooks/swapsApi/useSwapsApiSubmitTx.ts +0 -21
  273. package/src/hooks/swapsApi/useSwapsApiSubmitTxStatus.ts +2 -19
  274. package/src/hooks/swapsApi/useSwapsApiTokens.ts +0 -7
  275. package/src/hooks/swapsApi/useSwapsApiTokensByChain.ts +0 -7
  276. package/src/index.ts +1 -1
  277. package/src/providers/SodaxProvider.test.ts +2 -9
  278. package/src/providers/SodaxProvider.tsx +1 -12
  279. package/src/providers/createSodaxQueryClient.ts +4 -56
  280. package/src/utils/approvalPlan.ts +9 -32
  281. package/src/utils/dex-utils.ts +5 -20
  282. package/src/utils/index.ts +1 -0
  283. package/src/utils/nearStorageGate.ts +3 -14
  284. package/src/utils/stellarGate.ts +3 -16
  285. package/src/utils/swapLifecycle.test.ts +35 -0
  286. package/src/utils/swapLifecycle.ts +21 -28
  287. package/src/utils/xrpGate.test.ts +112 -0
  288. package/src/utils/xrpGate.ts +69 -0
@@ -12,11 +12,7 @@ export type UseStakingInfoParams = ReadHookParams<
12
12
  }
13
13
  >;
14
14
 
15
- /**
16
- * React hook to fetch the user's staking info (xSODA balance, share value, underlying SODA) by
17
- * deriving the hub wallet from the spoke `srcAddress` + `srcChainKey`. Throws on `!ok` so React
18
- * Query lands in `error` state.
19
- */
15
+ /** Throws on `!ok`. */
20
16
  export function useStakingInfo({
21
17
  params,
22
18
  queryOptions,
@@ -1,4 +1,3 @@
1
- // packages/dapp-kit/src/hooks/staking/useUnstake.ts
2
1
  import type { SpokeChainKey, TxHashPair, UnstakeAction } from '@sodax/sdk';
3
2
  import { useQueryClient } from '@tanstack/react-query';
4
3
  import { useSodaxContext } from '../shared/useSodaxContext.js';
@@ -8,12 +7,7 @@ import { unwrapResult } from '../shared/unwrapResult.js';
8
7
 
9
8
  export type UseUnstakeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<UnstakeAction<K, false>, 'raw'>;
10
9
 
11
- /**
12
- * React hook for initiating an SODA unstake.
13
- *
14
- * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
15
- * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
16
- */
10
+ /** Throws on SDK failure (React Query error state); resolves to the unwrapped `TxHashPair`. */
17
11
  export function useUnstake<K extends SpokeChainKey = SpokeChainKey>({
18
12
  mutationOptions,
19
13
  }: MutationHookParams<TxHashPair, UseUnstakeVars<K>> = {}): SafeUseMutationResult<
@@ -31,8 +25,7 @@ export function useUnstake<K extends SpokeChainKey = SpokeChainKey>({
31
25
  onSuccess: async (data, vars, ctx) => {
32
26
  const { params } = vars;
33
27
  queryClient.invalidateQueries({ queryKey: ['staking', 'info', params.srcChainKey, params.srcAddress] });
34
- // Scope to (srcChainKey, srcAddress) so a user's unstake doesn't refetch every other user's
35
- // staking data. Matches `useUnstakingInfo` / `useUnstakingInfoWithPenalty` query keys.
28
+ // Must match `useUnstakingInfo` / `useUnstakingInfoWithPenalty` query keys.
36
29
  queryClient.invalidateQueries({ queryKey: ['staking', 'unstakingInfo', params.srcChainKey, params.srcAddress] });
37
30
  queryClient.invalidateQueries({
38
31
  queryKey: ['staking', 'unstakingInfoWithPenalty', params.srcChainKey, params.srcAddress],
@@ -11,11 +11,7 @@ export type UseUnstakeAllowanceParams<K extends SpokeChainKey = SpokeChainKey> =
11
11
  }
12
12
  >;
13
13
 
14
- /**
15
- * React hook to check whether the user has approved sufficient xSODA spending for the unstake
16
- * action. Read-only — calls `staking.isAllowanceValid` with `raw: true` so no `walletProvider`
17
- * is required.
18
- */
14
+ /** Read-only (`raw: true`), so no `walletProvider` is needed. */
19
15
  export function useUnstakeAllowance<K extends SpokeChainKey = SpokeChainKey>({
20
16
  params,
21
17
  queryOptions,
@@ -1,4 +1,3 @@
1
- // packages/dapp-kit/src/hooks/staking/useUnstakeApprove.ts
2
1
  import type { GetWalletProviderType, SpokeChainKey, TxReturnType, UnstakeParams } from '@sodax/sdk';
3
2
  import { useQueryClient } from '@tanstack/react-query';
4
3
  import { useSodaxContext } from '../shared/useSodaxContext.js';
@@ -6,20 +5,12 @@ import type { MutationHookParams } from '../shared/types.js';
6
5
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
7
6
  import { unwrapResult } from '../shared/unwrapResult.js';
8
7
 
9
- /**
10
- * Mutation variables for {@link useUnstakeApprove}. The `action` literal is injected by the hook.
11
- */
12
8
  export type UseUnstakeApproveVars<K extends SpokeChainKey = SpokeChainKey> = {
13
9
  params: Omit<UnstakeParams<K>, 'action'>;
14
10
  walletProvider: GetWalletProviderType<K>;
15
11
  };
16
12
 
17
- /**
18
- * React hook for approving xSODA spending on the unstake action.
19
- *
20
- * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
21
- * `onError`, `retry`). Returns the unwrapped tx return value on success.
22
- */
13
+ /** Throws on SDK failure (React Query error state); resolves to the unwrapped tx return value. */
23
14
  export function useUnstakeApprove<K extends SpokeChainKey = SpokeChainKey>({
24
15
  mutationOptions,
25
16
  }: MutationHookParams<TxReturnType<K, false>, UseUnstakeApproveVars<K>> = {}): SafeUseMutationResult<
@@ -12,10 +12,7 @@ export type UseUnstakingInfoParams = ReadHookParams<
12
12
  }
13
13
  >;
14
14
 
15
- /**
16
- * React hook to fetch the user's pending unstake requests by deriving the hub wallet from the
17
- * spoke `srcAddress` + `srcChainKey`. Throws on `!ok`.
18
- */
15
+ /** Throws on `!ok`. */
19
16
  export function useUnstakingInfo({
20
17
  params,
21
18
  queryOptions,
@@ -14,10 +14,7 @@ export type UseUnstakingInfoWithPenaltyParams = ReadHookParams<
14
14
  }
15
15
  >;
16
16
 
17
- /**
18
- * React hook to fetch the user's pending unstake requests **with computed early-exit penalties**
19
- * by deriving the hub wallet from the spoke `srcAddress` + `srcChainKey`. Throws on `!ok`.
20
- */
17
+ /** Includes computed early-exit penalties. Throws on `!ok`. */
21
18
  export function useUnstakingInfoWithPenalty({
22
19
  params,
23
20
  queryOptions,
@@ -1,4 +1,3 @@
1
- // packages/dapp-kit/src/hooks/swap/useCancelLimitOrder.ts
2
1
  import { useSodaxContext } from '../shared/useSodaxContext.js';
3
2
  import type { GetWalletProviderType, Intent, SpokeChainKey, TxHashPair } from '@sodax/sdk';
4
3
  import type { MutationHookParams } from '../shared/types.js';
@@ -12,12 +11,7 @@ type CancelLimitOrderParams<K extends SpokeChainKey = SpokeChainKey> = {
12
11
  timeout?: number;
13
12
  };
14
13
 
15
- /**
16
- * React hook for cancelling a limit-order intent.
17
- *
18
- * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
19
- * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
20
- */
14
+ /** Throws on SDK failure; resolves to the unwrapped `TxHashPair`. */
21
15
  export function useCancelLimitOrder({
22
16
  mutationOptions,
23
17
  }: MutationHookParams<TxHashPair, CancelLimitOrderParams> = {}): SafeUseMutationResult<
@@ -1,4 +1,3 @@
1
- // packages/dapp-kit/src/hooks/swap/useCancelSwap.ts
2
1
  import { useSodaxContext } from '../shared/useSodaxContext.js';
3
2
  import type { GetWalletProviderType, Intent, SpokeChainKey, TxHashPair } from '@sodax/sdk';
4
3
  import type { MutationHookParams } from '../shared/types.js';
@@ -11,12 +10,7 @@ type CancelIntentParams<K extends SpokeChainKey = SpokeChainKey> = {
11
10
  intent: Intent;
12
11
  };
13
12
 
14
- /**
15
- * React hook for cancelling an in-flight swap intent.
16
- *
17
- * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
18
- * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
19
- */
13
+ /** Throws on SDK failure; resolves to the unwrapped `TxHashPair`. */
20
14
  export function useCancelSwap({
21
15
  mutationOptions,
22
16
  }: MutationHookParams<TxHashPair, CancelIntentParams> = {}): SafeUseMutationResult<
@@ -1,5 +1,4 @@
1
1
  import { useQueryClient } from '@tanstack/react-query';
2
- // packages/dapp-kit/src/hooks/swap/useCreateLimitOrder.ts
3
2
  import { useSodaxContext } from '../shared/useSodaxContext.js';
4
3
  import type { LimitOrderActionParams, SpokeChainKey, SwapResponse } from '@sodax/sdk';
5
4
  import type { MutationHookParams } from '../shared/types.js';
@@ -7,22 +6,13 @@ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMu
7
6
  import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
8
7
  import { unwrapResult } from '../shared/unwrapResult.js';
9
8
 
10
- /**
11
- * Mutation variables for {@link useCreateLimitOrder}. Generic over `K extends SpokeChainKey`
12
- * (defaults to the full union). Sophisticated callers can lock K at the call site to narrow the
13
- * `walletProvider` and `params.srcChainKey` types.
14
- */
9
+ /** Lock `K` at the call site to narrow `walletProvider` and `params.srcChainKey`. */
15
10
  export type UseCreateLimitOrderVars<K extends SpokeChainKey = SpokeChainKey> = Omit<
16
11
  LimitOrderActionParams<K, false>,
17
12
  'raw'
18
13
  >;
19
14
 
20
- /**
21
- * React hook for creating a limit-order intent (no deadline).
22
- *
23
- * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
24
- * `onError`, `retry`). Returns the unwrapped `SwapResponse` on success.
25
- */
15
+ /** Creates a limit order (no deadline). Throws on SDK failure; resolves to the unwrapped `SwapResponse`. */
26
16
  export function useCreateLimitOrder<K extends SpokeChainKey = SpokeChainKey>({
27
17
  mutationOptions,
28
18
  }: MutationHookParams<SwapResponse, UseCreateLimitOrderVars<K>> = {}): SafeUseMutationResult<
@@ -12,13 +12,7 @@ import {
12
12
  toNotFoundBudgetRead,
13
13
  } from '../shared/solverStatusPolicy.js';
14
14
 
15
- /**
16
- * Guards the polling-stop invariant for `useDetailedStatus`. The two variants report terminality in
17
- * their own vocabularies, so the stop condition reads whichever source answered. Unresolved reads
18
- * share `useStatus`'s single budget — but only the ones that are ambiguous by nature (solver
19
- * `NOT_FOUND`, or a relay with no packet for the tx), never a dependency outage, which must keep
20
- * polling so it recovers on its own.
21
- */
15
+ // Only ambiguous reads (solver NOT_FOUND, no relay packet) spend the budget; an outage must keep polling.
22
16
 
23
17
  /** Derived from the public union so the fixtures track the wire contract without a cast. */
24
18
  type BackendStatus = Extract<DetailedSwapStatus, { source: 'backend' }>['data']['status'];
@@ -51,7 +45,7 @@ const outage = {
51
45
  error: new SodaxError('LOOKUP_FAILED', 'relay down', { feature: 'swap' }),
52
46
  };
53
47
 
54
- /** A key the backend rejected. Terminal, and reached before any budget — see the stop below. */
48
+ /** A key the backend rejected: terminal before any budget is spent. */
55
49
  const rejectedKey = {
56
50
  ok: false as const,
57
51
  error: new SodaxError('LOOKUP_FAILED', 'rejected', { feature: 'swap', context: { status: 401 } }),
@@ -73,9 +67,7 @@ const advance = (
73
67
  );
74
68
 
75
69
  describe('getSolverDetailedStatusRefetchInterval', () => {
76
- // Both terminal states of the `SubmitSwapTxStatusV2` wire contract. `'failed'` is unreachable via
77
- // `getDetailedStatus` today (the SDK routes abandoned records to the solver) — asserted here as
78
- // the hook's own contract, so a terminal record is never polled forever if that routing changes.
70
+ // `'failed'` is unreachable via `getDetailedStatus` today; asserted so a routing change never polls a terminal record forever.
79
71
  it.each(['solved', 'failed'] as const)('stops on a backend record at the terminal status %s', status => {
80
72
  expect(getSolverDetailedStatusRefetchInterval(ok(backend(status)), 0)).toBe(false);
81
73
  });
@@ -136,9 +128,7 @@ describe('getSolverDetailedStatusRefetchInterval', () => {
136
128
  expect(getSolverDetailedStatusRefetchInterval(rejected, 0)).toBe(false);
137
129
  });
138
130
 
139
- // The regression this guards: a rejected key leaves the backend unanswered, so a relay miss behind
140
- // it is unprovable and never tagged `DETAILED_STATUS_NOT_DELIVERED`. Without its own stop the read
141
- // would poll both endpoints forever, because the budget it would need to exhaust never advances.
131
+ // A rejected key hides any relay miss from the budget, so without its own stop it would poll forever.
142
132
  it('stops a rejected key even though the not-delivered budget never advances', () => {
143
133
  expect(advance(INITIAL_NOT_FOUND_STREAK, Array(MAX_NOT_FOUND_POLLS).fill(rejectedKey)).consecutiveNotFound).toBe(0);
144
134
  expect(getSolverDetailedStatusRefetchInterval(rejectedKey, 0)).toBe(false);
@@ -183,8 +173,7 @@ describe('detailed-status budget', () => {
183
173
  expect(getSolverDetailedStatusRefetchInterval(notFound, state.consecutiveNotFound)).toBe(false);
184
174
  });
185
175
 
186
- // The regression this guards: a swap whose relay packet never lands used to poll forever, because
187
- // every LOOKUP_FAILED reset the budget it should have been spending.
176
+ // Regression: a LOOKUP_FAILED must not reset the budget, or an undelivered packet polls forever.
188
177
  it('counts consecutive undelivered reads up to the cutoff, then stops', () => {
189
178
  const state = advance({ ...INITIAL_NOT_FOUND_STREAK }, Array(MAX_NOT_FOUND_POLLS).fill(notDelivered));
190
179
 
@@ -192,8 +181,7 @@ describe('detailed-status budget', () => {
192
181
  expect(getSolverDetailedStatusRefetchInterval(notDelivered, state.consecutiveNotFound)).toBe(false);
193
182
  });
194
183
 
195
- // The regression this guards: a 2-minute solver or relay outage used to exhaust the budget and
196
- // stop the poll for good, turning recoverable downtime into a permanently stuck status.
184
+ // Regression: an outage must not exhaust the budget, or recoverable downtime becomes a stuck status.
197
185
  it('never exhausts the budget on an outage, however long it runs', () => {
198
186
  const state = advance({ ...INITIAL_NOT_FOUND_STREAK }, Array(MAX_NOT_FOUND_POLLS * 2).fill(outage));
199
187
 
@@ -18,25 +18,8 @@ export type UseDetailedStatusParams = ReadHookParams<
18
18
  >;
19
19
 
20
20
  /**
21
- * Hook for monitoring a swap from its source-chain transaction.
22
- *
23
- * `useStatus` needs the hub tx hash and always asks the solver; this takes `(srcChainKey,
24
- * srcTxHash)` — the pair you hold after `swap()` — and routes to whichever source can answer.
25
- * `data.value` is discriminated on `source`, and each variant carries that source's payload
26
- * unmodified.
27
- *
28
- * Polls every 3s. Stops once the answering source is terminal, once the backend rejects the API
29
- * key, and — like `useStatus` — after 40 consecutive *ambiguous* reads: a solver `NOT_FOUND`, or a
30
- * `LOOKUP_FAILED` whose relay has no packet for the tx. Neither can distinguish "still in flight" from "never will be", so the budget
31
- * is what stops a swap nothing can resolve. A dependency outage — relay unreachable, solver down —
32
- * keeps polling instead, so the read recovers by itself; any real status resets the budget.
33
- * Override with `queryOptions.refetchInterval`.
34
- *
35
- * @example
36
- * ```typescript
37
- * const { data } = useDetailedStatus({ params: { srcChainKey, srcTxHash } });
38
- * if (data?.ok && data.value.source === 'backend') console.log(data.value.data.status);
39
- * ```
21
+ * Status by source tx `(srcChainKey, srcTxHash)`, routed to whichever source can answer; `data.value` is discriminated on `source`.
22
+ * Polls every 3s until terminal, API-key rejection, or 40 consecutive ambiguous reads (solver NOT_FOUND / no relay packet); outages keep polling.
40
23
  */
41
24
  export const useDetailedStatus = ({
42
25
  params,
@@ -69,9 +69,6 @@ describe('getSwapQuoteQueryOptions', () => {
69
69
  expect(hashKey(queryKey)).toContain('"amount":"1000000"');
70
70
  });
71
71
 
72
- // `getQuote` deducts the configured fee from `amount` before quoting, so it is an input to the
73
- // result even though it never appears in `payload`. Two providers with different swap fees must
74
- // not share a cache entry, and a reconfigured provider must not serve the old fee's quote.
75
72
  it('keys the configured swap partner fee', () => {
76
73
  const noFee = getSwapQuoteQueryOptions({ sodax: makeSodax().sodax, payload: PAYLOAD }).queryKey;
77
74
  const withFee = getSwapQuoteQueryOptions({
@@ -102,9 +99,7 @@ describe('getSwapQuoteQueryOptions', () => {
102
99
  expect(hashKey(queryKey)).toContain('7000');
103
100
  });
104
101
 
105
- // Pins the allow-list. If `SolverIntentQuoteRequest` gains a field, this fails and forces a
106
- // decision about whether it belongs in the key — rather than a spread silently carrying a new
107
- // bigint in and crashing `hashKey` at render time.
102
+ // Fails when `SolverIntentQuoteRequest` gains a field, forcing a deliberate key decision.
108
103
  it('keys exactly the known request fields', () => {
109
104
  const { sodax } = makeSodax();
110
105
  const { queryKey } = getSwapQuoteQueryOptions({ sodax, payload: PAYLOAD });
@@ -122,10 +117,9 @@ describe('getSwapQuoteQueryOptions', () => {
122
117
  );
123
118
  });
124
119
 
125
- // Key derivation runs during render, so it must not throw on a payload assembled from
126
- // partially-validated form state.
127
120
  it('derives a hashable key even when amount is missing', () => {
128
121
  const { sodax } = makeSodax();
122
+ // Simulates partially-validated form state; key derivation runs during render and must not throw.
129
123
  const malformed = { ...PAYLOAD, amount: undefined } as unknown as SolverIntentQuoteRequest;
130
124
 
131
125
  const { queryKey } = getSwapQuoteQueryOptions({ sodax, payload: malformed });
@@ -3,10 +3,7 @@ import { useSodaxContext } from '../shared/useSodaxContext.js';
3
3
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
4
4
  import type { ReadHookParams } from '../shared/types.js';
5
5
 
6
- /**
7
- * Derived from the SDK method rather than restated, so the error union stays exact and cannot
8
- * drift. `undefined` is the disabled state, before a `payload` exists.
9
- */
6
+ /** Derived from the SDK method so the error union cannot drift; `undefined` means disabled (no `payload`). */
10
7
  type SwapQuote = Awaited<ReturnType<Sodax['swaps']['getQuote']>> | undefined;
11
8
 
12
9
  export type UseQuoteParams = ReadHookParams<SwapQuote, { payload: SolverIntentQuoteRequest | undefined }>;
@@ -20,20 +17,8 @@ function feeKeyPart(fee: PartnerFee | undefined) {
20
17
  }
21
18
 
22
19
  /**
23
- * Includes the configured partner fee: `getQuote` deducts it from `amount` before quoting, so it
24
- * is a real input to the result even though it never appears in `payload`. Leaving it out lets two
25
- * providers configured with different fees share one cache entry, and lets a reconfigured provider
26
- * serve the previous fee's quote until the next poll — either way a `minOutputAmount` derived from
27
- * that quote can be unfillable.
28
- *
29
- * Fields are named explicitly rather than spread. A spread would carry any future bigint field on
30
- * `SolverIntentQuoteRequest` straight into the key, and `JSON.stringify` throws on bigint — so a
31
- * spread fails *open* into a render crash, while an allow-list fails *closed* into a missing key
32
- * segment. Add new fields here deliberately.
33
- *
34
- * `String(...)` rather than `.toString()`: a payload assembled from partially-validated form state
35
- * may not have an `amount` yet, and key derivation runs during render. Staying total lets the SDK's
36
- * own validation surface it instead of throwing past React Query.
20
+ * Keys on the partner fee too: `getQuote` deducts it from `amount`, so omitting it can serve another fee's (unfillable) quote.
21
+ * Fields are allow-listed, not spread, so a future bigint field cannot crash render; `String()` tolerates a missing `amount`.
37
22
  */
38
23
  function quoteKeyPart(payload: SolverIntentQuoteRequest | undefined, configuredFee: PartnerFee | undefined) {
39
24
  if (!payload) return undefined;
@@ -69,20 +54,8 @@ export function getSwapQuoteQueryOptions({
69
54
  }
70
55
 
71
56
  /**
72
- * Hook for fetching a quote for an intent-based swap.
73
- *
74
- * For a leverage-yield vault deposit or withdraw use `useLeverageYieldQuote` instead — this hook
75
- * deducts the effective *swap* fee, which is not what a vault intent charges.
76
- *
77
- * @example
78
- * ```typescript
79
- * const { data: quote, isLoading } = useQuote({ params: { payload } });
80
- * ```
81
- *
82
- * @remarks
83
- * - The quote is automatically refreshed every 3 seconds
84
- * - The query is disabled when payload is undefined
85
- * - Returns the SDK `Result` as `data`; branch on `data?.ok` rather than reading `isError`
57
+ * Polls every 3s; `data` is the SDK `Result`, so branch on `data?.ok`, not `isError`.
58
+ * Deducts the swap fee: use `useLeverageYieldQuote` for leverage-yield vault intents.
86
59
  */
87
60
  export const useQuote = ({ params, queryOptions }: UseQuoteParams = {}): UseQueryResult<SwapQuote> => {
88
61
  const { sodax } = useSodaxContext();
@@ -13,16 +13,8 @@ export type UseStatusParams = ReadHookParams<
13
13
  >;
14
14
 
15
15
  /**
16
- * Hook for monitoring the status of an intent-based swap.
17
- *
18
- * Polls every 3s while the intent is in flight. Stops on `SOLVED` (3) or `FAILED` (4). Stops after
19
- * 40 consecutive successful fetches while status stays `NOT_FOUND` (~2 min) — a forgotten intent
20
- * never changes. An in-flight status resets that streak. Override with `queryOptions.refetchInterval`.
21
- *
22
- * @example
23
- * ```typescript
24
- * const { data: status, isLoading } = useStatus({ params: { intentTxHash } });
25
- * ```
16
+ * Polls every 3s; stops on `SOLVED`/`FAILED` or after 40 consecutive `NOT_FOUND` reads (~2 min).
17
+ * An in-flight status resets that streak.
26
18
  */
27
19
  export const useStatus = ({
28
20
  params,
@@ -1,14 +1,4 @@
1
- /**
2
- * `useSwap` wire test for the per-action API key: `extras.apiKey` in the mutation vars must reach
3
- * the backend submit-tx leg as `x-api-key` — on the POST and on the status poll — beating the
4
- * instance-level key.
5
- *
6
- * Follows the package convention of testing hooks without a renderer (captured `mutationFn`), with
7
- * the SDK stubbed at the same seams its own backend 2-step tests use: `createIntent` is spied on a
8
- * real keyed `Sodax` so no wallet or chain is touched, while `POST /swaps/submit-tx` and
9
- * `GET /swaps/submit-tx/status` run call-through to a stubbed global fetch serving the schema-valid
10
- * fixtures from packages/sdk/src/swap/SwapService.test.ts.
11
- */
1
+ // `createIntent` is spied on a real keyed `Sodax` (no wallet/chain); submit-tx calls hit a stubbed global fetch.
12
2
 
13
3
  import { ChainKeys, Sodax } from '@sodax/sdk';
14
4
  import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -1,4 +1,3 @@
1
- // packages/dapp-kit/src/hooks/swap/useSwap.ts
2
1
  import { useSodaxContext } from '../shared/useSodaxContext.js';
3
2
  import { invalidateBalances } from '../shared/invalidateBalances.js';
4
3
  import type { SpokeChainKey, SwapActionParams, SwapResponse } from '@sodax/sdk';
@@ -8,19 +7,10 @@ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMu
8
7
  import { unwrapResult } from '../shared/unwrapResult.js';
9
8
  import { retryBeforeSubmission } from '../shared/retryBeforeSubmission.js';
10
9
 
11
- /**
12
- * Mutation variables for {@link useSwap}. Generic over `K extends SpokeChainKey` (defaults to the
13
- * full union). Sophisticated callers can lock K at the hook call site to narrow the
14
- * `walletProvider` and `params.srcChainKey` types.
15
- */
10
+ /** Lock `K` at the call site to narrow `walletProvider` and `params.srcChainKey`. */
16
11
  export type UseSwapVars<K extends SpokeChainKey = SpokeChainKey> = Omit<SwapActionParams<K, false>, 'raw'>;
17
12
 
18
- /**
19
- * React hook for executing an intent-based cross-chain swap.
20
- *
21
- * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
22
- * `onError`, `retry`). Returns the unwrapped `SwapResponse` on success.
23
- */
13
+ /** Throws on SDK failure; resolves to the unwrapped `SwapResponse` and invalidates balances. */
24
14
  export function useSwap<K extends SpokeChainKey = SpokeChainKey>({
25
15
  mutationOptions,
26
16
  }: MutationHookParams<SwapResponse, UseSwapVars<K>> = {}): SafeUseMutationResult<SwapResponse, Error, UseSwapVars<K>> {
@@ -23,8 +23,7 @@ export function useSwapAllowance<K extends SpokeChainKey>({
23
23
  const walletProvider = params?.walletProvider;
24
24
 
25
25
  return useQuery<boolean, Error>({
26
- // Extract the (chain, owner, token, amount) tuple that actually scopes the allowance —
27
- // raw-object keys break per Rule 4 (bigints) and churn on every render.
26
+ // Key on the scoping tuple only: raw payload objects hold bigints and churn every render.
28
27
  queryKey: [
29
28
  'swap',
30
29
  'allowance',
@@ -15,13 +15,8 @@ export type UseSwapApprovalStrategyParams<K extends SpokeChainKey = SpokeChainKe
15
15
  >;
16
16
 
17
17
  /**
18
- * Which approval path {@link useSwapWithApproval} would take for this swap: `'not-required'`,
19
- * `'atomic-batch'` (approve + swap in one EIP-5792 signature) or `'sequential'` (approve, then
20
- * swap). Use it to label the swap button before the user clicks. Pass the same `allowAccountUpgrade`
21
- * you give the swap.
22
- *
23
- * Not polled: `useSwapWithApproval` invalidates it after a successful swap, and the swap itself
24
- * re-reads the strategy at execution, so a stale label never picks the wrong path.
18
+ * Predicts the approval path {@link useSwapWithApproval} will take; pass the same `allowAccountUpgrade`.
19
+ * Not polled: the swap re-reads the strategy at execution, so a stale label never picks the wrong path.
25
20
  */
26
21
  export function useSwapApprovalStrategy<K extends SpokeChainKey = SpokeChainKey>({
27
22
  params,
@@ -1,4 +1,3 @@
1
- // packages/dapp-kit/src/hooks/swap/useSwapApprove.ts
2
1
  import { useSodaxContext } from '../shared/useSodaxContext.js';
3
2
  import { useQueryClient } from '@tanstack/react-query';
4
3
  import type {
@@ -12,24 +11,13 @@ import type { MutationHookParams } from '../shared/types.js';
12
11
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
13
12
  import { unwrapResult } from '../shared/unwrapResult.js';
14
13
 
15
- /**
16
- * Mutation variables for {@link useSwapApprove}. Generic over `K extends SpokeChainKey` (defaults
17
- * to the full union). Sophisticated callers can lock K at the call site to narrow the
18
- * `walletProvider` and `params.srcChainKey` types.
19
- */
14
+ /** Lock `K` at the call site to narrow `walletProvider` and `params.srcChainKey`. */
20
15
  export type UseSwapApproveVars<K extends SpokeChainKey = SpokeChainKey> = {
21
16
  params: CreateIntentParams<K> | CreateLimitOrderParams<K>;
22
17
  walletProvider: GetWalletProviderType<K>;
23
18
  };
24
19
 
25
- /**
26
- * React hook for approving ERC-20 token spending (or trustline establishment) for a swap or
27
- * limit-order intent.
28
- *
29
- * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
30
- * `onError`, `retry`). Returns the unwrapped tx return value on success. Invalidates all
31
- * `['swap', 'allowance', ...]` queries so any pending allowance check refreshes.
32
- */
20
+ /** Approves spending (or sets a trustline). Throws on SDK failure; invalidates `['swap', 'allowance']` on success. */
33
21
  export function useSwapApprove<K extends SpokeChainKey = SpokeChainKey>({
34
22
  mutationOptions,
35
23
  }: MutationHookParams<TxReturnType<K, false>, UseSwapApproveVars<K>> = {}): SafeUseMutationResult<
@@ -13,15 +13,16 @@ const swapHook = vi.fn();
13
13
  const statusHook = vi.fn();
14
14
  const stellarHook = vi.fn();
15
15
  const nearHook = vi.fn();
16
+ const xrpHook = vi.fn();
16
17
  const fetchingChecks = vi.fn(() => 0);
17
18
 
18
- // The lifecycle is composition plus a pure resolver (covered in utils/swapLifecycle.test.ts), so the
19
- // sub-hooks are stubbed and the hook runs as a plain function.
19
+ // The resolver is covered in utils/swapLifecycle.test.ts, so sub-hooks are stubbed and the hook runs as a plain function.
20
20
  vi.mock('./useSwapApprovalStrategy.js', () => ({ useSwapApprovalStrategy: (args: unknown) => strategyHook(args) }));
21
21
  vi.mock('./useSwapWithApproval.js', () => ({ useSwapWithApproval: (args: unknown) => swapHook(args) }));
22
22
  vi.mock('./useDetailedStatus.js', () => ({ useDetailedStatus: (args: unknown) => statusHook(args) }));
23
23
  vi.mock('../shared/useStellarGate.js', () => ({ useStellarGate: (args: unknown) => stellarHook(args) }));
24
24
  vi.mock('../shared/useNearStorageGate.js', () => ({ useNearStorageGate: (args: unknown) => nearHook(args) }));
25
+ vi.mock('../shared/useXrpGate.js', () => ({ useXrpGate: (args: unknown) => xrpHook(args) }));
25
26
  // Its own state is one ref; a fresh one per run() is a fresh mount.
26
27
  vi.mock('react', () => ({ useRef: (initial: unknown) => ({ current: initial }) }));
27
28
  vi.mock('@tanstack/react-query', () => ({ useIsFetching: () => fetchingChecks() }));
@@ -56,6 +57,8 @@ const openGate = {
56
57
  blocksAction: false,
57
58
  isNear: false,
58
59
  needsRegistration: false,
60
+ isXrpIssuedToken: false,
61
+ blockedReason: undefined,
59
62
  activate: vi.fn(),
60
63
  requestTrustline: vi.fn(),
61
64
  retry: vi.fn(),
@@ -68,12 +71,14 @@ const stub = ({
68
71
  status,
69
72
  stellar = {},
70
73
  near = {},
74
+ xrp = {},
71
75
  }: {
72
76
  swap?: Record<string, unknown>;
73
77
  strategy?: string;
74
78
  status?: unknown;
75
79
  stellar?: Record<string, unknown>;
76
80
  near?: Record<string, unknown>;
81
+ xrp?: Record<string, unknown>;
77
82
  } = {}) => {
78
83
  strategyHook.mockReturnValue({ data: strategy, error: null, refetch: refetchStrategy });
79
84
  swapHook.mockReturnValue({
@@ -88,6 +93,7 @@ const stub = ({
88
93
  statusHook.mockReturnValue({ data: status });
89
94
  stellarHook.mockReturnValue({ ...openGate, ...stellar });
90
95
  nearHook.mockReturnValue({ ...openGate, ...near });
96
+ xrpHook.mockReturnValue({ ...openGate, ...xrp });
91
97
  };
92
98
 
93
99
  const run = (overrides: Partial<Parameters<typeof useSwapLifecycle>[0]> = {}) =>
@@ -192,6 +198,8 @@ describe('useSwapLifecycle', () => {
192
198
  [{ stellar: { isStellar: true, needsTrustline: true, blocksAction: true } }, 'requestTrustline'],
193
199
  [{ stellar: { isStellar: true, checkFailed: true, blocksAction: true } }, 'retry'],
194
200
  [{ near: { isNear: true, needsRegistration: true, blocksAction: true } }, 'registerStorage'],
201
+ [{ xrp: { isXrpIssuedToken: true, needsTrustline: true, blocksAction: true } }, 'requestTrustline'],
202
+ [{ xrp: { isXrpIssuedToken: true, checkFailed: true, blocksAction: true } }, 'retry'],
195
203
  ] as const)('runs the matching setup action', async (gates, action) => {
196
204
  stub(gates);
197
205
  const lifecycle = run();
@@ -211,6 +219,43 @@ describe('useSwapLifecycle', () => {
211
219
  expect(nearHook).toHaveBeenCalledWith(expect.objectContaining({ accountId: PARAMS.dstAddress }));
212
220
  });
213
221
 
222
+ it('sizes the XRPL trustline check as the SDK sizes its check before signing', () => {
223
+ stub();
224
+ run({ intentParams: { ...PARAMS, dstChainKey: ChainKeys.XRP_MAINNET } });
225
+
226
+ expect(xrpHook).toHaveBeenCalledWith(
227
+ expect.objectContaining({
228
+ dstChainKey: ChainKeys.XRP_MAINNET,
229
+ address: PARAMS.dstAddress,
230
+ token: PARAMS.outputToken,
231
+ amount: PARAMS.minOutputAmount,
232
+ maxAmount: PARAMS.minOutputAmount * 2n,
233
+ }),
234
+ );
235
+ });
236
+
237
+ it.each([
238
+ ['xrpBlocked', { blockedReason: 'issuer_frozen' }],
239
+ ['xrpFunding', { needsFunding: true }],
240
+ ] as const)('leaves %s to the app and sends nothing', async (reason, gate) => {
241
+ stub({ xrp: { isXrpIssuedToken: true, blocksAction: true, ...gate } });
242
+ const lifecycle = run();
243
+
244
+ expect(lifecycle.state).toEqual({ kind: 'needsSetup', reason });
245
+ expect(await lifecycle.next()).toBeUndefined();
246
+ expect(openGate.requestTrustline).not.toHaveBeenCalled();
247
+ expect(mutateAsyncSafe).not.toHaveBeenCalled();
248
+ });
249
+
250
+ it('holds the XRPL trustline step while its TrustSet is in flight', async () => {
251
+ stub({ xrp: { isXrpIssuedToken: true, needsTrustline: true, blocksAction: true, isRequestingTrustline: true } });
252
+ const lifecycle = run();
253
+
254
+ expect(lifecycle.state).toEqual({ kind: 'checking' });
255
+ await lifecycle.next();
256
+ expect(openGate.requestTrustline).not.toHaveBeenCalled();
257
+ });
258
+
214
259
  it('retries a failed NEAR storage check instead of swapping', async () => {
215
260
  const nearRetry = vi.fn();
216
261
  stub({ near: { isNear: true, checkFailed: true, retry: nearRetry } });