@sodax/dapp-kit 2.2.0-rc.6 → 2.2.0-rc.7

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 (34) hide show
  1. package/README.md +20 -3
  2. package/dist/index.d.ts +107 -13
  3. package/dist/index.mjs +118 -38
  4. package/package.json +4 -4
  5. package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.test.ts +144 -0
  6. package/src/hooks/bridge/getBridgeDetailedStatusRefetchInterval.ts +52 -0
  7. package/src/hooks/bridge/index.ts +2 -0
  8. package/src/hooks/bridge/useBridgeDetailedStatus.test.ts +93 -0
  9. package/src/hooks/bridge/useBridgeDetailedStatus.ts +79 -0
  10. package/src/hooks/bridgeApi/getBridgeSubmitTxStatusRefetchInterval.test.ts +81 -0
  11. package/src/hooks/bridgeApi/getBridgeSubmitTxStatusRefetchInterval.ts +25 -0
  12. package/src/hooks/bridgeApi/useBridgeApiAllowance.ts +2 -1
  13. package/src/hooks/bridgeApi/useBridgeApiApprove.ts +2 -1
  14. package/src/hooks/bridgeApi/useBridgeApiBridgeableAmount.ts +2 -1
  15. package/src/hooks/bridgeApi/useBridgeApiCreateBridgeIntent.ts +2 -1
  16. package/src/hooks/bridgeApi/useBridgeApiFee.ts +2 -1
  17. package/src/hooks/bridgeApi/useBridgeApiIsBridgeable.ts +2 -1
  18. package/src/hooks/bridgeApi/useBridgeApiSubmitTx.ts +5 -3
  19. package/src/hooks/bridgeApi/useBridgeApiSubmitTxStatus.test.ts +63 -0
  20. package/src/hooks/bridgeApi/useBridgeApiSubmitTxStatus.ts +7 -10
  21. package/src/hooks/bridgeApi/useBridgeApiTokens.ts +2 -1
  22. package/src/hooks/bridgeApi/useBridgeApiTokensByChain.ts +2 -1
  23. package/src/hooks/leverageYield/index.ts +1 -0
  24. package/src/hooks/leverageYield/useLeverageYieldDetailedStatus.test.ts +131 -0
  25. package/src/hooks/leverageYield/useLeverageYieldDetailedStatus.ts +83 -0
  26. package/src/hooks/leverageYield/useLeverageYieldVaultSwap.ts +13 -3
  27. package/src/hooks/shared/notFoundStreak.ts +59 -0
  28. package/src/hooks/shared/retryUnlessAuthFailure.ts +1 -1
  29. package/src/hooks/{swap/getSwapStatusRefetchInterval.test.ts → shared/solverStatusPolicy.test.ts} +25 -25
  30. package/src/hooks/shared/solverStatusPolicy.ts +117 -0
  31. package/src/hooks/swap/useDetailedStatus.test.ts +65 -21
  32. package/src/hooks/swap/useDetailedStatus.ts +9 -9
  33. package/src/hooks/swap/useStatus.ts +4 -7
  34. package/src/hooks/swap/getSwapStatusRefetchInterval.ts +0 -126
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { isSodaxError, isAuthFailure, ChainKeys, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, RadfiApiError, normalizePsbtToBase64, ClService, SPONSOR_CONFIG_TTL_MS, Sodax, SolverIntentStatusCode, DETAILED_STATUS_NOT_DELIVERED, isApprovalSupportedChainKeyType, isHubChainKeyType, isEvmSpokeOnlyChainKeyType, getEvmViemChain, isStellarChainKeyType } from '@sodax/sdk';
1
+ import { isSodaxError, isAuthFailure, ChainKeys, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, RadfiApiError, normalizePsbtToBase64, DETAILED_STATUS_NOT_DELIVERED, ClService, SPONSOR_CONFIG_TTL_MS, Sodax, SolverIntentStatusCode, isApprovalSupportedChainKeyType, isHubChainKeyType, isEvmSpokeOnlyChainKeyType, getEvmViemChain, isStellarChainKeyType } from '@sodax/sdk';
2
2
  export * from '@sodax/sdk';
3
3
  import { useMutation, useQuery, useQueryClient, useQueries, QueryClient, MutationCache } from '@tanstack/react-query';
4
4
  import { createContext, useCallback, useContext, useRef, useState, useEffect, useMemo } from 'react';
@@ -1149,6 +1149,8 @@ function useSwap({
1149
1149
  }
1150
1150
  });
1151
1151
  }
1152
+
1153
+ // src/hooks/shared/notFoundStreak.ts
1152
1154
  var STATUS_POLL_MS = 3e3;
1153
1155
  var MAX_NOT_FOUND_POLLS = 40;
