@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
@@ -0,0 +1,112 @@
1
+ import { ChainKeys, IndeterminateOutcomeError } from '@sodax/sdk';
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ const invalidateQueries = vi.fn();
5
+ const requestTrustline = vi.fn();
6
+
7
+ // Stubbing the React-side imports lets the real mutationFn and onSuccess run without a DOM.
8
+ vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
9
+ vi.mock('./useSodaxContext.js', () => ({
10
+ useSodaxContext: () => ({ sodax: { spoke: { xrp: { requestTrustline } } } }),
11
+ }));
12
+ vi.mock('./useSafeMutation.js', () => ({ useSafeMutation: (options: unknown) => options }));
13
+
14
+ const { useEstablishXrpTrustline } = await import('./useEstablishXrpTrustline.js');
15
+
16
+ const TOKEN = 'rMxCKbEDwqr76QuheSUMdEGf4B9xJ8m5De';
17
+ const ADDRESS = 'rJB8dmrf4JxkLKHPUfdxyPwpXMyxjkQsyG';
18
+
19
+ type OnSuccess = (data: string, vars: unknown, ctx: unknown) => Promise<void>;
20
+ type MutationFn = (vars: unknown) => Promise<string>;
21
+
22
+ const vars = (getWalletAddress: () => Promise<string>) => ({ token: TOKEN, walletProvider: { getWalletAddress } });
23
+
24
+ // The stubbed useSafeMutation returns its options, which the hook's declared return type does not describe.
25
+ const optionsOf = (retry?: number) =>
26
+ useEstablishXrpTrustline({ mutationOptions: { retry } }) as unknown as {
27
+ onSuccess: OnSuccess;
28
+ mutationFn: MutationFn;
29
+ retry: (failureCount: number, error: Error) => boolean;
30
+ };
31
+
32
+ const invalidatedKeys = () => invalidateQueries.mock.calls.map(([arg]) => arg.queryKey);
33
+
34
+ beforeEach(() => {
35
+ invalidateQueries.mockReset();
36
+ requestTrustline.mockReset();
37
+ });
38
+
39
+ describe('useEstablishXrpTrustline', () => {
40
+ it('requests the trustline for the wallet account and returns the validated hash', async () => {
41
+ requestTrustline.mockResolvedValue({ ok: true, value: 'hash' });
42
+ const request = vars(async () => ADDRESS);
43
+
44
+ await expect(optionsOf().mutationFn(request)).resolves.toBe('hash');
45
+ expect(requestTrustline).toHaveBeenCalledWith({
46
+ srcAddress: ADDRESS,
47
+ token: TOKEN,
48
+ walletProvider: request.walletProvider,
49
+ });
50
+ });
51
+
52
+ it('refuses, before signing, a wallet connected to another account than the one that needs the line', async () => {
53
+ const request = { ...vars(async () => ADDRESS), address: 'rOtherAccount1111111111111111111111' };
54
+
55
+ await expect(optionsOf().mutationFn(request)).rejects.toThrow(/is not rOtherAccount/);
56
+ expect(requestTrustline).not.toHaveBeenCalled();
57
+ });
58
+
59
+ it('proceeds when the wallet controls the account that needs the line', async () => {
60
+ requestTrustline.mockResolvedValue({ ok: true, value: 'hash' });
61
+
62
+ await expect(optionsOf().mutationFn({ ...vars(async () => ADDRESS), address: ADDRESS })).resolves.toBe('hash');
63
+ });
64
+
65
+ it('rejects with the SDK error, so mutateAsyncSafe reports it', async () => {
66
+ const error = new Error('GemWallet transaction was rejected by the user');
67
+ requestTrustline.mockResolvedValue({ ok: false, error });
68
+
69
+ await expect(optionsOf().mutationFn(vars(async () => ADDRESS))).rejects.toBe(error);
70
+ });
71
+
72
+ it('invalidates the destination check for this account, the reserve check, and XRPL balances', async () => {
73
+ await optionsOf().onSuccess(
74
+ 'hash',
75
+ vars(async () => ADDRESS),
76
+ undefined,
77
+ );
78
+
79
+ expect(invalidatedKeys()).toEqual([
80
+ ['shared', 'xrpDestinationCheck', ChainKeys.XRP_MAINNET, TOKEN, ADDRESS],
81
+ ['shared', 'xrpTrustlineReserveCheck'],
82
+ ['shared', 'balances', ChainKeys.XRP_MAINNET],
83
+ ['shared', 'xBalances', ChainKeys.XRP_MAINNET],
84
+ ]);
85
+ });
86
+
87
+ it('invalidates the checked account even after the wallet switched to another one', async () => {
88
+ await optionsOf().onSuccess(
89
+ 'hash',
90
+ { ...vars(async () => 'rOtherAccount1111111111111111111111'), address: ADDRESS },
91
+ undefined,
92
+ );
93
+
94
+ expect(invalidatedKeys()[0]).toEqual(['shared', 'xrpDestinationCheck', ChainKeys.XRP_MAINNET, TOKEN, ADDRESS]);
95
+ });
96
+
97
+ it('never retries a TrustSet that may have been sent, since each one costs a fee', () => {
98
+ const { retry } = optionsOf(3);
99
+
100
+ expect(retry(0, new IndeterminateOutcomeError('outcome unknown', { cause: undefined, txHash: 'AB' }))).toBe(false);
101
+ expect(retry(0, new Error('node unreachable'))).toBe(true);
102
+ });
103
+
104
+ it('still invalidates when the wallet fails right after the TrustSet validated', async () => {
105
+ const locked = vars(async () => {
106
+ throw new Error('wallet is locked');
107
+ });
108
+
109
+ await expect(optionsOf().onSuccess('hash', locked, undefined)).resolves.toBeUndefined();
110
+ expect(invalidatedKeys()[0]).toEqual(['shared', 'xrpDestinationCheck']);
111
+ });
112
+ });
@@ -0,0 +1,63 @@
1
+ import { ChainKeys, type IXrpWalletProvider } from '@sodax/sdk';
2
+ import { useQueryClient } from '@tanstack/react-query';
3
+ import { invalidateBalances } from './invalidateBalances.js';
4
+ import { retryBeforeSubmission } from './retryBeforeSubmission.js';
5
+ import type { MutationHookParams } from './types.js';
6
+ import { useSafeMutation, type SafeUseMutationResult } from './useSafeMutation.js';
7
+ import { useSodaxContext } from './useSodaxContext.js';
8
+ import { unwrapResult } from './unwrapResult.js';
9
+
10
+ export type UseEstablishXrpTrustlineVars = {
11
+ token: string;
12
+ /** When set, the mutation refuses a wallet connected to another account. */
13
+ address?: string;
14
+ walletProvider: IXrpWalletProvider;
15
+ };
16
+
17
+ /**
18
+ * Creates or raises the XRPL trustline; resolves to the validated TrustSet hash. The account pays the fee
19
+ * and possibly an owner reserve: check with {@link useXrpGate} before asking the user to sign.
20
+ */
21
+ export function useEstablishXrpTrustline({
22
+ mutationOptions,
23
+ }: MutationHookParams<string, UseEstablishXrpTrustlineVars> = {}): SafeUseMutationResult<
24
+ string,
25
+ Error,
26
+ UseEstablishXrpTrustlineVars
27
+ > {
28
+ const { sodax } = useSodaxContext();
29
+ const queryClient = useQueryClient();
30
+
31
+ return useSafeMutation<string, Error, UseEstablishXrpTrustlineVars>({
32
+ mutationKey: ['shared', 'establishXrpTrustline'],
33
+ ...mutationOptions,
34
+ // Each TrustSet costs a fee, so one that may have been sent is never signed again automatically.
35
+ retry: retryBeforeSubmission(
36
+ mutationOptions?.retry ??
37
+ queryClient.getMutationDefaults?.(mutationOptions?.mutationKey ?? ['shared', 'establishXrpTrustline'])?.retry ??
38
+ queryClient.getDefaultOptions?.().mutations?.retry,
39
+ ),
40
+ mutationFn: async ({ token, address, walletProvider }): Promise<string> => {
41
+ const srcAddress = await walletProvider.getWalletAddress();
42
+ if (address !== undefined && address !== srcAddress) {
43
+ throw new Error(
44
+ `The connected XRPL account ${srcAddress} is not ${address}, which needs the trustline — connect ${address} to add it`,
45
+ );
46
+ }
47
+ return unwrapResult(await sodax.spoke.xrp.requestTrustline<false>({ srcAddress, token, walletProvider }));
48
+ },
49
+ onSuccess: async (data, vars, ctx) => {
50
+ // The checked account, not whichever account the wallet is on by now.
51
+ const address = vars.address ?? (await vars.walletProvider.getWalletAddress().catch(() => undefined));
52
+ queryClient.invalidateQueries({
53
+ queryKey: address
54
+ ? ['shared', 'xrpDestinationCheck', ChainKeys.XRP_MAINNET, vars.token, address]
55
+ : ['shared', 'xrpDestinationCheck'],
56
+ });
57
+ // A new line locks an owner reserve, which changes what the next trustline can afford.
58
+ queryClient.invalidateQueries({ queryKey: ['shared', 'xrpTrustlineReserveCheck'] });
59
+ invalidateBalances(queryClient, ChainKeys.XRP_MAINNET);
60
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
61
+ },
62
+ });
63
+ }
@@ -1,4 +1,3 @@
1
- // packages/dapp-kit/src/hooks/shared/useEstimateGas.ts
2
1
  import type { EstimateGasParams, GetEstimateGasReturnType, SpokeChainKey } from '@sodax/sdk';