1154
1156
  var INITIAL_NOT_FOUND_STREAK = {
@@ -1156,21 +1158,10 @@ var INITIAL_NOT_FOUND_STREAK = {
1156
1158
  seenUpdates: 0,
1157
1159
  consecutiveNotFound: 0
1158
1160
  };
1159
- function getSwapStatusRefetchInterval(data, consecutiveNotFound) {
1160
- const status = data?.ok ? data.value.status : void 0;
1161
- if (status === SolverIntentStatusCode.SOLVED || status === SolverIntentStatusCode.FAILED) {
1162
- return false;
1163
- }
1164
- if (status === SolverIntentStatusCode.NOT_FOUND && consecutiveNotFound >= MAX_NOT_FOUND_POLLS) {
1165
- return false;
1166
- }
1167
- return STATUS_POLL_MS;
1168
- }
1169
- function nextNotFoundStreak(data, previousStreak) {
1170
- const status = data?.ok ? data.value.status : void 0;
1171
- return status === SolverIntentStatusCode.NOT_FOUND ? previousStreak + 1 : 0;
1161
+ function nextNotFoundStreak(isAmbiguousMiss, previousStreak) {
1162
+ return isAmbiguousMiss ? previousStreak + 1 : 0;
1172
1163
  }
1173
- function advanceNotFoundStreak(state, pollKey, data, dataUpdateCount) {
1164
+ function advanceNotFoundStreak(state, pollKey, isAmbiguousMiss, dataUpdateCount) {
1174
1165
  if (state.pollKey !== pollKey) {
1175
1166
  state = { pollKey, seenUpdates: 0, consecutiveNotFound: 0 };
1176
1167
  }
@@ -1180,9 +1171,22 @@ function advanceNotFoundStreak(state, pollKey, data, dataUpdateCount) {
1180
1171
  return {
1181
1172
  pollKey,
1182
1173
  seenUpdates: dataUpdateCount,
1183
- consecutiveNotFound: nextNotFoundStreak(data, state.consecutiveNotFound)
1174
+ consecutiveNotFound: nextNotFoundStreak(isAmbiguousMiss, state.consecutiveNotFound)
1184
1175
  };
1185
1176
  }
1177
+ function getSolverStatusRefetchInterval(data, consecutiveNotFound) {
1178
+ const status = data?.ok ? data.value.status : void 0;
1179
+ if (status === SolverIntentStatusCode.SOLVED || status === SolverIntentStatusCode.FAILED) {
1180
+ return false;
1181
+ }
1182
+ if (status === SolverIntentStatusCode.NOT_FOUND && consecutiveNotFound >= MAX_NOT_FOUND_POLLS) {
1183
+ return false;
1184
+ }
1185
+ return STATUS_POLL_MS;
1186
+ }
1187
+ function isSolverNotFound(data) {
1188
+ return (data?.ok ? data.value.status : void 0) === SolverIntentStatusCode.NOT_FOUND;
1189
+ }
1186
1190
  function toNotFoundBudgetRead(data) {
1187
1191
  if (data === void 0) return void 0;
1188
1192
  if (data.ok) {
@@ -1190,12 +1194,13 @@ function toNotFoundBudgetRead(data) {
1190
1194
  }
1191
1195
  return data.error?.context?.reason === DETAILED_STATUS_NOT_DELIVERED ? { ok: true, value: { status: SolverIntentStatusCode.NOT_FOUND } } : void 0;
1192
1196
  }
1193
- function getDetailedStatusRefetchInterval(data, consecutiveNotFound) {
1197
+ function getSolverDetailedStatusRefetchInterval(data, consecutiveNotFound) {
1198
+ if (data && !data.ok && isAuthFailure(data.error)) return false;
1194
1199
  if (data?.ok && data.value.source === "backend") {
1195
1200
  const { status } = data.value.data;
1196
1201
  return status === "solved" || status === "failed" ? false : STATUS_POLL_MS;
1197
1202
  }
1198
- return getSwapStatusRefetchInterval(toNotFoundBudgetRead(data), consecutiveNotFound);
1203
+ return getSolverStatusRefetchInterval(toNotFoundBudgetRead(data), consecutiveNotFound);
1199
1204
  }
1200
1205
 
1201
1206
  // src/hooks/swap/useStatus.ts
@@ -1217,10 +1222,10 @@ var useStatus = ({
1217
1222
  notFoundStreakRef.current = advanceNotFoundStreak(
1218
1223
  notFoundStreakRef.current,
1219
1224
  intentTxHash,
1220
- query.state.data,
1225
+ isSolverNotFound(query.state.data),
1221
1226
  query.state.dataUpdateCount
1222
1227
  );
1223
- return getSwapStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
1228
+ return getSolverStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
1224
1229
  },
1225
1230
  ...queryOptions
1226
1231
  });
@@ -1245,10 +1250,10 @@ var useDetailedStatus = ({
1245
1250
  notFoundStreakRef.current = advanceNotFoundStreak(
1246
1251
  notFoundStreakRef.current,
1247
1252
  pollKey,
1248
- toNotFoundBudgetRead(query.state.data),
1253
+ isSolverNotFound(toNotFoundBudgetRead(query.state.data)),
1249
1254
  query.state.dataUpdateCount
1250
1255
  );
1251
- return getDetailedStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
1256
+ return getSolverDetailedStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
1252
1257
  },
1253
1258
  ...queryOptions
1254
1259
  });
@@ -2037,6 +2042,19 @@ var useSwapsApiSubmitTxStatus = ({
2037
2042
  ...queryOptions
2038
2043
  });
2039
2044
  };
2045
+ function isBridgeNotDelivered(data) {
2046
+ return data !== void 0 && !data.ok && data.error?.context?.reason === DETAILED_STATUS_NOT_DELIVERED;
2047
+ }
2048
+ function getBridgeDetailedStatusRefetchInterval(data, consecutiveNotFound) {
2049
+ if (data?.ok) {
2050
+ if (data.value.source === "relay") return false;
2051
+ const { status, abandonedAt } = data.value.data;
2052
+ return status === "executed" || status === "failed" || abandonedAt ? false : STATUS_POLL_MS;
2053
+ }
2054
+ if (data && !data.ok && isAuthFailure(data.error)) return false;
2055
+ if (isBridgeNotDelivered(data) && consecutiveNotFound >= MAX_NOT_FOUND_POLLS) return false;
2056
+ return STATUS_POLL_MS;
2057
+ }
2040
2058
  function useBridge({
2041
2059
  mutationOptions
2042
2060
  } = {}) {
@@ -2052,6 +2070,35 @@ function useBridge({
2052
2070
  }
2053
2071
  });
2054
2072
  }
2073
+ var useBridgeDetailedStatus = ({
2074
+ params,
2075
+ queryOptions
2076
+ } = {}) => {
2077
+ const { sodax } = useSodaxContext();
2078
+ const srcChainKey = params?.srcChainKey;
2079
+ const srcTxHash = params?.srcTxHash;
2080
+ const apiConfig = params?.apiConfig;
2081
+ const pollKey = srcChainKey && srcTxHash ? `${srcChainKey}:${srcTxHash}` : void 0;
2082
+ const notFoundStreakRef = useRef({ ...INITIAL_NOT_FOUND_STREAK });
2083
+ return useQuery({
2084
+ queryKey: ["bridge", "detailedStatus", srcChainKey, srcTxHash],
2085
+ queryFn: async () => {
2086
+ if (!srcChainKey || !srcTxHash) return void 0;
2087
+ return sodax.bridge.getDetailedStatus({ srcChainKey, srcTxHash }, apiConfig);
2088
+ },
2089
+ enabled: !!srcChainKey && !!srcTxHash,
2090
+ refetchInterval: (query) => {
2091
+ notFoundStreakRef.current = advanceNotFoundStreak(
2092
+ notFoundStreakRef.current,
2093
+ pollKey,
2094
+ isBridgeNotDelivered(query.state.data),
2095
+ query.state.dataUpdateCount
2096
+ );
2097
+ return getBridgeDetailedStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
2098
+ },
2099
+ ...queryOptions
2100
+ });
2101
+ };
2055
2102
  function useBridgeAllowance({
2056
2103
  params,
2057
2104
  queryOptions
@@ -2163,7 +2210,7 @@ var useBridgeApiAllowance = ({
2163
2210
  return unwrapResult(await sodax.api.bridge.checkAllowance(body, apiConfig));
2164
2211
  },
2165
2212
  enabled: !!body,
2166
- retry: 3,
2213
+ retry: retryUnlessAuthFailure,
2167
2214
  ...queryOptions
2168
2215
  });
2169
2216
  };
@@ -2175,7 +2222,7 @@ var useBridgeApiApprove = ({
2175
2222
  const { sodax } = useSodaxContext();
2176
2223
  return useSafeMutation({
2177
2224
  mutationKey: ["bridgeApi", "approve"],
2178
- retry: 3,
2225
+ retry: retryUnlessAuthFailure,
2179
2226
  ...mutationOptions,
2180
2227
  mutationFn: async ({ body, apiConfig }) => unwrapResult(await sodax.api.bridge.approve(body, apiConfig))
2181
2228
  });
@@ -2218,7 +2265,7 @@ var useBridgeApiBridgeableAmount = ({
2218
2265
  return unwrapResult(await sodax.api.bridge.getBridgeableAmount(body, apiConfig));
2219
2266
  },
2220
2267
  enabled: !!body,
2221
- retry: 3,
2268
+ retry: retryUnlessAuthFailure,
2222
2269
  ...queryOptions
2223
2270
  });
2224
2271
  };
@@ -2230,7 +2277,7 @@ var useBridgeApiCreateBridgeIntent = ({
2230
2277
  const { sodax } = useSodaxContext();
2231
2278
  return useSafeMutation({
2232
2279
  mutationKey: ["bridgeApi", "createBridgeIntent"],
2233
- retry: 3,
2280
+ retry: retryUnlessAuthFailure,
2234
2281
  ...mutationOptions,
2235
2282
  mutationFn: async ({ body, apiConfig }) => unwrapResult(await sodax.api.bridge.createBridgeIntent(body, apiConfig))
2236
2283
  });
@@ -2249,7 +2296,7 @@ var useBridgeApiFee = ({
2249
2296
  return unwrapResult(await sodax.api.bridge.getFee(body, apiConfig));
2250
2297
  },
2251
2298
  enabled: !!body,
2252
- retry: 3,
2299
+ retry: retryUnlessAuthFailure,
2253
2300
  ...queryOptions
2254
2301
  });
2255
2302
  };
@@ -2267,7 +2314,7 @@ var useBridgeApiIsBridgeable = ({
2267
2314
  return unwrapResult(await sodax.api.bridge.isBridgeable(body, apiConfig));
2268
2315
  },
2269
2316
  enabled: !!body,
2270
- retry: 3,
2317
+ retry: retryUnlessAuthFailure,
2271
2318
  ...queryOptions
2272
2319
  });
2273
2320
  };
@@ -2279,11 +2326,19 @@ var useBridgeApiSubmitTx = ({
2279
2326
  const { sodax } = useSodaxContext();
2280
2327
  return useSafeMutation({
2281
2328
  mutationKey: ["bridgeApi", "submitTx"],
2282
- retry: 3,
2329
+ retry: retryUnlessAuthFailure,
2283
2330
  ...mutationOptions,
2284
2331
  mutationFn: async ({ request, apiConfig }) => unwrapResult(await sodax.api.bridge.submitTx(request, apiConfig))
2285
2332
  });
2286
2333
  };
2334
+ var BRIDGE_SUBMIT_TX_STATUS_POLL_MS = 1e3;
2335
+ function getBridgeSubmitTxStatusRefetchInterval(error, data) {
2336
+ if (isAuthFailure(error)) return false;
2337
+ if (data?.status === "executed" || data?.status === "failed" || data?.abandonedAt) return false;
2338
+ return BRIDGE_SUBMIT_TX_STATUS_POLL_MS;
2339
+ }
2340
+
2341
+ // src/hooks/bridgeApi/useBridgeApiSubmitTxStatus.ts
2287
2342
  var useBridgeApiSubmitTxStatus = ({
2288
2343
  params,
2289
2344
  queryOptions
@@ -2299,12 +2354,8 @@ var useBridgeApiSubmitTxStatus = ({
2299
2354
  return unwrapResult(await sodax.api.bridge.getSubmitTxStatus({ txHash, srcChainKey }, apiConfig));
2300
2355
  },
2301
2356
  enabled: !!txHash && txHash.length > 0 && !!srcChainKey,
2302
- retry: 3,
2303
- refetchInterval: (query) => {
2304
- const data = query.state.data?.data;
2305
- if (data?.status === "executed" || data?.status === "failed" || data?.abandonedAt) return false;
2306
- return 1e3;
2307
- },
2357
+ retry: retryUnlessAuthFailure,
2358
+ refetchInterval: (query) => getBridgeSubmitTxStatusRefetchInterval(query.state.error, query.state.data?.data),
2308
2359
  ...queryOptions
2309
2360
  });
2310
2361
  };
@@ -2317,7 +2368,7 @@ var useBridgeApiTokens = ({
2317
2368
  return useQuery({
2318
2369
  queryKey: ["bridgeApi", "tokens"],
2319
2370
  queryFn: async () => unwrapResult(await sodax.api.bridge.getTokens(apiConfig)),
2320
- retry: 3,
2371
+ retry: retryUnlessAuthFailure,
2321
2372
  ...queryOptions
2322
2373
  });
2323
2374
  };
@@ -2335,7 +2386,7 @@ var useBridgeApiTokensByChain = ({
2335
2386
  return unwrapResult(await sodax.api.bridge.getTokensByChain(chainKey, apiConfig));
2336
2387
  },
2337
2388
  enabled: !!chainKey && chainKey.length > 0,
2338
- retry: 3,
2389
+ retry: retryUnlessAuthFailure,
2339
2390
  ...queryOptions
2340
2391
  });
2341
2392
  };