3
2
  import { useSodaxContext } from './useSodaxContext.js';
4
3
  import type { MutationHookParams } from './types.js';
@@ -13,24 +13,7 @@ export type UseGetUserHubWalletAddressParams = ReadHookParams<
13
13
  }
14
14
  >;
15
15
 
16
- /**
17
- * Hook for deriving user wallet address for hub abstraction.
18
- *
19
- * This hook derives the user's abstracted wallet address for the hub chain based on the spoke chain ID and address.
20
- * If the spoke chain is the same as the hub chain, it returns the encoded spoke address.
21
- * Otherwise, it derives and returns the abstracted wallet address for cross-chain operations.
22
- * NOTE: This hook is different from useDeriveUserWalletAddress because it uses wallet router address instead of CREATE3 address for Sonic (hub).
23
- *
24
- * The query is automatically enabled when both `spokeChainId` and `spokeAddress` are provided.
25
- * This is a deterministic operation, so the result is cached and not refetched automatically.
26
- *
27
- * @example
28
- * ```typescript
29
- * const { data: derivedAddress, isLoading, error } = useGetUserHubWalletAddress({
30
- * params: { spokeChainId, spokeAddress: userAddress },
31
- * });
32
- * ```
33
- */
16
+ /** Unlike `useDeriveUserWalletAddress`, uses the wallet router address (not CREATE3) for the hub chain. */
34
17
  export function useGetUserHubWalletAddress({
35
18
  params,
36
19
  queryOptions,
@@ -13,15 +13,8 @@ export type UseNearStorageCheckParams = ReadHookParams<
13
13
  >;
14
14
 
15
15
  /**
16
- * Whether `accountId` is NEP-141 storage-registered for `token` on NEAR — the receive-side
17
- * prerequisite for any leg that delivers a token to the user on NEAR (swap output on NEAR, bridge
18
- * into NEAR, money-market borrow/withdraw to NEAR). NEAR's analogue of a Stellar trustline.
19
- *
20
- * Returns `true` (no gate) when `chainId` is not NEAR, mirroring how the Stellar trustline check
21
- * short-circuits off-chain. Native NEAR is not a NEP-141 token, so the SDK reports it as registered.
22
- *
23
- * Pair with {@link useRegisterNearStorage} to perform the one-time `storage_deposit` when this
24
- * resolves to `false`.
16
+ * Whether `accountId` is NEP-141 storage-registered to receive `token` on NEAR. Resolves `true` when
17
+ * `chainId` is not NEAR; native NEAR always reads as registered.
25
18
  */
26
19
  export function useNearStorageCheck({
27
20
  params,
@@ -4,38 +4,28 @@ import { useNearStorageCheck } from './useNearStorageCheck.js';
4
4
  import { useRegisterNearStorage } from './useRegisterNearStorage.js';
5
5
 
6
6
  export interface UseNearStorageGateParams {
7
- /** Destination chain the token is delivered on; `undefined` (not chosen yet) leaves the gate inert. */
7
+ /** `undefined` (not chosen yet) leaves the gate inert. */
8
8
  dstChainKey: SpokeChainKey | undefined;
9
- /** Destination token address the recipient must be registered for. */
10
9
  token: string | undefined;
11
- /** Recipient NEAR account id. */
12
10
  accountId: string | undefined;
13
- /** Destination wallet provider; only consumed when it is the NEAR provider. */
11
+ /** Only consumed when it is the NEAR provider. */
14
12
  walletProvider: GetWalletProviderType<SpokeChainKey> | undefined;
15
13
  }
16
14
 
17
15
  export interface NearStorageGate {
18
- /** Destination is NEAR. */
19
16
  isNear: boolean;
20
- /** Destination is NEAR and the recipient is not yet storage-registered for `token`. */
21
17
  needsRegistration: boolean;
22
- /** The downstream action must stay disabled while the gate is unresolved or unmet. */
18
+ /** True while the gate is unresolved or unmet. */
23
19
  blocksAction: boolean;
24
- /** The registration-status query is actively fetching. */
25
20
  isChecking: boolean;
26
- /** Destination is NEAR and the registration check failed, so whether the recipient can receive is unknown. */
27
21
  checkFailed: boolean;
28
- /** Re-run the registration check. */
29
22
  retry: () => void;
30
- /** A `storage_deposit` tx is in flight. */
31
23
  isRegistering: boolean;
32
- /** Submit the `storage_deposit`; resolves to the SDK `Result` or `undefined` if inputs are missing. */
24
+ /** Resolves to `undefined` if inputs are missing. */
33
25
  registerStorage: () => Promise<Result<string> | undefined>;
34
26
  }
35
27
 
36
- /**
37
- * NEP-141 storage-registration gate for flows that deliver a token to a user on NEAR.
38
- */
28
+ /** NEP-141 storage-registration gate for flows that deliver a token to a user on NEAR. */
39
29
  export function useNearStorageGate({
40
30
  dstChainKey,
41
31
  token,
@@ -12,16 +12,7 @@ export type UseRegisterNearStorageVars = {
12
12
  deposit?: bigint;
13
13
  };
14
14
 
15
- /**
16
- * Submit a NEP-141 `storage_deposit` so `accountId` can receive `token` on NEAR. NEAR's analogue of
17
- * requesting a Stellar trustline; pair with {@link useNearStorageCheck} and call this when the check
18
- * resolves to `false`. The recipient's NEAR wallet signs the registration tx.
19
- *
20
- * Pure mutation: pass `{ token, accountId, walletProvider }` to `mutate(...)`. The hook itself only
21
- * takes the structural `mutationOptions` slot. `registerStorage` throws natively (no `Result<T>`),
22
- * so this hook is registered as `nativeThrow` in the mutation contract. On success it invalidates
23
- * the matching {@link useNearStorageCheck} query.
24
- */
15
+ /** NEP-141 `storage_deposit` so `accountId` can receive `token` on NEAR; the recipient's wallet signs. */
25
16
  export function useRegisterNearStorage({
26
17
  mutationOptions,
27
18
  }: MutationHookParams<string, UseRegisterNearStorageVars> = {}): SafeUseMutationResult<
@@ -34,6 +25,7 @@ export function useRegisterNearStorage({
34
25
  return useSafeMutation<string, Error, UseRegisterNearStorageVars>({
35
26
  mutationKey: ['shared', 'registerNearStorage'],
36
27
  ...mutationOptions,
28
+ // `registerStorage` throws natively (no Result), hence `nativeThrow` in the mutation contract.
37
29
  mutationFn: async ({ token, accountId, walletProvider, deposit }) =>
38
30
  sodax.spoke.near.registerStorage({ token, accountId, walletProvider, deposit, raw: false }),
39
31
  onSuccess: async (data, vars, ctx) => {
@@ -14,8 +14,7 @@ let mutation: MutationState;
14
14
  const refSlots: Array<{ current: unknown }> = [];
15
15
  let refCursor = 0;
16
16
 
17
- // Only useRef and useCallback are needed, and call order is stable, so this replays React's
18
- // slot semantics well enough to observe the deprecated hook across renders — no DOM, no renderer.
17
+ // Replays React's ref slots by call order, enough to observe the hook across renders without a DOM.
19
18
  vi.mock('react', () => ({
20
19
  useRef: (initial: unknown) => {
21
20
  const slot = refSlots[refCursor] ?? { current: initial };
@@ -39,12 +38,9 @@ const idle: MutationState = {
39
38
  data: undefined,
40
39
  };
41
40
 
42
- /** One render of the hook, with the mutation in `state`. */
43
41
  const render = (state: Partial<MutationState> = {}) => {
44
42
  mutation = { ...idle, ...state };
45
43
  refCursor = 0;
46
- // The positional argument was ignored in 2.0.0 and still is; passed here because keeping it
47
- // callable is the point of this wrapper.
48
44
  return useRequestTrustline(TOKEN);
49
45
  };
50
46
 
@@ -79,8 +75,6 @@ describe('useRequestTrustline — 2.0.0 compatibility wrapper', () => {
79
75
  expect(first.isRequested).toBe(true);
80
76
  expect(first.data).toBe('hash');
81
77
 
82
- // React Query clears data and isSuccess once the next attempt starts; 2.0.0 held both
83
- // in component state and never cleared them.
84
78
  const retrying = render({ isPending: true });
85
79
  expect(retrying.isRequested).toBe(true);
86
80
  expect(retrying.data).toBe('hash');
@@ -1,10 +1,7 @@
1
1
  import { useCallback, useRef } from 'react';
2
2
  import { useEstablishTrustline, type UseEstablishTrustlineVars } from './useEstablishTrustline.js';
3
3
 
4
- /**
5
- * The shape released in 2.0.0. Declared explicitly so a change to it fails
6
- * `checkTs` here rather than silently breaking consumers.
7
- */
4
+ // The 2.0.0 shape, declared explicitly so a change fails `checkTs` here instead of breaking consumers.
8
5
  type ReleasedRequestTrustline = {
9
6
  requestTrustline: (params: UseEstablishTrustlineVars) => Promise<string>;
10
7
  isLoading: boolean;
@@ -14,20 +11,13 @@ type ReleasedRequestTrustline = {
14
11
  };
15
12
 
16
13
  /**
17
- * Establish a Stellar trustline.
18
- *
19
- * @deprecated Use {@link useEstablishTrustline}, the canonical mutation hook, which exposes
20
- * `mutate` / `mutateAsync` / `mutateAsyncSafe` and accepts `mutationOptions`. This wrapper
21
- * preserves the shape released in 2.0.0 and will be removed in the next major.
22
- *
23
- * @param token - Ignored, as it was in 2.0.0. Accepted only so existing call sites compile.
14
+ * @deprecated Use {@link useEstablishTrustline}; removed in the next major. `token` is ignored, as in 2.0.0.
24
15
  */
25
16
  export function useRequestTrustline(token?: string | undefined): ReleasedRequestTrustline {
26
17
  const { mutateAsync, isPending, isSuccess, error, data } = useEstablishTrustline();
27
18
 
28
- // 2.0.0 held `isRequested` and `data` in component state and never cleared them, whereas
29
- // React Query resets its equivalents when the next attempt starts. Latch to keep the
30
- // released semantics: a retry that fails must not un-report the trustline that succeeded.
19
+ // Latch like 2.0.0 did: React Query resets these on the next attempt, but a failed retry
20
+ // must not un-report a trustline that succeeded.
31
21
  const requested = useRef(false);
32
22
  const lastData = useRef<string | null>(null);
33
23
  if (isSuccess) requested.current = true;
@@ -26,8 +26,6 @@ describe('toResult', () => {
26
26
  });
27
27
 
28
28
  it('does not catch synchronous throws above the await — caller must produce a Promise', async () => {
29
- // Documents the contract: toResult only neutralizes Promise rejections, not sync throws
30
- // before the Promise is constructed. Hooks always pass `mutateAsync(vars)` which is async.
31
29
  const wrapped = (): Promise<Result<number>> =>
32
30
  toResult(
33
31
  (async () => {
@@ -39,5 +37,4 @@ describe('toResult', () => {
39
37
  });
40
38
  });
41
39
 
42
- // Local type alias to keep the file self-contained — mirrors @sodax/sdk's Result<T>.
43
40
  type Result<T> = { ok: true; value: T } | { ok: false; error: unknown };
@@ -1,4 +1,3 @@
1
- // packages/dapp-kit/src/hooks/shared/useSafeMutation.ts
2
1
  import type { Result } from '@sodax/sdk';
3
2
  import {
4
3
  useMutation,
@@ -10,35 +9,16 @@ import {
10
9
  import { useCallback } from 'react';
11
10
  import { retryBeforeSubmission } from './retryBeforeSubmission.js';
12
11
 
13
- /**
14
- * Return shape of every dapp-kit mutation hook. Extends `UseMutationResult` with one extra
15
- * method, `mutateAsyncSafe`, that never rejects — it returns the SDK's `Result<T>` shape so
16
- * callers can branch on `.ok` without `try/catch`.
17
- *
18
- * The underlying `mutationFn` still throws on SDK failure, so React Query's native error model
19
- * (`isError`, `error`, `onError`, `retry`, `throwOnError`, devtools) keeps working as documented.
20
- */
21
12
  export type SafeUseMutationResult<TData, TError, TVars, TContext = unknown> = UseMutationResult<
22
13
  TData,
23
14
  TError,
24
15
  TVars,
25
16
  TContext
26
17
  > & {
27
- /**
28
- * Like `mutateAsync` but never rejects. Returns `Result<TData>` so callers can branch
29
- * on `.ok` without `try/catch`.
30
- *
31
- * Use this for imperative flows where rejection-style errors are awkward — e.g. sequential
32
- * `if (!hasAllowance) await approve(...); await action(...)` chains where the user-reject
33
- * case is the modal failure mode, not an exceptional one.
34
- */
18
+ /** Like `mutateAsync` but never rejects; resolves to `Result<TData>`. */
35
19
  mutateAsyncSafe: (vars: TVars, options?: MutateOptions<TData, TError, TVars, TContext>) => Promise<Result<TData>>;
36
20
  };
37
21
 
38
- /**
39
- * Wraps a `Promise<T>` (typically `mutateAsync(vars)`) into a `Promise<Result<T>>` that never
40
- * rejects. Pure, side-effect-free — extracted for unit testing.
41
- */
42
22
  export async function toResult<T>(promise: Promise<T>): Promise<Result<T>> {
43
23
  try {
44
24
  const value = await promise;
@@ -48,11 +28,7 @@ export async function toResult<T>(promise: Promise<T>): Promise<Result<T>> {
48
28
  }
49
29
  }
50
30
 
51
- /**
52
- * Drop-in replacement for `useMutation` that augments the result with `mutateAsyncSafe`. Used
53
- * by every dapp-kit mutation hook so consumers can pick rejection-style (`mutateAsync`) or
54
- * Result-style (`mutateAsyncSafe`) ergonomics without the hook author having to think about it.
55
- */
31
+ /** `useMutation` plus `mutateAsyncSafe`; retries are suppressed once funds may have moved. */
56
32
  export function useSafeMutation<TData, TError, TVars, TContext = unknown>(
57
33
  options: UseMutationOptions<TData, TError, TVars, TContext>,
58
34
  ): SafeUseMutationResult<TData, TError, TVars, TContext> {
@@ -1,12 +1,6 @@
1
1
  import { SodaxContext, type SodaxContextType } from '@/contexts/index.js';
2
2
  import { useContext } from 'react';
3
3
 
4
- /**
5
- * Hook to access the Sodax context which provides access to the Sodax SDK instance and chain configuration
6
- * @throws {Error} If used outside of a SodaxProvider
7
- * @returns {SodaxContextType} The Sodax context containing SDK instance and configuration
8
- */
9
-
10
4
  export const useSodaxContext = (): SodaxContextType => {
11
5
  const context = useContext(SodaxContext);
12
6
  if (!context) {
@@ -5,8 +5,7 @@ const statusCheck = vi.fn();
5
5
  const trustlineCheck = vi.fn();
6
6
  const requiresTrustline = vi.fn(() => true);
7
7
 
8
- // Stubbing the child hooks keeps this a DOM-free assertion on the params the gate builds —
9
- // the resolver itself is covered by utils/stellarGate.test.ts.
8
+ // Stubbing the child hooks keeps this a DOM-free assertion on the params the gate builds.
10
9
  vi.mock('../sponsoring/useStellarAccountStatus.js', () => ({
11
10
  useStellarAccountStatus: (args: unknown) => statusCheck(args),
12
11
  }));
@@ -30,10 +29,7 @@ const ADDRESS = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
30
29
 
31
30
  const idle = { isLoading: false, isError: false, data: undefined, error: null, refetch: vi.fn() };
32
31
 
33
- /**
34
- * Drive the gate with a given account-status result. An absent `walletAddress` is what
35
- * leaves `useStellarTrustlineCheck` disabled, so it stands in for "no Horizon read".
36
- */
32
+ // An absent `walletAddress` leaves `useStellarTrustlineCheck` disabled: it stands in for "no Horizon read".
37
33
  const run = (status: unknown, overrides: Record<string, unknown> = {}) => {
38
34
  statusCheck.mockReturnValue({ ...idle, ...(status as object) });
39
35
  trustlineCheck.mockReturnValue(idle);
@@ -58,15 +54,12 @@ beforeEach(() => {
58
54
 
59
55
  describe('useStellarGate — the trustline read is gated on account existence', () => {
60
56
  it('does NOT read the trustline for an account that does not exist', () => {
61
- // hasSufficientTrustline 404s on a missing account, and React Query would retry it.
62
57
  const { gate, trustlineAddress } = run({ data: { exists: false, canAffordTrustline: false } });
63
58
 
64
59
  expect(trustlineAddress).toBeUndefined();
65
- // The gate still reaches the right conclusion without the trustline read.
66
60
  expect(gate.needsActivation).toBe(true);
67
61
  expect(gate.blocksAction).toBe(true);
68
62
  expect(gate.checkFailed).toBe(false);
69
- // No spurious error while the UI is showing "activate".
70
63
  expect(gate.error).toBeUndefined();
71
64
  });
72
65
 
@@ -33,10 +33,7 @@ export interface StellarGate extends StellarGateState {
33
33
  requestTrustline: () => Promise<Result<string> | undefined>;
34
34
  }
35
35
 
36
- /**
37
- * Gate Stellar delivery on account activation, trustline availability, and
38
- * enough spendable XLM to create a missing trustline.
39
- */
36
+ /** Gates Stellar delivery on account activation, trustline, and enough spendable XLM to create one. */
40
37
  export function useStellarGate({
41
38
  dstChainKey,
42
39
  token,
@@ -51,11 +48,8 @@ export function useStellarGate({
51
48
  const gatedAddress = isStellarDestination ? address : undefined;
52
49
 
53
50
  const statusCheck = useStellarAccountStatus({ params: { address: gatedAddress } });
54
- // Withhold the address until the account is known to exist, which leaves the trustline query
55
- // disabled: `hasSufficientTrustline` 404s on a missing account, and React Query would retry it
56
- // and surface the failure on `error` while the gate is correctly reporting `needsActivation`.
57
- // `resolveStellarGate` decides activation from `statusCheck` alone and reads the unresolved
58
- // trustline query as blocking, so this never changes the gate's outcome.
51
+ // `hasSufficientTrustline` 404s on a missing account, so keep the trustline query disabled until
52
+ // the account exists; otherwise its retries surface on `error` while the gate says `needsActivation`.
59
53
  const trustlineAddress = statusCheck.data?.exists === true ? gatedAddress : undefined;
60
54
  const trustlineCheck = useStellarTrustlineCheck({
61
55
  params: { token, amount, chainId: dstChainKey, walletAddress: trustlineAddress },
@@ -44,8 +44,6 @@ describe('getStellarTrustlineCheckQueryOptions — query key', () => {
44
44
  });
45
45
 
46
46
  it('shares the useEstablishTrustline invalidation prefix (chain, token, account) across every amount', () => {
47
- // useEstablishTrustline invalidates ['shared','stellarTrustlineCheck', srcChainKey, token, srcAddress];
48
- // amount sits after that prefix, so the invalidation covers the account's checks at any amount.
49
47
  const invalidationKey = ['shared', 'stellarTrustlineCheck', STELLAR, TOKEN, WALLET_A];
50
48
  for (const amount of [100n, 10_000n]) {
51
49
  expect(optionsFor({ amount }).queryKey.slice(0, invalidationKey.length)).toEqual(invalidationKey);
@@ -9,15 +9,13 @@ export type UseStellarTrustlineCheckParams = ReadHookParams<
9
9
  token: string | undefined;
10
10
  amount: bigint | undefined;
11
11
  chainId: SpokeChainKey | undefined;
12
- /** Resolved Stellar account address (e.g. `useXAccount('STELLAR').address`) — keys the cache per account. */
13
12
  walletAddress: string | undefined;
14
13
  }
15
14
  >;
16
15
 
17
- // Narrow slice of the SDK this query reads — lets tests pass a minimal stub without casting `Sodax`.
16
+ // Narrow slice so tests can pass a minimal stub without casting `Sodax`.
18
17
  type StellarTrustlineReader = { spoke: { stellar: Pick<Sodax['spoke']['stellar'], 'hasSufficientTrustline'> } };
19
18
 
20
- // Pure query options, extracted for unit testing (mirrors `getXBalancesQueryOptions`).
21
19
  export function getStellarTrustlineCheckQueryOptions({
22
20
  sodax,
23
21
  token,
@@ -32,7 +30,6 @@ export function getStellarTrustlineCheckQueryOptions({
32
30
  walletAddress: string | undefined;
33
31
  }) {
34
32
  return {
35
- // Key on chain, token, account, amount so editing the amount (or switching account/chain) re-queries.
36
33
  queryKey: ['shared', 'stellarTrustlineCheck', chainId, token, walletAddress, amount?.toString()] as const,
37
34
  queryFn: async (): Promise<boolean> => {
38
35
  if (chainId !== ChainKeys.STELLAR_MAINNET) return true;
@@ -2,10 +2,6 @@ import { type UseQueryResult, useQuery } from '@tanstack/react-query';
2
2
  import type { SpokeChainKey, IXServiceBase, XToken } from '@sodax/sdk';
3
3
  import type { ReadHookParams } from './types.js';
4
4
 
5
- /**
6
- * Domain inputs for {@link useXBalances}. `xChainId` is optional so the hook can be mounted
7
- * before a chain is selected; `enabled` gates execution on every required field being present.
8
- */
9
5
  export interface XBalancesInputs {
10
6
  xService: IXServiceBase | undefined;
11
7
  xChainId: SpokeChainKey | undefined;
@@ -17,14 +13,9 @@ export type UseXBalancesParams = ReadHookParams<Record<string, bigint>, XBalance
17
13
 
18
14
  const REFETCH_INTERVAL_MS = 5_000;
19
15
 
20
- /**
21
- * Pure builder for {@link useXBalances} query options. Exported for unit
22
- * tests and for advanced callers that compose their own `useQuery` wrapper.
23
- */
24
16
  export function getXBalancesQueryOptions({ xService, xChainId, xTokens, address }: XBalancesInputs) {
25
17
  return {
26
- // Pair symbol + address: readable in devtools, unique on-chain (symbol alone
27
- // can collide — e.g. scam tokens copying legitimate ticker).
18
+ // Symbol alone can collide (scam tokens copy tickers), so pair it with the address.
28
19
  queryKey: ['shared', 'xBalances', xChainId, xTokens.map(x => [x.symbol, x.address] as const), address] as const,
29
20
  queryFn: async (): Promise<Record<string, bigint>> => {
30
21
  if (!xService) return {};
@@ -35,16 +26,7 @@ export function getXBalancesQueryOptions({ xService, xChainId, xTokens, address
35
26
  };
36
27
  }
37
28
 
38
- /**
39
- * Fetch token balances for multiple tokens on a specific chain. Returns an
40
- * object mapping each token's address to its balance in smallest unit.
41
- *
42
- * @example
43
- * ```tsx
44
- * const xService = useXService({ xChainType: getXChainType(xChainId) });
45
- * const { data: balances } = useXBalances({ params: { xService, xChainId, xTokens, address } });
46
- * ```
47
- */
29
+ /** Balances keyed by token address, in smallest units. */
48
30
  export function useXBalances({
49
31
  params,
50
32
  queryOptions,