@@ -3829,6 +3880,35 @@ function useLeverageYieldNotifySolver({
3829
3880
  mutationFn: async (vars) => unwrapResult(await sodax.leverageYield.notifySolver(vars))
3830
3881
  });
3831
3882
  }
3883
+ var useLeverageYieldDetailedStatus = ({
3884
+ params,
3885
+ queryOptions
3886
+ } = {}) => {
3887
+ const { sodax } = useSodaxContext();
3888
+ const srcChainKey = params?.srcChainKey;
3889
+ const srcTxHash = params?.srcTxHash;
3890
+ const apiConfig = params?.apiConfig;
3891
+ const pollKey = srcChainKey && srcTxHash ? `${srcChainKey}:${srcTxHash}` : void 0;
3892
+ const notFoundStreakRef = useRef({ ...INITIAL_NOT_FOUND_STREAK });
3893
+ return useQuery({
3894
+ queryKey: ["leverageYield", "detailedStatus", srcChainKey, srcTxHash],
3895
+ queryFn: async () => {
3896
+ if (!srcChainKey || !srcTxHash) return void 0;
3897
+ return sodax.leverageYield.getDetailedStatus({ srcChainKey, srcTxHash }, apiConfig);
3898
+ },
3899
+ enabled: !!srcChainKey && !!srcTxHash,
3900
+ refetchInterval: (query) => {
3901
+ notFoundStreakRef.current = advanceNotFoundStreak(
3902
+ notFoundStreakRef.current,
3903
+ pollKey,
3904
+ isSolverNotFound(toNotFoundBudgetRead(query.state.data)),
3905
+ query.state.dataUpdateCount
3906
+ );
3907
+ return getSolverDetailedStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
3908
+ },
3909
+ ...queryOptions
3910
+ });
3911
+ };
3832
3912
  function useLeverageYieldVaultSwap({
3833
3913
  mutationOptions
3834
3914
  } = {}) {
@@ -4745,4 +4825,4 @@ function createSodaxQueryClient({
4745
4825
  });
4746
4826
  }
4747
4827
 
4748
- export { SodaxProvider, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getBalancesQueryOptions, getLeverageYieldQuoteQueryOptions, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, getSwapQuoteQueryOptions, getXBalancesQueryOptions, invalidateBalances, isTerminalSwapIntentStatus, isUserRejectedError, loadRadfiSession, resolveNearStorageGate, resolveStellarGate, retryUnlessAuthFailure, runApprovalPlan, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useActivateStellarAccount, useApproveLeveragePositionFunding, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOracleCandles, useBackendOracleMarkets, useBackendOrderbook, useBackendUserIntents, useBalances, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApiAllowance, useBridgeApiApprove, useBridgeApiApproveAndBroadcast, useBridgeApiBridgeableAmount, useBridgeApiCreateBridgeIntent, useBridgeApiFee, useBridgeApiIsBridgeable, useBridgeApiSubmitTx, useBridgeApiSubmitTxStatus, useBridgeApiTokens, useBridgeApiTokensByChain, useBridgeApprove, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDetailedStatus, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, useEModes, useEnsureRadfiAccessToken, useEstablishTrustline, useEstimateGas, useExpiredUtxos, useFeeClaimSwap, useFeeClaimWithdraw, useFetchAssetsBalances, useFundTradingWallet, useGetAutoSwapPreferences, useGetBridgeableAmount, useGetBridgeableTokens, useGetIntentDetails, useGetUserHubWalletAddress, useGetUserIntent, useHubAssetBalances, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useIsTokenApproved, useLeveragePositionAccount, useLeveragePositionCollateral, useLeveragePositionFundingAllowance, useLeveragePositionInfo, useLeveragePositionPayoutAddress, useLeveragePositionPending, useLeveragePositions, useLeveragePositionsForUser, useLeverageYieldApiAllowance, useLeverageYieldApiApprove, useLeverageYieldApiApproveAndBroadcast, useLeverageYieldApiApr, useLeverageYieldApiAsset, useLeverageYieldApiCancelIntent, useLeverageYieldApiCreateDepositIntent, useLeverageYieldApiCreateWithdrawIntent, useLeverageYieldApiDeadline, useLeverageYieldApiDepositQuote, useLeverageYieldApiEffectiveApr, useLeverageYieldApiEstimateGas, useLeverageYieldApiFilledIntent, useLeverageYieldApiIntent, useLeverageYieldApiIntentExtraData, useLeverageYieldApiIntentHash, useLeverageYieldApiIntentPacket, useLeverageYieldApiLsdApr, useLeverageYieldApiMaxWithdraw, useLeverageYieldApiPartnerFee, useLeverageYieldApiPosition, useLeverageYieldApiPreviewDeposit, useLeverageYieldApiPreviewRedeem, useLeverageYieldApiPreviewWithdraw, useLeverageYieldApiShareBalance, useLeverageYieldApiSolverFee, useLeverageYieldApiStatus, useLeverageYieldApiSubmitIntent, useLeverageYieldApiSubmitTx, useLeverageYieldApiSubmitTxStatus, useLeverageYieldApiTotalAssets, useLeverageYieldApiVault, useLeverageYieldApiVaults, useLeverageYieldApiWithdrawQuote, useLeverageYieldDeposit, useLeverageYieldEffectiveApr, useLeverageYieldNotifySolver, useLeverageYieldPosition, useLeverageYieldPreviewRedeem, useLeverageYieldQuote, useLeverageYieldShareBalances, useLeverageYieldTotalAssets, useLeverageYieldVaultSwap, useLeverageYieldWithdraw, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrateBaln, useMigrateIcxToSoda, useMigratebnUSD, useMigrationAllowance, useMigrationApprove, useNearStorageCheck, useNearStorageGate, useOpenLeveragePosition, usePartnerCancelIntent, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRegisterNearStorage, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesHumanized, useReservesList, useReservesUsdFormat, useRevertMigrateSodaToIcx, useRunLeveragePositionOperation, useSafeMutation, useSetSwapPreference, useSodaxContext, useSponsorConfig, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarAccountActive, useStellarAccountStatus, useStellarGate, useStellarTrustlineCheck, useSubmitLeveragePositionIntent, useSupply, useSupplyLiquidity, useSwap, useSwapAllowance, useSwapApprove, useSwapsApiAllowance, useSwapsApiApprove, useSwapsApiApproveAndBroadcast, useSwapsApiCancelIntent, useSwapsApiCreateIntent, useSwapsApiCreateLimitOrder, useSwapsApiDeadline, useSwapsApiEstimateGas, useSwapsApiFilledIntent, useSwapsApiIntent, useSwapsApiIntentExtraData, useSwapsApiIntentHash, useSwapsApiIntentPacket, useSwapsApiPartnerFee, useSwapsApiQuote, useSwapsApiSolverFee, useSwapsApiStatus, useSwapsApiSubmitIntent, useSwapsApiSubmitTx, useSwapsApiSubmitTxStatus, useSwapsApiTokens, useSwapsApiTokensByChain, useTradingWallet, useTradingWalletBalance, useUnstake, useUnstakeAllowance, useUnstakeApprove, useUnstakingInfo, useUnstakingInfoWithPenalty, useUserFormattedSummary, useUserReservesData, useWithdraw, useWithdrawHubAsset, useXBalances };
4828
+ export { SodaxProvider, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getBalancesQueryOptions, getBridgeDetailedStatusRefetchInterval, getLeverageYieldQuoteQueryOptions, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, getSwapQuoteQueryOptions, getXBalancesQueryOptions, invalidateBalances, isBridgeNotDelivered, isTerminalSwapIntentStatus, isUserRejectedError, loadRadfiSession, resolveNearStorageGate, resolveStellarGate, retryUnlessAuthFailure, runApprovalPlan, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useActivateStellarAccount, useApproveLeveragePositionFunding, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOracleCandles, useBackendOracleMarkets, useBackendOrderbook, useBackendUserIntents, useBalances, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApiAllowance, useBridgeApiApprove, useBridgeApiApproveAndBroadcast, useBridgeApiBridgeableAmount, useBridgeApiCreateBridgeIntent, useBridgeApiFee, useBridgeApiIsBridgeable, useBridgeApiSubmitTx, useBridgeApiSubmitTxStatus, useBridgeApiTokens, useBridgeApiTokensByChain, useBridgeApprove, useBridgeDetailedStatus, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDetailedStatus, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, useEModes, useEnsureRadfiAccessToken, useEstablishTrustline, useEstimateGas, useExpiredUtxos, useFeeClaimSwap, useFeeClaimWithdraw, useFetchAssetsBalances, useFundTradingWallet, useGetAutoSwapPreferences, useGetBridgeableAmount, useGetBridgeableTokens, useGetIntentDetails, useGetUserHubWalletAddress, useGetUserIntent, useHubAssetBalances, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useIsTokenApproved, useLeveragePositionAccount, useLeveragePositionCollateral, useLeveragePositionFundingAllowance, useLeveragePositionInfo, useLeveragePositionPayoutAddress, useLeveragePositionPending, useLeveragePositions, useLeveragePositionsForUser, useLeverageYieldApiAllowance, useLeverageYieldApiApprove, useLeverageYieldApiApproveAndBroadcast, useLeverageYieldApiApr, useLeverageYieldApiAsset, useLeverageYieldApiCancelIntent, useLeverageYieldApiCreateDepositIntent, useLeverageYieldApiCreateWithdrawIntent, useLeverageYieldApiDeadline, useLeverageYieldApiDepositQuote, useLeverageYieldApiEffectiveApr, useLeverageYieldApiEstimateGas, useLeverageYieldApiFilledIntent, useLeverageYieldApiIntent, useLeverageYieldApiIntentExtraData, useLeverageYieldApiIntentHash, useLeverageYieldApiIntentPacket, useLeverageYieldApiLsdApr, useLeverageYieldApiMaxWithdraw, useLeverageYieldApiPartnerFee, useLeverageYieldApiPosition, useLeverageYieldApiPreviewDeposit, useLeverageYieldApiPreviewRedeem, useLeverageYieldApiPreviewWithdraw, useLeverageYieldApiShareBalance, useLeverageYieldApiSolverFee, useLeverageYieldApiStatus, useLeverageYieldApiSubmitIntent, useLeverageYieldApiSubmitTx, useLeverageYieldApiSubmitTxStatus, useLeverageYieldApiTotalAssets, useLeverageYieldApiVault, useLeverageYieldApiVaults, useLeverageYieldApiWithdrawQuote, useLeverageYieldDeposit, useLeverageYieldDetailedStatus, useLeverageYieldEffectiveApr, useLeverageYieldNotifySolver, useLeverageYieldPosition, useLeverageYieldPreviewRedeem, useLeverageYieldQuote, useLeverageYieldShareBalances, useLeverageYieldTotalAssets, useLeverageYieldVaultSwap, useLeverageYieldWithdraw, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrateBaln, useMigrateIcxToSoda, useMigratebnUSD, useMigrationAllowance, useMigrationApprove, useNearStorageCheck, useNearStorageGate, useOpenLeveragePosition, usePartnerCancelIntent, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRegisterNearStorage, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesHumanized, useReservesList, useReservesUsdFormat, useRevertMigrateSodaToIcx, useRunLeveragePositionOperation, useSafeMutation, useSetSwapPreference, useSodaxContext, useSponsorConfig, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarAccountActive, useStellarAccountStatus, useStellarGate, useStellarTrustlineCheck, useSubmitLeveragePositionIntent, useSupply, useSupplyLiquidity, useSwap, useSwapAllowance, useSwapApprove, useSwapsApiAllowance, useSwapsApiApprove, useSwapsApiApproveAndBroadcast, useSwapsApiCancelIntent, useSwapsApiCreateIntent, useSwapsApiCreateLimitOrder, useSwapsApiDeadline, useSwapsApiEstimateGas, useSwapsApiFilledIntent, useSwapsApiIntent, useSwapsApiIntentExtraData, useSwapsApiIntentHash, useSwapsApiIntentPacket, useSwapsApiPartnerFee, useSwapsApiQuote, useSwapsApiSolverFee, useSwapsApiStatus, useSwapsApiSubmitIntent, useSwapsApiSubmitTx, useSwapsApiSubmitTxStatus, useSwapsApiTokens, useSwapsApiTokensByChain, useTradingWallet, useTradingWalletBalance, useUnstake, useUnstakeAllowance, useUnstakeApprove, useUnstakingInfo, useUnstakingInfoWithPenalty, useUserFormattedSummary, useUserReservesData, useWithdraw, useWithdrawHubAsset, useXBalances };
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "access": "public"
6
6
  },
7
7
  "license": "MIT",
8
- "version": "2.2.0-rc.6",
8
+ "version": "2.2.0-rc.7",
9
9
  "description": "React hooks for building dApps on the SODAX cross-chain DeFi platform",
10
10
  "keywords": [
11
11
  "sodax",
@@ -34,17 +34,17 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "viem": "2.29.2",
37
- "@sodax/sdk": "2.2.0-rc.6"
37
+ "@sodax/sdk": "2.2.0-rc.7"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@arethetypeswrong/cli": "0.17.4",
41
41
  "@tanstack/react-query": "5.87.4",
42
42
  "@types/react": "19.0.8",
43
- "knip": "5.30.5",
43
+ "knip": "5.88.1",
44
44
  "tslib": "2.8.1",
45
45
  "tsup": "8.5.0",
46
46
  "typescript": "5.5.4",
47
- "vitest": "3.2.6"
47
+ "vitest": "4.1.11"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "@tanstack/react-query": "5.x",
@@ -0,0 +1,144 @@
1
+ import {
2
+ DETAILED_STATUS_NOT_DELIVERED,
3
+ SodaxError,
4
+ type BridgeDetailedStatusError,
5
+ type DetailedBridgeStatus,
6
+ type PacketData,
7
+ type Result,
8
+ } from '@sodax/sdk';
9
+ import { describe, expect, it } from 'vitest';
10
+ import {
11
+ advanceNotFoundStreak,
12
+ INITIAL_NOT_FOUND_STREAK,
13
+ MAX_NOT_FOUND_POLLS,
14
+ STATUS_POLL_MS,
15
+ } from '../shared/notFoundStreak.js';
16
+ import {
17
+ getBridgeDetailedStatusRefetchInterval,
18
+ isBridgeNotDelivered,
19
+ } from './getBridgeDetailedStatusRefetchInterval.js';
20
+
21
+ /**
22
+ * Guards the polling-stop invariant for `useBridgeDetailedStatus.refetchInterval`: stop on a
23
+ * terminal or abandoned backend record, on any relay packet (always terminal), on a rejected API
24
+ * key, and on an exhausted not-delivered budget — but keep polling through an outage. Tested as a
25
+ * pure function because dapp-kit's vitest runs in the `node` environment.
26
+ */
27
+ const KEY_A = 'arb:0xaaa';
28
+ const KEY_B = 'arb:0xbbb';
29
+
30
+ type Read = Result<DetailedBridgeStatus, BridgeDetailedStatusError> | undefined;
31
+
32
+ const backend = (status: string, abandonedAt?: string): Read => ({
33
+ ok: true,
34
+ value: {
35
+ source: 'backend',
36
+ data: { txHash: '0xaaa', srcChainKey: '0xa4b1.arbitrum', status, processingAttempts: 1, abandonedAt },
37
+ },
38
+ });
39
+
40
+ const packet: PacketData = {
41
+ src_chain_id: 23,
42
+ src_tx_hash: '0xaaa',
43
+ src_address: '0xsrc',
44
+ status: 'executed',
45
+ dst_chain_id: 146,
46
+ conn_sn: 1,
47
+ dst_address: '0xdst',
48
+ dst_tx_hash: '0xdst',
49
+ signatures: [],
50
+ payload: '0x',
51
+ };
52
+
53
+ const relayed: Read = { ok: true, value: { source: 'relay', data: packet } };
54
+
55
+ const lookupFailed = (context: Record<string, unknown>): Read => ({
56
+ ok: false,
57
+ error: new SodaxError('LOOKUP_FAILED', 'no source could answer', {
58
+ feature: 'bridge',
59
+ context: { phase: 'lookup', method: 'getDetailedStatus', ...context },
60
+ }),
61
+ });
62
+
63
+ const notDelivered = lookupFailed({ reason: DETAILED_STATUS_NOT_DELIVERED });
64
+ const outage = lookupFailed({});
65
+ const rejectedKey = lookupFailed({ status: 401 });
66
+
67
+ describe('isBridgeNotDelivered', () => {
68
+ it('counts only the ambiguous relay miss', () => {
69
+ expect(isBridgeNotDelivered(notDelivered)).toBe(true);
70
+ expect(isBridgeNotDelivered(outage)).toBe(false);
71
+ expect(isBridgeNotDelivered(rejectedKey)).toBe(false);
72
+ expect(isBridgeNotDelivered(relayed)).toBe(false);
73
+ expect(isBridgeNotDelivered(backend('relaying'))).toBe(false);
74
+ expect(isBridgeNotDelivered(undefined)).toBe(false);
75
+ });
76
+ });
77
+
78
+ describe('getBridgeDetailedStatusRefetchInterval', () => {
79
+ it('keeps polling an in-flight backend record', () => {
80
+ for (const status of ['pending', 'relaying', 'relayed']) {
81
+ expect(getBridgeDetailedStatusRefetchInterval(backend(status), 0)).toBe(STATUS_POLL_MS);
82
+ }
83
+ expect(getBridgeDetailedStatusRefetchInterval(undefined, 0)).toBe(STATUS_POLL_MS);
84
+ });
85
+
86
+ it('stops on the two terminal backend statuses and on an abandoned record', () => {
87
+ expect(getBridgeDetailedStatusRefetchInterval(backend('executed'), 0)).toBe(false);
88
+ expect(getBridgeDetailedStatusRefetchInterval(backend('failed'), 0)).toBe(false);
89
+ expect(getBridgeDetailedStatusRefetchInterval(backend('relayed', '2026-09-18T00:00:00.000Z'), 0)).toBe(false);
90
+ });
91
+
92
+ it('stops on a relay packet without waiting for a budget — that arm is terminal on arrival', () => {
93
+ expect(getBridgeDetailedStatusRefetchInterval(relayed, 0)).toBe(false);
94
+ });
95
+
96
+ it('stops on a rejected API key, at the first read', () => {
97
+ expect(getBridgeDetailedStatusRefetchInterval(rejectedKey, 0)).toBe(false);
98
+ });
99
+
100
+ it('stops a not-delivered read only once the budget is spent', () => {
101
+ expect(getBridgeDetailedStatusRefetchInterval(notDelivered, MAX_NOT_FOUND_POLLS - 1)).toBe(STATUS_POLL_MS);
102
+ expect(getBridgeDetailedStatusRefetchInterval(notDelivered, MAX_NOT_FOUND_POLLS)).toBe(false);
103
+ });
104
+
105
+ it('keeps polling an outage forever — that is how the read recovers', () => {
106
+ expect(getBridgeDetailedStatusRefetchInterval(outage, MAX_NOT_FOUND_POLLS)).toBe(STATUS_POLL_MS);
107
+ });
108
+ });
109
+
110
+ describe('the not-delivered budget, driven as the hook drives it', () => {
111
+ /** One query update per read, the way `refetchInterval` advances it. */
112
+ const advance = (reads: Read[], key = KEY_A, from = 1) =>
113
+ reads.reduce(
114
+ (acc, read, i) => advanceNotFoundStreak(acc, key, isBridgeNotDelivered(read), from + i),
115
+ INITIAL_NOT_FOUND_STREAK,
116
+ );
117
+
118
+ it('a backend-pending stretch never exhausts the budget', () => {
119
+ // The reset is what makes this safe: pending reads are not misses, so they zero the counter.
120
+ const pending = advance(Array.from({ length: MAX_NOT_FOUND_POLLS + 5 }, () => backend('pending')));
121
+ expect(pending.consecutiveNotFound).toBe(0);
122
+ expect(getBridgeDetailedStatusRefetchInterval(backend('pending'), pending.consecutiveNotFound)).toBe(
123
+ STATUS_POLL_MS,
124
+ );
125
+ });
126
+
127
+ it('an outage in the middle resets a run of misses', () => {
128
+ const state = advance([notDelivered, notDelivered, outage, notDelivered]);
129
+ expect(state.consecutiveNotFound).toBe(1);
130
+ });
131
+
132
+ it('stops only after MAX_NOT_FOUND_POLLS consecutive misses', () => {
133
+ const state = advance(Array.from({ length: MAX_NOT_FOUND_POLLS }, () => notDelivered));
134
+ expect(state.consecutiveNotFound).toBe(MAX_NOT_FOUND_POLLS);
135
+ expect(getBridgeDetailedStatusRefetchInterval(notDelivered, state.consecutiveNotFound)).toBe(false);
136
+ });
137
+
138
+ it('starts a fresh budget for a new source tx', () => {
139
+ const spent = advance(Array.from({ length: MAX_NOT_FOUND_POLLS }, () => notDelivered));
140
+ const next = advanceNotFoundStreak(spent, KEY_B, true, 1);
141
+ expect(next.consecutiveNotFound).toBe(1);
142
+ expect(next.pollKey).toBe(KEY_B);
143
+ });
144
+ });
@@ -0,0 +1,52 @@
1
+ import {
2
+ DETAILED_STATUS_NOT_DELIVERED,
3
+ isAuthFailure,
4
+ type BridgeDetailedStatusError,
5
+ type DetailedBridgeStatus,
6
+ type Result,
7
+ } from '@sodax/sdk';
8
+ import { MAX_NOT_FOUND_POLLS, STATUS_POLL_MS } from '../shared/notFoundStreak.js';
9
+
10
+ /**
11
+ * Structural mirror of `useBridgeDetailedStatus`'s data type. Declared locally rather than imported
12
+ * so this module does not own the hook's public contract.
13
+ */
14
+ type DetailedBridgeStatusRead = Result<DetailedBridgeStatus, BridgeDetailedStatusError> | undefined;
15
+
16
+ /**
17
+ * The read the budget counts: the relay has no packet for this source tx *and* the backend answered,
18
+ * so the miss is real rather than unprovable. Every other `LOOKUP_FAILED` is a dependency failing
19
+ * right now — the relay unreachable, a malformed response — and those keep polling, because that is
20
+ * how the read recovers when the outage ends.
21
+ */
22
+ export function isBridgeNotDelivered(data: DetailedBridgeStatusRead): boolean {
23
+ return data !== undefined && !data.ok && data.error?.context?.reason === DETAILED_STATUS_NOT_DELIVERED;
24
+ }
25
+
26
+ /**
27
+ * Polling interval for `useBridgeDetailedStatus`.
28
+ *
29
+ * Unlike the swap analog there is no in-flight second arm to wait on: the relay arm only ever
30
+ * carries a matched `executed` packet, so it is terminal on arrival. That leaves three stops — a
31
+ * terminal or abandoned backend record, a rejected API key, and the ambiguous relay miss once it has
32
+ * run `MAX_NOT_FOUND_POLLS` times in a row.
33
+ *
34
+ * Kept in its own pure module (no React/context imports) so it is unit-testable in dapp-kit's `node`
35
+ * test environment — importing the hook itself pulls in `useSodaxContext`.
36
+ */
37
+ export function getBridgeDetailedStatusRefetchInterval(
38
+ data: DetailedBridgeStatusRead,
39
+ consecutiveNotFound: number,
40
+ ): number | false {
41
+ if (data?.ok) {
42
+ if (data.value.source === 'relay') return false;
43
+ // The two terminal states of the bridge wire contract, plus a record the backend abandoned
44
+ // while its status was still non-terminal.
45
+ const { status, abandonedAt } = data.value.data;
46
+ return status === 'executed' || status === 'failed' || abandonedAt ? false : STATUS_POLL_MS;
47
+ }
48
+ // A rejected key is terminal — only a corrected key changes the answer, so stop asking.
49
+ if (data && !data.ok && isAuthFailure(data.error)) return false;
50
+ if (isBridgeNotDelivered(data) && consecutiveNotFound >= MAX_NOT_FOUND_POLLS) return false;
51
+ return STATUS_POLL_MS;
52
+ }
@@ -1,4 +1,6 @@
1
+ export * from './getBridgeDetailedStatusRefetchInterval.js'; // poll policy (drives the detailed-status hook)
1
2
  export * from './useBridge.js';
3
+ export * from './useBridgeDetailedStatus.js';
2
4
  export * from './useBridgeAllowance.js';
3
5
  export * from './useBridgeApprove.js';
4
6
  export * from './useGetBridgeableAmount.js';
@@ -0,0 +1,93 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { MAX_NOT_FOUND_POLLS, STATUS_POLL_MS } from '../shared/notFoundStreak.js';
3
+
4
+ /**
5
+ * Pins the WIRING the pure-policy test cannot see: the hook must pass the read into the policy and
6
+ * advance the budget once per query update. Feeding the policy the wrong argument reproduces a
7
+ * poll that never stops, with the policy's own tests still green.
8
+ *
9
+ * No renderer, per the package convention (see `_apiKeyWire.test.ts`): the React Query wrapper is
10
+ * mocked so the captured options bag can be driven directly.
11
+ */
12
+
13
+ // The captured options bag is opaque, like the real wrapper's.
14
+ let captured: any;
15
+
16
+ const refSlots: Array<{ current: unknown }> = [];
17
+ let refCursor = 0;
18
+
19
+ // Only useRef is needed, and call order is stable, so this replays React's slot semantics well
20
+ // enough to observe the budget across refetchInterval calls — the same shape
21
+ // `shared/useRequestTrustline.test.ts` uses.
22
+ vi.mock('react', () => ({
23
+ useRef: (initial: unknown) => {
24
+ const slot = refSlots[refCursor] ?? { current: initial };
25
+ refSlots[refCursor] = slot;
26
+ refCursor += 1;
27
+ return slot;
28
+ },
29
+ }));
30
+
31
+ const getDetailedStatus = vi.fn();
32
+ vi.mock('../shared/useSodaxContext.js', () => ({
33
+ useSodaxContext: () => ({ sodax: { bridge: { getDetailedStatus } } }),
34
+ }));
35
+ vi.mock('@tanstack/react-query', () => ({
36
+ useQuery: (options: any) => {
37
+ captured = options;
38
+ return {};
39
+ },
40
+ }));
41
+
42
+ const { useBridgeDetailedStatus } = await import('./useBridgeDetailedStatus.js');
43
+
44
+ const SRC_CHAIN = '0xa4b1.arbitrum';
45
+ const SRC_TX = '0xaaa';
46
+ const render = (apiConfig?: { apiKey: string }) => {
47
+ refCursor = 0;
48
+ return useBridgeDetailedStatus({ params: { srcChainKey: SRC_CHAIN, srcTxHash: SRC_TX, apiConfig } });
49
+ };
50
+
51
+ const notDeliveredRead = {
52
+ ok: false,
53
+ error: { code: 'LOOKUP_FAILED', context: { reason: 'relay_not_delivered' } },
54
+ };
55
+
56
+ describe('useBridgeDetailedStatus wiring', () => {
57
+ it('keys the query on the source tx and runs only when both identifiers are present', () => {
58
+ render();
59
+ expect(captured.queryKey).toEqual(['bridge', 'detailedStatus', SRC_CHAIN, SRC_TX]);
60
+ expect(captured.enabled).toBe(true);
61
+
62
+ refCursor = 0;
63
+ useBridgeDetailedStatus({ params: { srcChainKey: SRC_CHAIN, srcTxHash: undefined } });
64
+ expect(captured.enabled).toBe(false);
65
+ });
66
+
67
+ it('threads a per-request override into the SDK call', async () => {
68
+ render({ apiKey: 'per-action-key' });
69
+ await captured.queryFn();
70
+ expect(getDetailedStatus).toHaveBeenCalledWith(
71
+ { srcChainKey: SRC_CHAIN, srcTxHash: SRC_TX },
72
+ { apiKey: 'per-action-key' },
73
+ );
74
+ });
75
+
76
+ it('feeds the read into the policy, so a terminal answer stops the poll', () => {
77
+ render();
78
+ const relayed = { ok: true, value: { source: 'relay', data: { dst_tx_hash: '0xdst' } } };
79
+ expect(captured.refetchInterval({ state: { data: relayed, dataUpdateCount: 1 } })).toBe(false);
80
+ });
81
+
82
+ it('advances the not-delivered budget once per update, and stops when it is spent', () => {
83
+ refSlots.length = 0;
84
+ render();
85
+ // Same dataUpdateCount twice must not double-count, so the cap is reached on update 40, not 20.
86
+ for (let update = 1; update <= MAX_NOT_FOUND_POLLS - 1; update++) {
87
+ captured.refetchInterval({ state: { data: notDeliveredRead, dataUpdateCount: update } });
88
+ captured.refetchInterval({ state: { data: notDeliveredRead, dataUpdateCount: update } });
89
+ }
90
+ expect(captured.refetchInterval({ state: { data: notDeliveredRead, dataUpdateCount: 39 } })).toBe(STATUS_POLL_MS);
91
+ expect(captured.refetchInterval({ state: { data: notDeliveredRead, dataUpdateCount: 40 } })).toBe(false);
92
+ });
93
+ });