@sodax/dapp-kit 2.1.0-rc.5 → 2.1.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.
- package/dist/index.d.ts +34 -2
- package/dist/index.mjs +90 -3
- package/package.json +4 -4
- package/src/hooks/swap/getSwapStatusRefetchInterval.test.ts +105 -0
- package/src/hooks/swap/getSwapStatusRefetchInterval.ts +126 -0
- package/src/hooks/swap/index.ts +1 -0
- package/src/hooks/swap/useDetailedStatus.test.ts +195 -0
- package/src/hooks/swap/useDetailedStatus.ts +70 -0
- package/src/hooks/swap/useStatus.ts +20 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { UseMutationOptions, UseQueryOptions, UseMutationResult, MutateOptions, UseQueryResult, QueryClientConfig, QueryClient } from '@tanstack/react-query';
|
|
2
2
|
import * as _sodax_sdk from '@sodax/sdk';
|
|
3
|
-
import { Result, Sodax, SpokeChainKey, GetEstimateGasReturnType, EstimateGasParams, StellarChainKey, IStellarWalletProvider, INearWalletProvider, GetWalletProviderType, StellarAccountStatus, ActivateStellarAccountResult, IXServiceBase, XToken, EvmHubProvider, IBitcoinWalletProvider, RadfiWalletBalance, IWalletProvider, RadfiUtxo, MoneyMarketBorrowActionParams, TxHashPair, MoneyMarketRepayActionParams, MoneyMarketSupplyActionParams, MoneyMarketWithdrawActionParams, UserReserveData, AggregatedReserveData, BaseCurrencyInfo, ReservesDataHumanized, Address as Address$1, MoneyMarketParams, MoneyMarketApproveActionParams, TxReturnType, Erc20Token, ChainKey, ReserveDataHumanized, FormatReserveUSDResponse, FormatUserSummaryResponse, SolverIntentQuoteRequest, SwapActionParams, SwapResponse, SolverIntentStatusResponse, SolverErrorResponse, Hex, CreateIntentParams, CreateLimitOrderParams, Intent, LimitOrderActionParams, IntentResponse, UserIntentsResponse, OrderbookResponse, MoneyMarketPosition, MoneyMarketAsset, MoneyMarketAssetBorrowers, MoneyMarketAssetSuppliers, MoneyMarketBorrowers, GetSwapTokensResponseV2, RequestOverrideConfig, GetSwapTokensByChainResponseV2, QuoteResponseV2, QuoteRequestV2, QuoteQueryV2, DeadlineResponseV2, DeadlineQueryV2, AllowanceCheckResponseV2, CreateIntentParamsV2, ApproveResponseV2, CreateIntentResponseV2, SubmitIntentRequestV2, SubmitIntentResponseV2, StatusResponseV2, SwapIntentStatusCodeV2, CancelIntentRequestV2, CancelIntentResponseV2, IntentHashResponseV2, IntentRequestV2, IntentPacketResponseV2, IntentPacketRequestV2, IntentExtraDataResponseV2, IntentExtraDataRequestV2, IntentStateV2, GetIntentResponseV2, CreateLimitOrderParamsV2, CreateLimitOrderResponseV2, GasEstimateResponseV2, GasEstimateRequestV2, FeeResponseV2, SubmitTxRequestV2, SubmitTxResponseV2, SubmitTxStatusResponseV2, BridgeParams, CreateBridgeIntentParams, BridgeLimit, BridgeAllowanceCheckResponseV2, CreateBridgeIntentParamsV2, BridgeApproveResponseV2, BridgeableAmountResponseV2, BridgeQuoteRequestV2, CreateBridgeIntentResponseV2, BridgeFeeResponseV2, BridgeFeeRequestV2, BridgeableCheckResponseV2, BridgeSubmitTxRequestV2, BridgeSubmitTxResponseV2, BridgeSubmitTxStatusResponseV2, GetBridgeTokensResponseV2, GetBridgeTokensByChainResponseV2, StakeAction, StakeParams, UnstakeAction, ClaimAction, CancelUnstakeAction, StakingInfo, UnstakingInfo, UnstakeRequestWithPenalty, StakingConfig, InstantUnstakeAction, UnstakeParams, InstantUnstakeParams, PartnerFeeClaimAssetBalance, AutoSwapPreferences, FeeTokenApproveParams, FeeTokenApproveAction, HubChainKey, SetSwapPreferenceAction, PartnerFeeClaimSwapAction, IntentAutoSwapResult, PartnerFeeClaimCancelAction, GetUserIntentParams, HubAssetBalance, WithdrawHubAssetAction, IcxMigrateAction, IcxRevertMigrationAction, UnifiedBnUSDMigrateAction, BalnMigrateAction, MigrationAction, IcxMigrateParams, IcxCreateRevertMigrationParams, UnifiedBnUSDMigrateParams, BalnMigrateParams, PoolKey, PoolData, ClPositionInfo, AssetDepositAction, AssetWithdrawAction, CreateAssetDepositParams, ClSupplyParams, ClIncreaseLiquidityParams, ClLiquidityDecreaseLiquidityAction, ClDecreaseLiquidityParams, CreateAssetWithdrawParams, PoolSpokeAssets, DestinationParamsType, ClLiquidityClaimRewardsAction, LeverageYieldQuoteParams, LeverageYieldEffectiveApr, LeverageYieldPosition, LeverageYieldSwapDepositParams, LeverageYieldSwapPayload, SolverExecutionRequest, SolverExecutionResponse, VaultSwapActionParams, VaultSwapResponse, LeverageYieldSwapWithdrawParams, ActivateStellarAccountParams, StellarSponsorConfig, SodaxOptions } from '@sodax/sdk';
|
|
3
|
+
import { Result, Sodax, SpokeChainKey, GetEstimateGasReturnType, EstimateGasParams, StellarChainKey, IStellarWalletProvider, INearWalletProvider, GetWalletProviderType, StellarAccountStatus, ActivateStellarAccountResult, IXServiceBase, XToken, EvmHubProvider, IBitcoinWalletProvider, RadfiWalletBalance, IWalletProvider, RadfiUtxo, MoneyMarketBorrowActionParams, TxHashPair, MoneyMarketRepayActionParams, MoneyMarketSupplyActionParams, MoneyMarketWithdrawActionParams, UserReserveData, AggregatedReserveData, BaseCurrencyInfo, ReservesDataHumanized, Address as Address$1, MoneyMarketParams, MoneyMarketApproveActionParams, TxReturnType, Erc20Token, ChainKey, ReserveDataHumanized, FormatReserveUSDResponse, FormatUserSummaryResponse, SolverIntentQuoteRequest, SwapActionParams, SwapResponse, SolverIntentStatusResponse, SolverErrorResponse, Hex, DetailedSwapStatus, DetailedStatusError, CreateIntentParams, CreateLimitOrderParams, Intent, LimitOrderActionParams, IntentResponse, UserIntentsResponse, OrderbookResponse, MoneyMarketPosition, MoneyMarketAsset, MoneyMarketAssetBorrowers, MoneyMarketAssetSuppliers, MoneyMarketBorrowers, GetSwapTokensResponseV2, RequestOverrideConfig, GetSwapTokensByChainResponseV2, QuoteResponseV2, QuoteRequestV2, QuoteQueryV2, DeadlineResponseV2, DeadlineQueryV2, AllowanceCheckResponseV2, CreateIntentParamsV2, ApproveResponseV2, CreateIntentResponseV2, SubmitIntentRequestV2, SubmitIntentResponseV2, StatusResponseV2, SwapIntentStatusCodeV2, CancelIntentRequestV2, CancelIntentResponseV2, IntentHashResponseV2, IntentRequestV2, IntentPacketResponseV2, IntentPacketRequestV2, IntentExtraDataResponseV2, IntentExtraDataRequestV2, IntentStateV2, GetIntentResponseV2, CreateLimitOrderParamsV2, CreateLimitOrderResponseV2, GasEstimateResponseV2, GasEstimateRequestV2, FeeResponseV2, SubmitTxRequestV2, SubmitTxResponseV2, SubmitTxStatusResponseV2, BridgeParams, CreateBridgeIntentParams, BridgeLimit, BridgeAllowanceCheckResponseV2, CreateBridgeIntentParamsV2, BridgeApproveResponseV2, BridgeableAmountResponseV2, BridgeQuoteRequestV2, CreateBridgeIntentResponseV2, BridgeFeeResponseV2, BridgeFeeRequestV2, BridgeableCheckResponseV2, BridgeSubmitTxRequestV2, BridgeSubmitTxResponseV2, BridgeSubmitTxStatusResponseV2, GetBridgeTokensResponseV2, GetBridgeTokensByChainResponseV2, StakeAction, StakeParams, UnstakeAction, ClaimAction, CancelUnstakeAction, StakingInfo, UnstakingInfo, UnstakeRequestWithPenalty, StakingConfig, InstantUnstakeAction, UnstakeParams, InstantUnstakeParams, PartnerFeeClaimAssetBalance, AutoSwapPreferences, FeeTokenApproveParams, FeeTokenApproveAction, HubChainKey, SetSwapPreferenceAction, PartnerFeeClaimSwapAction, IntentAutoSwapResult, PartnerFeeClaimCancelAction, GetUserIntentParams, HubAssetBalance, WithdrawHubAssetAction, IcxMigrateAction, IcxRevertMigrationAction, UnifiedBnUSDMigrateAction, BalnMigrateAction, MigrationAction, IcxMigrateParams, IcxCreateRevertMigrationParams, UnifiedBnUSDMigrateParams, BalnMigrateParams, PoolKey, PoolData, ClPositionInfo, AssetDepositAction, AssetWithdrawAction, CreateAssetDepositParams, ClSupplyParams, ClIncreaseLiquidityParams, ClLiquidityDecreaseLiquidityAction, ClDecreaseLiquidityParams, CreateAssetWithdrawParams, PoolSpokeAssets, DestinationParamsType, ClLiquidityClaimRewardsAction, LeverageYieldQuoteParams, LeverageYieldEffectiveApr, LeverageYieldPosition, LeverageYieldSwapDepositParams, LeverageYieldSwapPayload, SolverExecutionRequest, SolverExecutionResponse, VaultSwapActionParams, VaultSwapResponse, LeverageYieldSwapWithdrawParams, ActivateStellarAccountParams, StellarSponsorConfig, SodaxOptions } from '@sodax/sdk';
|
|
4
4
|
export * from '@sodax/sdk';
|
|
5
5
|
import { Address } from 'viem';
|
|
6
6
|
import { ReactNode, ReactElement } from 'react';
|
|
@@ -799,6 +799,10 @@ type UseStatusParams = ReadHookParams<Result<SolverIntentStatusResponse, SolverE
|
|
|
799
799
|
/**
|
|
800
800
|
* Hook for monitoring the status of an intent-based swap.
|
|
801
801
|
*
|
|
802
|
+
* Polls every 3s while the intent is in flight. Stops on `SOLVED` (3) or `FAILED` (4). Stops after
|
|
803
|
+
* 40 consecutive successful fetches while status stays `NOT_FOUND` (~2 min) — a forgotten intent
|
|
804
|
+
* never changes. An in-flight status resets that streak. Override with `queryOptions.refetchInterval`.
|
|
805
|
+
*
|
|
802
806
|
* @example
|
|
803
807
|
* ```typescript
|
|
804
808
|
* const { data: status, isLoading } = useStatus({ params: { intentTxHash } });
|
|
@@ -806,6 +810,34 @@ type UseStatusParams = ReadHookParams<Result<SolverIntentStatusResponse, SolverE
|
|
|
806
810
|
*/
|
|
807
811
|
declare const useStatus: ({ params, queryOptions, }?: UseStatusParams) => UseQueryResult<Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined>;
|
|
808
812
|
|
|
813
|
+
type UseDetailedStatusResult = Result<DetailedSwapStatus, DetailedStatusError> | undefined;
|
|
814
|
+
type UseDetailedStatusParams = ReadHookParams<UseDetailedStatusResult, {
|
|
815
|
+
srcChainKey: SpokeChainKey | undefined;
|
|
816
|
+
srcTxHash: string | undefined;
|
|
817
|
+
}>;
|
|
818
|
+
/**
|
|
819
|
+
* Hook for monitoring a swap from its source-chain transaction.
|
|
820
|
+
*
|
|
821
|
+
* `useStatus` needs the hub tx hash and always asks the solver; this takes `(srcChainKey,
|
|
822
|
+
* srcTxHash)` — the pair you hold after `swap()` — and routes to whichever source can answer.
|
|
823
|
+
* `data.value` is discriminated on `source`, and each variant carries that source's payload
|
|
824
|
+
* unmodified.
|
|
825
|
+
*
|
|
826
|
+
* Polls every 3s. Stops once the answering source is terminal, and — like `useStatus` — after 40
|
|
827
|
+
* consecutive *ambiguous* reads: a solver `NOT_FOUND`, or a `LOOKUP_FAILED` whose relay has no
|
|
828
|
+
* packet for the tx. Neither can distinguish "still in flight" from "never will be", so the budget
|
|
829
|
+
* is what stops a swap nothing can resolve. A dependency outage — relay unreachable, solver down —
|
|
830
|
+
* keeps polling instead, so the read recovers by itself; any real status resets the budget.
|
|
831
|
+
* Override with `queryOptions.refetchInterval`.
|
|
832
|
+
*
|
|
833
|
+
* @example
|
|
834
|
+
* ```typescript
|
|
835
|
+
* const { data } = useDetailedStatus({ params: { srcChainKey, srcTxHash } });
|
|
836
|
+
* if (data?.ok && data.value.source === 'backend') console.log(data.value.data.status);
|
|
837
|
+
* ```
|
|
838
|
+
*/
|
|
839
|
+
declare const useDetailedStatus: ({ params, queryOptions, }?: UseDetailedStatusParams) => UseQueryResult<UseDetailedStatusResult>;
|
|
840
|
+
|
|
809
841
|
type UseSwapAllowanceParams<K extends SpokeChainKey> = ReadHookParams<boolean, {
|
|
810
842
|
payload: CreateIntentParams | CreateLimitOrderParams | undefined;
|
|
811
843
|
srcChainKey: K | undefined;
|
|
@@ -2758,4 +2790,4 @@ interface NearStorageGateState {
|
|
|
2758
2790
|
*/
|
|
2759
2791
|
declare function resolveNearStorageGate(chainKey: SpokeChainKey, check: NearStorageCheckResult): NearStorageGateState;
|
|
2760
2792
|
|
|
2761
|
-
export { type ATokenData, type BackendPaginationParams, type BitcoinTradingSetup, type CreateSodaxQueryClientOptions, type DecreaseLiquidityParamsCore, type DepositParamsCore, type LeverageYieldShareHolder, type LeverageYieldShareHolding, type MutationHookOptions, type MutationHookParams, type NearStorageCheckResult, type NearStorageGateState, type RadfiSession, type ReadHookParams, type ReadQueryOptions, type ReserveUsdFormat, type SafeUseMutationResult, SodaxProvider, type StellarCheckResult, type StellarGate, type StellarGateInputs, type StellarGateState, type SwapsApiApprovalHashes, type UseATokenParams, type UseATokensBalancesParams, type UseActivateStellarAccountVars, type UseApproveTokenVars, type UseBitcoinBalanceParams, type UseBitcoinTradingSetupParams, type UseBorrowVars, type UseBridgeAllowanceParams, type UseBridgeApiAllowanceParams, type UseBridgeApiApproveVars, type UseBridgeApiBridgeableAmountParams, type UseBridgeApiCreateBridgeIntentVars, type UseBridgeApiFeeParams, type UseBridgeApiIsBridgeableParams, type UseBridgeApiSubmitTxStatusParams, type UseBridgeApiSubmitTxVars, type UseBridgeApiTokensByChainParams, type UseBridgeApiTokensParams, type UseBridgeApproveVars, type UseBridgeVars, type UseClaimRewardsVars, type UseCreateDecreaseLiquidityParamsProps, type UseCreateDepositParamsProps, type UseCreateLimitOrderVars, type UseCreateSupplyLiquidityParamsProps, type UseCreateSupplyLiquidityParamsResult, type UseCreateWithdrawParamsProps, type UseDecreaseLiquidityVars, type UseDeriveUserWalletAddressParams, type UseDexAllowanceParams, type UseDexApproveVars, type UseDexDepositVars, type UseDexWithdrawVars, type UseEnsureRadfiAccessTokenVars, type UseEstablishTrustlineVars, type UseExpiredUtxosParams, type UseFeeClaimSwapVars, type UseFeeClaimWithdrawVars, type UseFetchAssetsBalancesParams, type UseFundTradingWalletVars, type UseGetAutoSwapPreferencesParams, type UseGetBridgeableAmountParams, type UseGetBridgeableTokensParams, type UseGetIntentDetailsParams, type UseGetUserHubWalletAddressParams, type UseGetUserIntentParams, type UseHubAssetBalancesParams, type UseIsTokenApprovedParams, type UseLeverageYieldDepositVars, type UseLeverageYieldEffectiveAprParams, type UseLeverageYieldNotifySolverVars, type UseLeverageYieldPositionParams, type UseLeverageYieldPreviewRedeemParams, type UseLeverageYieldQuoteParams, type UseLeverageYieldShareBalancesParams, type UseLeverageYieldTotalAssetsParams, type UseLeverageYieldVaultSwapVars, type UseLeverageYieldWithdrawVars, type UseLiquidityAmountsResult, type UseMMAllowanceParams, type UseMMApproveVars, type UseMigrateBalnVars, type UseMigrateIcxToSodaVars, type UseMigratebnUSDVars, type UseMigrationAllowanceInputs, type UseMigrationAllowanceParams, type UseMigrationApproveVars, type UseNearStorageCheckParams, type UsePartnerCancelIntentVars, type UsePoolBalancesParams, type UsePoolBalancesResponse, type UsePoolDataParams, type UsePoolsParams, type UsePositionInfoParams, type UsePositionInfoResponse, type UseQuoteParams, type UseRadfiAuthVars, type UseRadfiSessionReturn, type UseRadfiWithdrawVars, type UseRegisterNearStorageVars, type UseRenewUtxosVars, type UseRepayVars, type UseReservesDataParams, type UseReservesHumanizedParams, type UseReservesListParams, type UseReservesUsdFormatParams, type UseRevertMigrateSodaToIcxVars, type UseSetSwapPreferenceVars, type UseSetSwapPreferenceVarsHub, type UseSponsorConfigParams, type UseStatusParams, type UseStellarAccountActiveParams, type UseStellarAccountStatusParams, type UseStellarGateParams, type UseStellarTrustlineCheckParams, type UseSupplyLiquidityVars, type UseSupplyVars, type UseSwapAllowanceParams, type UseSwapApproveVars, type UseSwapVars, type UseSwapsApiAllowanceParams, type UseSwapsApiApproveAndBroadcastVars, type UseSwapsApiApproveVars, type UseSwapsApiCancelIntentVars, type UseSwapsApiCreateIntentVars, type UseSwapsApiCreateLimitOrderVars, type UseSwapsApiDeadlineParams, type UseSwapsApiEstimateGasParams, type UseSwapsApiFilledIntentParams, type UseSwapsApiIntentExtraDataParams, type UseSwapsApiIntentHashParams, type UseSwapsApiIntentPacketParams, type UseSwapsApiIntentParams, type UseSwapsApiPartnerFeeParams, type UseSwapsApiQuoteParams, type UseSwapsApiSolverFeeParams, type UseSwapsApiStatusParams, type UseSwapsApiSubmitIntentVars, type UseSwapsApiSubmitTxStatusParams, type UseSwapsApiSubmitTxVars, type UseSwapsApiTokensByChainParams, type UseSwapsApiTokensParams, type UseTradingWalletBalanceParams, type UseUserFormattedSummaryParams, type UseUserReservesDataParams, type UseWithdrawHubAssetVars, type UseWithdrawVars, type UseXBalancesParams, type WithdrawParamsCore, type XBalancesInputs, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getLeverageYieldQuoteQueryOptions, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, getSwapQuoteQueryOptions, getXBalancesQueryOptions, isTerminalSwapIntentStatus, isUserRejectedError, loadRadfiSession, resolveNearStorageGate, resolveStellarGate, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useActivateStellarAccount, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOrderbook, useBackendUserIntents, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApiAllowance, useBridgeApiApprove, useBridgeApiBridgeableAmount, useBridgeApiCreateBridgeIntent, useBridgeApiFee, useBridgeApiIsBridgeable, useBridgeApiSubmitTx, useBridgeApiSubmitTxStatus, useBridgeApiTokens, useBridgeApiTokensByChain, useBridgeApprove, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, useEnsureRadfiAccessToken, useEstablishTrustline, useEstimateGas, useExpiredUtxos, useFeeClaimSwap, useFeeClaimWithdraw, useFetchAssetsBalances, useFundTradingWallet, useGetAutoSwapPreferences, useGetBridgeableAmount, useGetBridgeableTokens, useGetIntentDetails, useGetUserHubWalletAddress, useGetUserIntent, useHubAssetBalances, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useIsTokenApproved, useLeverageYieldDeposit, useLeverageYieldEffectiveApr, useLeverageYieldNotifySolver, useLeverageYieldPosition, useLeverageYieldPreviewRedeem, useLeverageYieldQuote, useLeverageYieldShareBalances, useLeverageYieldTotalAssets, useLeverageYieldVaultSwap, useLeverageYieldWithdraw, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrateBaln, useMigrateIcxToSoda, useMigratebnUSD, useMigrationAllowance, useMigrationApprove, useNearStorageCheck, useNearStorageGate, usePartnerCancelIntent, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRegisterNearStorage, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesHumanized, useReservesList, useReservesUsdFormat, useRevertMigrateSodaToIcx, useSafeMutation, useSetSwapPreference, useSodaxContext, useSponsorConfig, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarAccountActive, useStellarAccountStatus, useStellarGate, useStellarTrustlineCheck, 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 };
|
|
2793
|
+
export { type ATokenData, type BackendPaginationParams, type BitcoinTradingSetup, type CreateSodaxQueryClientOptions, type DecreaseLiquidityParamsCore, type DepositParamsCore, type LeverageYieldShareHolder, type LeverageYieldShareHolding, type MutationHookOptions, type MutationHookParams, type NearStorageCheckResult, type NearStorageGateState, type RadfiSession, type ReadHookParams, type ReadQueryOptions, type ReserveUsdFormat, type SafeUseMutationResult, SodaxProvider, type StellarCheckResult, type StellarGate, type StellarGateInputs, type StellarGateState, type SwapsApiApprovalHashes, type UseATokenParams, type UseATokensBalancesParams, type UseActivateStellarAccountVars, type UseApproveTokenVars, type UseBitcoinBalanceParams, type UseBitcoinTradingSetupParams, type UseBorrowVars, type UseBridgeAllowanceParams, type UseBridgeApiAllowanceParams, type UseBridgeApiApproveVars, type UseBridgeApiBridgeableAmountParams, type UseBridgeApiCreateBridgeIntentVars, type UseBridgeApiFeeParams, type UseBridgeApiIsBridgeableParams, type UseBridgeApiSubmitTxStatusParams, type UseBridgeApiSubmitTxVars, type UseBridgeApiTokensByChainParams, type UseBridgeApiTokensParams, type UseBridgeApproveVars, type UseBridgeVars, type UseClaimRewardsVars, type UseCreateDecreaseLiquidityParamsProps, type UseCreateDepositParamsProps, type UseCreateLimitOrderVars, type UseCreateSupplyLiquidityParamsProps, type UseCreateSupplyLiquidityParamsResult, type UseCreateWithdrawParamsProps, type UseDecreaseLiquidityVars, type UseDeriveUserWalletAddressParams, type UseDetailedStatusParams, type UseDetailedStatusResult, type UseDexAllowanceParams, type UseDexApproveVars, type UseDexDepositVars, type UseDexWithdrawVars, type UseEnsureRadfiAccessTokenVars, type UseEstablishTrustlineVars, type UseExpiredUtxosParams, type UseFeeClaimSwapVars, type UseFeeClaimWithdrawVars, type UseFetchAssetsBalancesParams, type UseFundTradingWalletVars, type UseGetAutoSwapPreferencesParams, type UseGetBridgeableAmountParams, type UseGetBridgeableTokensParams, type UseGetIntentDetailsParams, type UseGetUserHubWalletAddressParams, type UseGetUserIntentParams, type UseHubAssetBalancesParams, type UseIsTokenApprovedParams, type UseLeverageYieldDepositVars, type UseLeverageYieldEffectiveAprParams, type UseLeverageYieldNotifySolverVars, type UseLeverageYieldPositionParams, type UseLeverageYieldPreviewRedeemParams, type UseLeverageYieldQuoteParams, type UseLeverageYieldShareBalancesParams, type UseLeverageYieldTotalAssetsParams, type UseLeverageYieldVaultSwapVars, type UseLeverageYieldWithdrawVars, type UseLiquidityAmountsResult, type UseMMAllowanceParams, type UseMMApproveVars, type UseMigrateBalnVars, type UseMigrateIcxToSodaVars, type UseMigratebnUSDVars, type UseMigrationAllowanceInputs, type UseMigrationAllowanceParams, type UseMigrationApproveVars, type UseNearStorageCheckParams, type UsePartnerCancelIntentVars, type UsePoolBalancesParams, type UsePoolBalancesResponse, type UsePoolDataParams, type UsePoolsParams, type UsePositionInfoParams, type UsePositionInfoResponse, type UseQuoteParams, type UseRadfiAuthVars, type UseRadfiSessionReturn, type UseRadfiWithdrawVars, type UseRegisterNearStorageVars, type UseRenewUtxosVars, type UseRepayVars, type UseReservesDataParams, type UseReservesHumanizedParams, type UseReservesListParams, type UseReservesUsdFormatParams, type UseRevertMigrateSodaToIcxVars, type UseSetSwapPreferenceVars, type UseSetSwapPreferenceVarsHub, type UseSponsorConfigParams, type UseStatusParams, type UseStellarAccountActiveParams, type UseStellarAccountStatusParams, type UseStellarGateParams, type UseStellarTrustlineCheckParams, type UseSupplyLiquidityVars, type UseSupplyVars, type UseSwapAllowanceParams, type UseSwapApproveVars, type UseSwapVars, type UseSwapsApiAllowanceParams, type UseSwapsApiApproveAndBroadcastVars, type UseSwapsApiApproveVars, type UseSwapsApiCancelIntentVars, type UseSwapsApiCreateIntentVars, type UseSwapsApiCreateLimitOrderVars, type UseSwapsApiDeadlineParams, type UseSwapsApiEstimateGasParams, type UseSwapsApiFilledIntentParams, type UseSwapsApiIntentExtraDataParams, type UseSwapsApiIntentHashParams, type UseSwapsApiIntentPacketParams, type UseSwapsApiIntentParams, type UseSwapsApiPartnerFeeParams, type UseSwapsApiQuoteParams, type UseSwapsApiSolverFeeParams, type UseSwapsApiStatusParams, type UseSwapsApiSubmitIntentVars, type UseSwapsApiSubmitTxStatusParams, type UseSwapsApiSubmitTxVars, type UseSwapsApiTokensByChainParams, type UseSwapsApiTokensParams, type UseTradingWalletBalanceParams, type UseUserFormattedSummaryParams, type UseUserReservesDataParams, type UseWithdrawHubAssetVars, type UseWithdrawVars, type UseXBalancesParams, type WithdrawParamsCore, type XBalancesInputs, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getLeverageYieldQuoteQueryOptions, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, getSwapQuoteQueryOptions, getXBalancesQueryOptions, isTerminalSwapIntentStatus, isUserRejectedError, loadRadfiSession, resolveNearStorageGate, resolveStellarGate, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useActivateStellarAccount, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOrderbook, useBackendUserIntents, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApiAllowance, useBridgeApiApprove, 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, useEnsureRadfiAccessToken, useEstablishTrustline, useEstimateGas, useExpiredUtxos, useFeeClaimSwap, useFeeClaimWithdraw, useFetchAssetsBalances, useFundTradingWallet, useGetAutoSwapPreferences, useGetBridgeableAmount, useGetBridgeableTokens, useGetIntentDetails, useGetUserHubWalletAddress, useGetUserIntent, useHubAssetBalances, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useIsTokenApproved, useLeverageYieldDeposit, useLeverageYieldEffectiveApr, useLeverageYieldNotifySolver, useLeverageYieldPosition, useLeverageYieldPreviewRedeem, useLeverageYieldQuote, useLeverageYieldShareBalances, useLeverageYieldTotalAssets, useLeverageYieldVaultSwap, useLeverageYieldWithdraw, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrateBaln, useMigrateIcxToSoda, useMigratebnUSD, useMigrationAllowance, useMigrationApprove, useNearStorageCheck, useNearStorageGate, usePartnerCancelIntent, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRegisterNearStorage, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesHumanized, useReservesList, useReservesUsdFormat, useRevertMigrateSodaToIcx, useSafeMutation, useSetSwapPreference, useSodaxContext, useSponsorConfig, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarAccountActive, useStellarAccountStatus, useStellarGate, useStellarTrustlineCheck, 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/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isSodaxError, ChainKeys, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, RadfiApiError, normalizePsbtToBase64, isHubChainKeyType, isEvmSpokeOnlyChainKeyType, isStellarChainKeyType, ClService, SPONSOR_CONFIG_TTL_MS, Sodax } from '@sodax/sdk';
|
|
1
|
+
import { isSodaxError, ChainKeys, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, RadfiApiError, normalizePsbtToBase64, isHubChainKeyType, isEvmSpokeOnlyChainKeyType, isStellarChainKeyType, ClService, SPONSOR_CONFIG_TTL_MS, Sodax, SolverIntentStatusCode, DETAILED_STATUS_NOT_DELIVERED } 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';
|
|
@@ -1107,12 +1107,63 @@ function useSwap({
|
|
|
1107
1107
|
}
|
|
1108
1108
|
});
|
|
1109
1109
|
}
|
|
1110
|
+
var STATUS_POLL_MS = 3e3;
|
|
1111
|
+
var MAX_NOT_FOUND_POLLS = 40;
|
|
1112
|
+
var INITIAL_NOT_FOUND_STREAK = {
|
|
1113
|
+
pollKey: void 0,
|
|
1114
|
+
seenUpdates: 0,
|
|
1115
|
+
consecutiveNotFound: 0
|
|
1116
|
+
};
|
|
1117
|
+
function getSwapStatusRefetchInterval(data, consecutiveNotFound) {
|
|
1118
|
+
const status = data?.ok ? data.value.status : void 0;
|
|
1119
|
+
if (status === SolverIntentStatusCode.SOLVED || status === SolverIntentStatusCode.FAILED) {
|
|
1120
|
+
return false;
|
|
1121
|
+
}
|
|
1122
|
+
if (status === SolverIntentStatusCode.NOT_FOUND && consecutiveNotFound >= MAX_NOT_FOUND_POLLS) {
|
|
1123
|
+
return false;
|
|
1124
|
+
}
|
|
1125
|
+
return STATUS_POLL_MS;
|
|
1126
|
+
}
|
|
1127
|
+
function nextNotFoundStreak(data, previousStreak) {
|
|
1128
|
+
const status = data?.ok ? data.value.status : void 0;
|
|
1129
|
+
return status === SolverIntentStatusCode.NOT_FOUND ? previousStreak + 1 : 0;
|
|
1130
|
+
}
|
|
1131
|
+
function advanceNotFoundStreak(state, pollKey, data, dataUpdateCount) {
|
|
1132
|
+
if (state.pollKey !== pollKey) {
|
|
1133
|
+
state = { pollKey, seenUpdates: 0, consecutiveNotFound: 0 };
|
|
1134
|
+
}
|
|
1135
|
+
if (state.seenUpdates === dataUpdateCount) {
|
|
1136
|
+
return state;
|
|
1137
|
+
}
|
|
1138
|
+
return {
|
|
1139
|
+
pollKey,
|
|
1140
|
+
seenUpdates: dataUpdateCount,
|
|
1141
|
+
consecutiveNotFound: nextNotFoundStreak(data, state.consecutiveNotFound)
|
|
1142
|
+
};
|
|
1143
|
+
}
|
|
1144
|
+
function toNotFoundBudgetRead(data) {
|
|
1145
|
+
if (data === void 0) return void 0;
|
|
1146
|
+
if (data.ok) {
|
|
1147
|
+
return data.value.source === "solver" ? { ok: true, value: data.value.data } : void 0;
|
|
1148
|
+
}
|
|
1149
|
+
return data.error?.context?.reason === DETAILED_STATUS_NOT_DELIVERED ? { ok: true, value: { status: SolverIntentStatusCode.NOT_FOUND } } : void 0;
|
|
1150
|
+
}
|
|
1151
|
+
function getDetailedStatusRefetchInterval(data, consecutiveNotFound) {
|
|
1152
|
+
if (data?.ok && data.value.source === "backend") {
|
|
1153
|
+
const { status } = data.value.data;
|
|
1154
|
+
return status === "solved" || status === "failed" ? false : STATUS_POLL_MS;
|
|
1155
|
+
}
|
|
1156
|
+
return getSwapStatusRefetchInterval(toNotFoundBudgetRead(data), consecutiveNotFound);
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
// src/hooks/swap/useStatus.ts
|
|
1110
1160
|
var useStatus = ({
|
|
1111
1161
|
params,
|
|
1112
1162
|
queryOptions
|
|
1113
1163
|
} = {}) => {
|
|
1114
1164
|
const { sodax } = useSodaxContext();
|
|
1115
1165
|
const intentTxHash = params?.intentTxHash;
|
|
1166
|
+
const notFoundStreakRef = useRef({ ...INITIAL_NOT_FOUND_STREAK });
|
|
1116
1167
|
return useQuery({
|
|
1117
1168
|
queryKey: ["swap", "status", intentTxHash],
|
|
1118
1169
|
queryFn: async () => {
|
|
@@ -1120,7 +1171,43 @@ var useStatus = ({
|
|
|
1120
1171
|
return sodax.swaps.getStatus({ intent_tx_hash: intentTxHash });
|
|
1121
1172
|
},
|
|
1122
1173
|
enabled: !!intentTxHash,
|
|
1123
|
-
refetchInterval:
|
|
1174
|
+
refetchInterval: (query) => {
|
|
1175
|
+
notFoundStreakRef.current = advanceNotFoundStreak(
|
|
1176
|
+
notFoundStreakRef.current,
|
|
1177
|
+
intentTxHash,
|
|
1178
|
+
query.state.data,
|
|
1179
|
+
query.state.dataUpdateCount
|
|
1180
|
+
);
|
|
1181
|
+
return getSwapStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
|
|
1182
|
+
},
|
|
1183
|
+
...queryOptions
|
|
1184
|
+
});
|
|
1185
|
+
};
|
|
1186
|
+
var useDetailedStatus = ({
|
|
1187
|
+
params,
|
|
1188
|
+
queryOptions
|
|
1189
|
+
} = {}) => {
|
|
1190
|
+
const { sodax } = useSodaxContext();
|
|
1191
|
+
const srcChainKey = params?.srcChainKey;
|
|
1192
|
+
const srcTxHash = params?.srcTxHash;
|
|
1193
|
+
const pollKey = srcChainKey && srcTxHash ? `${srcChainKey}:${srcTxHash}` : void 0;
|
|
1194
|
+
const notFoundStreakRef = useRef({ ...INITIAL_NOT_FOUND_STREAK });
|
|
1195
|
+
return useQuery({
|
|
1196
|
+
queryKey: ["swap", "detailedStatus", srcChainKey, srcTxHash],
|
|
1197
|
+
queryFn: async () => {
|
|
1198
|
+
if (!srcChainKey || !srcTxHash) return void 0;
|
|
1199
|
+
return sodax.swaps.getDetailedStatus({ srcChainKey, srcTxHash });
|
|
1200
|
+
},
|
|
1201
|
+
enabled: !!srcChainKey && !!srcTxHash,
|
|
1202
|
+
refetchInterval: (query) => {
|
|
1203
|
+
notFoundStreakRef.current = advanceNotFoundStreak(
|
|
1204
|
+
notFoundStreakRef.current,
|
|
1205
|
+
pollKey,
|
|
1206
|
+
toNotFoundBudgetRead(query.state.data),
|
|
1207
|
+
query.state.dataUpdateCount
|
|
1208
|
+
);
|
|
1209
|
+
return getDetailedStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
|
|
1210
|
+
},
|
|
1124
1211
|
...queryOptions
|
|
1125
1212
|
});
|
|
1126
1213
|
};
|
|
@@ -3696,4 +3783,4 @@ function createSodaxQueryClient({
|
|
|
3696
3783
|
});
|
|
3697
3784
|
}
|
|
3698
3785
|
|
|
3699
|
-
export { SodaxProvider, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getLeverageYieldQuoteQueryOptions, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, getSwapQuoteQueryOptions, getXBalancesQueryOptions, isTerminalSwapIntentStatus, isUserRejectedError, loadRadfiSession, resolveNearStorageGate, resolveStellarGate, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useActivateStellarAccount, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOrderbook, useBackendUserIntents, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApiAllowance, useBridgeApiApprove, useBridgeApiBridgeableAmount, useBridgeApiCreateBridgeIntent, useBridgeApiFee, useBridgeApiIsBridgeable, useBridgeApiSubmitTx, useBridgeApiSubmitTxStatus, useBridgeApiTokens, useBridgeApiTokensByChain, useBridgeApprove, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, useEnsureRadfiAccessToken, useEstablishTrustline, useEstimateGas, useExpiredUtxos, useFeeClaimSwap, useFeeClaimWithdraw, useFetchAssetsBalances, useFundTradingWallet, useGetAutoSwapPreferences, useGetBridgeableAmount, useGetBridgeableTokens, useGetIntentDetails, useGetUserHubWalletAddress, useGetUserIntent, useHubAssetBalances, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useIsTokenApproved, useLeverageYieldDeposit, useLeverageYieldEffectiveApr, useLeverageYieldNotifySolver, useLeverageYieldPosition, useLeverageYieldPreviewRedeem, useLeverageYieldQuote, useLeverageYieldShareBalances, useLeverageYieldTotalAssets, useLeverageYieldVaultSwap, useLeverageYieldWithdraw, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrateBaln, useMigrateIcxToSoda, useMigratebnUSD, useMigrationAllowance, useMigrationApprove, useNearStorageCheck, useNearStorageGate, usePartnerCancelIntent, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRegisterNearStorage, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesHumanized, useReservesList, useReservesUsdFormat, useRevertMigrateSodaToIcx, useSafeMutation, useSetSwapPreference, useSodaxContext, useSponsorConfig, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarAccountActive, useStellarAccountStatus, useStellarGate, useStellarTrustlineCheck, 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 };
|
|
3786
|
+
export { SodaxProvider, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getLeverageYieldQuoteQueryOptions, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, getSwapQuoteQueryOptions, getXBalancesQueryOptions, isTerminalSwapIntentStatus, isUserRejectedError, loadRadfiSession, resolveNearStorageGate, resolveStellarGate, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useActivateStellarAccount, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOrderbook, useBackendUserIntents, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApiAllowance, useBridgeApiApprove, 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, useEnsureRadfiAccessToken, useEstablishTrustline, useEstimateGas, useExpiredUtxos, useFeeClaimSwap, useFeeClaimWithdraw, useFetchAssetsBalances, useFundTradingWallet, useGetAutoSwapPreferences, useGetBridgeableAmount, useGetBridgeableTokens, useGetIntentDetails, useGetUserHubWalletAddress, useGetUserIntent, useHubAssetBalances, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useIsTokenApproved, useLeverageYieldDeposit, useLeverageYieldEffectiveApr, useLeverageYieldNotifySolver, useLeverageYieldPosition, useLeverageYieldPreviewRedeem, useLeverageYieldQuote, useLeverageYieldShareBalances, useLeverageYieldTotalAssets, useLeverageYieldVaultSwap, useLeverageYieldWithdraw, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrateBaln, useMigrateIcxToSoda, useMigratebnUSD, useMigrationAllowance, useMigrationApprove, useNearStorageCheck, useNearStorageGate, usePartnerCancelIntent, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRegisterNearStorage, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesHumanized, useReservesList, useReservesUsdFormat, useRevertMigrateSodaToIcx, useSafeMutation, useSetSwapPreference, useSodaxContext, useSponsorConfig, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarAccountActive, useStellarAccountStatus, useStellarGate, useStellarTrustlineCheck, 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.1.0-rc.
|
|
8
|
+
"version": "2.1.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,7 +34,7 @@
|
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"viem": "2.29.2",
|
|
37
|
-
"@sodax/sdk": "2.1.0-rc.
|
|
37
|
+
"@sodax/sdk": "2.1.0-rc.7"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@arethetypeswrong/cli": "0.17.4",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
"react": ">=18"
|
|
52
52
|
},
|
|
53
53
|
"engines": {
|
|
54
|
-
"node": ">=
|
|
54
|
+
"node": ">=22.12.0"
|
|
55
55
|
},
|
|
56
56
|
"sideEffects": false,
|
|
57
57
|
"exports": {
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
}
|
|
63
63
|
},
|
|
64
64
|
"scripts": {
|
|
65
|
-
"build": "tsup",
|
|
65
|
+
"build": "tsup && node ../../scripts/verify-dist-exports.mjs",
|
|
66
66
|
"dev": "tsup --watch ./src",
|
|
67
67
|
"test": "vitest run",
|
|
68
68
|
"clean": "rm -rf dist && rm -rf node_modules && rm -rf .turbo",
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { SolverIntentErrorCode, SolverIntentStatusCode } from '@sodax/sdk';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import {
|
|
4
|
+
advanceNotFoundStreak,
|
|
5
|
+
getSwapStatusRefetchInterval,
|
|
6
|
+
INITIAL_NOT_FOUND_STREAK,
|
|
7
|
+
MAX_NOT_FOUND_POLLS,
|
|
8
|
+
nextNotFoundStreak,
|
|
9
|
+
STATUS_POLL_MS,
|
|
10
|
+
} from './getSwapStatusRefetchInterval.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Guards the polling-stop invariant for `useStatus.refetchInterval`: keep polling until SOLVED/
|
|
14
|
+
* FAILED, or until NOT_FOUND has been consecutive for MAX_NOT_FOUND_POLLS successful fetches.
|
|
15
|
+
* Tested as a pure function because dapp-kit's vitest runs in the `node` environment.
|
|
16
|
+
*/
|
|
17
|
+
const HASH_A = '0xaaa';
|
|
18
|
+
const HASH_B = '0xbbb';
|
|
19
|
+
const ok = (status: SolverIntentStatusCode) => ({ ok: true as const, value: { status } });
|
|
20
|
+
|
|
21
|
+
const solverError = {
|
|
22
|
+
ok: false as const,
|
|
23
|
+
error: { detail: { code: SolverIntentErrorCode.INTENT_NOT_FOUND, message: 'missing' } },
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
describe('getSwapStatusRefetchInterval', () => {
|
|
27
|
+
it('stops immediately on SOLVED (3) and FAILED (4), even at consecutive count 1', () => {
|
|
28
|
+
expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.SOLVED), 1)).toBe(false);
|
|
29
|
+
expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.FAILED), 1)).toBe(false);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('keeps polling NOT_FOUND until MAX_NOT_FOUND_POLLS consecutive, then stops', () => {
|
|
33
|
+
expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), MAX_NOT_FOUND_POLLS - 1)).toBe(
|
|
34
|
+
STATUS_POLL_MS,
|
|
35
|
+
);
|
|
36
|
+
expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), MAX_NOT_FOUND_POLLS)).toBe(false);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('never stops in-flight NOT_STARTED_YET (1) or STARTED_NOT_FINISHED (2), even at a high count', () => {
|
|
40
|
+
expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_STARTED_YET), 100)).toBe(STATUS_POLL_MS);
|
|
41
|
+
expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.STARTED_NOT_FINISHED), 100)).toBe(STATUS_POLL_MS);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('keeps polling the first NOT_FOUND after a long in-flight streak', () => {
|
|
45
|
+
expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), 1)).toBe(STATUS_POLL_MS);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('keeps polling when no status has arrived yet (undefined) or the Result is ok: false', () => {
|
|
49
|
+
expect(getSwapStatusRefetchInterval(undefined, 1)).toBe(STATUS_POLL_MS);
|
|
50
|
+
expect(getSwapStatusRefetchInterval(solverError, MAX_NOT_FOUND_POLLS)).toBe(STATUS_POLL_MS);
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
describe('nextNotFoundStreak', () => {
|
|
55
|
+
it('increments only while status is NOT_FOUND and resets otherwise', () => {
|
|
56
|
+
expect(nextNotFoundStreak(ok(SolverIntentStatusCode.NOT_FOUND), 0)).toBe(1);
|
|
57
|
+
expect(nextNotFoundStreak(ok(SolverIntentStatusCode.NOT_FOUND), 39)).toBe(40);
|
|
58
|
+
expect(nextNotFoundStreak(ok(SolverIntentStatusCode.STARTED_NOT_FINISHED), 39)).toBe(0);
|
|
59
|
+
expect(nextNotFoundStreak(undefined, 5)).toBe(0);
|
|
60
|
+
expect(nextNotFoundStreak(solverError, 5)).toBe(0);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
describe('advanceNotFoundStreak', () => {
|
|
65
|
+
it('increments consecutive NOT_FOUND once per dataUpdateCount, not per refetchInterval call', () => {
|
|
66
|
+
let state = INITIAL_NOT_FOUND_STREAK;
|
|
67
|
+
state = advanceNotFoundStreak(state, HASH_A, ok(SolverIntentStatusCode.NOT_FOUND), 1);
|
|
68
|
+
expect(state.consecutiveNotFound).toBe(1);
|
|
69
|
+
state = advanceNotFoundStreak(state, HASH_A, ok(SolverIntentStatusCode.NOT_FOUND), 1);
|
|
70
|
+
expect(state.consecutiveNotFound).toBe(1);
|
|
71
|
+
state = advanceNotFoundStreak(state, HASH_A, ok(SolverIntentStatusCode.NOT_FOUND), 2);
|
|
72
|
+
expect(state.consecutiveNotFound).toBe(2);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('resets the streak when an in-flight status follows a long NOT_FOUND run', () => {
|
|
76
|
+
const started = advanceNotFoundStreak(
|
|
77
|
+
{ pollKey: HASH_A, seenUpdates: 39, consecutiveNotFound: 39 },
|
|
78
|
+
HASH_A,
|
|
79
|
+
ok(SolverIntentStatusCode.STARTED_NOT_FINISHED),
|
|
80
|
+
40,
|
|
81
|
+
);
|
|
82
|
+
expect(started.consecutiveNotFound).toBe(0);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('starts a new streak at 1 after in-flight polls, so a solver restart cannot stop the query', () => {
|
|
86
|
+
let state = INITIAL_NOT_FOUND_STREAK;
|
|
87
|
+
state = advanceNotFoundStreak(state, HASH_A, ok(SolverIntentStatusCode.STARTED_NOT_FINISHED), 40);
|
|
88
|
+
state = advanceNotFoundStreak(state, HASH_A, ok(SolverIntentStatusCode.NOT_FOUND), 41);
|
|
89
|
+
expect(state.consecutiveNotFound).toBe(1);
|
|
90
|
+
expect(getSwapStatusRefetchInterval(ok(SolverIntentStatusCode.NOT_FOUND), state.consecutiveNotFound)).toBe(
|
|
91
|
+
STATUS_POLL_MS,
|
|
92
|
+
);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('resets on pollKey change so a prior intent cannot consume the next budget', () => {
|
|
96
|
+
const state = advanceNotFoundStreak(
|
|
97
|
+
{ pollKey: HASH_A, seenUpdates: 39, consecutiveNotFound: 39 },
|
|
98
|
+
HASH_B,
|
|
99
|
+
ok(SolverIntentStatusCode.NOT_FOUND),
|
|
100
|
+
1,
|
|
101
|
+
);
|
|
102
|
+
expect(state.consecutiveNotFound).toBe(1);
|
|
103
|
+
expect(state.pollKey).toBe(HASH_B);
|
|
104
|
+
});
|
|
105
|
+
});
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DETAILED_STATUS_NOT_DELIVERED,
|
|
3
|
+
SolverIntentStatusCode,
|
|
4
|
+
type DetailedStatusError,
|
|
5
|
+
type DetailedSwapStatus,
|
|
6
|
+
type Result,
|
|
7
|
+
type SolverErrorResponse,
|
|
8
|
+
type SolverIntentStatusResponse,
|
|
9
|
+
} from '@sodax/sdk';
|
|
10
|
+
|
|
11
|
+
export const STATUS_POLL_MS = 3000;
|
|
12
|
+
/** Cap consecutive NOT_FOUND polls (~2 min at 3s). First NOT_FOUND is a race, not a stop. */
|
|
13
|
+
export const MAX_NOT_FOUND_POLLS = 40;
|
|
14
|
+
|
|
15
|
+
export type SwapStatusResult = Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined;
|
|
16
|
+
|
|
17
|
+
export type NotFoundStreakState = {
|
|
18
|
+
/** Identity of what is being polled — an intent tx hash, or a composite source-chain/tx key. */
|
|
19
|
+
pollKey: string | undefined;
|
|
20
|
+
seenUpdates: number;
|
|
21
|
+
consecutiveNotFound: number;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export const INITIAL_NOT_FOUND_STREAK: NotFoundStreakState = {
|
|
25
|
+
pollKey: undefined,
|
|
26
|
+
seenUpdates: 0,
|
|
27
|
+
consecutiveNotFound: 0,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Polling interval for `useStatus`. Stops on SOLVED/FAILED immediately; stops on NOT_FOUND only
|
|
32
|
+
* after `MAX_NOT_FOUND_POLLS` consecutive successful fetches (solver forgot / never saw the intent).
|
|
33
|
+
* In-flight statuses keep polling with no global cap.
|
|
34
|
+
*
|
|
35
|
+
* Kept in its own pure module (no React/context imports) so it is unit-testable in dapp-kit's
|
|
36
|
+
* `node` test environment — importing the hook itself pulls in `useSodaxContext`.
|
|
37
|
+
*/
|
|
38
|
+
export function getSwapStatusRefetchInterval(data: SwapStatusResult, consecutiveNotFound: number): number | false {
|
|
39
|
+
const status = data?.ok ? data.value.status : undefined;
|
|
40
|
+
if (status === SolverIntentStatusCode.SOLVED || status === SolverIntentStatusCode.FAILED) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (status === SolverIntentStatusCode.NOT_FOUND && consecutiveNotFound >= MAX_NOT_FOUND_POLLS) {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
return STATUS_POLL_MS;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function nextNotFoundStreak(data: SwapStatusResult, previousStreak: number): number {
|
|
50
|
+
const status = data?.ok ? data.value.status : undefined;
|
|
51
|
+
return status === SolverIntentStatusCode.NOT_FOUND ? previousStreak + 1 : 0;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Advances the consecutive-NOT_FOUND counter once per successful query update. A `pollKey` change
|
|
56
|
+
* starts a new streak so a prior intent's count cannot stop the next one. React Query may call
|
|
57
|
+
* `refetchInterval` more than once per fetch — same `dataUpdateCount` is a no-op.
|
|
58
|
+
*/
|
|
59
|
+
export function advanceNotFoundStreak(
|
|
60
|
+
state: NotFoundStreakState,
|
|
61
|
+
pollKey: string | undefined,
|
|
62
|
+
data: SwapStatusResult,
|
|
63
|
+
dataUpdateCount: number,
|
|
64
|
+
): NotFoundStreakState {
|
|
65
|
+
if (state.pollKey !== pollKey) {
|
|
66
|
+
state = { pollKey, seenUpdates: 0, consecutiveNotFound: 0 };
|
|
67
|
+
}
|
|
68
|
+
if (state.seenUpdates === dataUpdateCount) {
|
|
69
|
+
return state;
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
pollKey,
|
|
73
|
+
seenUpdates: dataUpdateCount,
|
|
74
|
+
consecutiveNotFound: nextNotFoundStreak(data, state.consecutiveNotFound),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Structural mirror of `useDetailedStatus`'s data type. Declared locally rather than imported so
|
|
80
|
+
* this module does not own another hook's public contract — `UseDetailedStatusResult` lives with
|
|
81
|
+
* the hook.
|
|
82
|
+
*/
|
|
83
|
+
type DetailedStatusRead = Result<DetailedSwapStatus, DetailedStatusError> | undefined;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Maps a detailed-status read onto the shape the shared NOT_FOUND policy consumes, three ways:
|
|
87
|
+
*
|
|
88
|
+
* - solver arm → passes through, so its status drives the budget as it does for `useStatus`;
|
|
89
|
+
* - backend arm → `undefined`, which resets the budget; the solver is not the one being asked;
|
|
90
|
+
* - failed read → counts as `NOT_FOUND` **only** when the relay has no packet for this source tx
|
|
91
|
+
* (`DETAILED_STATUS_NOT_DELIVERED`). That miss is ambiguous — a swap still in flight and one whose
|
|
92
|
+
* tx never relayed look the same — so a budget is the only way to stop the second case.
|
|
93
|
+
*
|
|
94
|
+
* Every other `LOOKUP_FAILED` is a dependency failing right now: the relay unreachable, a malformed
|
|
95
|
+
* response, the solver down. Those reset the budget and keep polling, because that is how the read
|
|
96
|
+
* recovers when the outage ends. Counting them would stop polling a healthy swap after ~2 min of
|
|
97
|
+
* downtime and never resume.
|
|
98
|
+
*/
|
|
99
|
+
export function toNotFoundBudgetRead(data: DetailedStatusRead): SwapStatusResult {
|
|
100
|
+
if (data === undefined) return undefined;
|
|
101
|
+
if (data.ok) {
|
|
102
|
+
return data.value.source === 'solver' ? { ok: true, value: data.value.data } : undefined;
|
|
103
|
+
}
|
|
104
|
+
return data.error?.context?.reason === DETAILED_STATUS_NOT_DELIVERED
|
|
105
|
+
? { ok: true, value: { status: SolverIntentStatusCode.NOT_FOUND } }
|
|
106
|
+
: undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Polling interval for `useDetailedStatus`. Backend records report terminality in their own
|
|
111
|
+
* vocabulary; everything else reuses `useStatus`'s policy verbatim, so `MAX_NOT_FOUND_POLLS` stays
|
|
112
|
+
* the single cutoff — for a forgotten intent and for a swap no source can resolve.
|
|
113
|
+
*/
|
|
114
|
+
export function getDetailedStatusRefetchInterval(
|
|
115
|
+
data: DetailedStatusRead,
|
|
116
|
+
consecutiveNotFound: number,
|
|
117
|
+
): number | false {
|
|
118
|
+
if (data?.ok && data.value.source === 'backend') {
|
|
119
|
+
// Both terminal states of `SubmitSwapTxStatusV2`. Today the SDK routes `'failed'` records to the
|
|
120
|
+
// solver so only `'solved'` reaches us, but that is its routing rule, not this hook's contract —
|
|
121
|
+
// encoding the wire contract keeps a terminal record from being polled forever if it changes.
|
|
122
|
+
const { status } = data.value.data;
|
|
123
|
+
return status === 'solved' || status === 'failed' ? false : STATUS_POLL_MS;
|
|
124
|
+
}
|
|
125
|
+
return getSwapStatusRefetchInterval(toNotFoundBudgetRead(data), consecutiveNotFound);
|
|
126
|
+
}
|
package/src/hooks/swap/index.ts
CHANGED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { DETAILED_STATUS_NOT_DELIVERED, SodaxError, SolverIntentStatusCode, type DetailedSwapStatus } from '@sodax/sdk';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import {
|
|
4
|
+
advanceNotFoundStreak,
|
|
5
|
+
getDetailedStatusRefetchInterval,
|
|
6
|
+
INITIAL_NOT_FOUND_STREAK,
|
|
7
|
+
MAX_NOT_FOUND_POLLS,
|
|
8
|
+
STATUS_POLL_MS,
|
|
9
|
+
toNotFoundBudgetRead,
|
|
10
|
+
} from './getSwapStatusRefetchInterval.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Guards the polling-stop invariant for `useDetailedStatus`. The two variants report terminality in
|
|
14
|
+
* their own vocabularies, so the stop condition reads whichever source answered. Unresolved reads
|
|
15
|
+
* share `useStatus`'s single budget — but only the ones that are ambiguous by nature (solver
|
|
16
|
+
* `NOT_FOUND`, or a relay with no packet for the tx), never a dependency outage, which must keep
|
|
17
|
+
* polling so it recovers on its own.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** Derived from the public union so the fixtures track the wire contract without a cast. */
|
|
21
|
+
type BackendStatus = Extract<DetailedSwapStatus, { source: 'backend' }>['data']['status'];
|
|
22
|
+
|
|
23
|
+
const backend = (status: BackendStatus): DetailedSwapStatus => ({
|
|
24
|
+
source: 'backend',
|
|
25
|
+
data: { txHash: '0xsrc', srcChainKey: 'arb', status, processingAttempts: 1 },
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const solver = (status: SolverIntentStatusCode): DetailedSwapStatus => ({
|
|
29
|
+
source: 'solver',
|
|
30
|
+
dstTxHash: '0xdst',
|
|
31
|
+
data: { status },
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const ok = (value: DetailedSwapStatus) => ({ ok: true as const, value });
|
|
35
|
+
|
|
36
|
+
/** The relay has no packet for this tx — ambiguous between "not yet" and "never", so it is budgeted. */
|
|
37
|
+
const notDelivered = {
|
|
38
|
+
ok: false as const,
|
|
39
|
+
error: new SodaxError('LOOKUP_FAILED', 'relay has not delivered the intent to the hub yet', {
|
|
40
|
+
feature: 'swap',
|
|
41
|
+
context: { reason: DETAILED_STATUS_NOT_DELIVERED },
|
|
42
|
+
}),
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** A dependency failing right now. Must NOT be budgeted, or an outage permanently stops the poll. */
|
|
46
|
+
const outage = {
|
|
47
|
+
ok: false as const,
|
|
48
|
+
error: new SodaxError('LOOKUP_FAILED', 'relay down', { feature: 'swap' }),
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const KEY_A = 'arb:0xaaa';
|
|
52
|
+
const KEY_B = 'arb:0xbbb';
|
|
53
|
+
|
|
54
|
+
/** Drives the streak the way the hook does, one query update per call. */
|
|
55
|
+
const advance = (
|
|
56
|
+
state: typeof INITIAL_NOT_FOUND_STREAK,
|
|
57
|
+
reads: (ReturnType<typeof ok> | typeof notDelivered | typeof outage)[],
|
|
58
|
+
key = KEY_A,
|
|
59
|
+
from = 1,
|
|
60
|
+
) => reads.reduce((acc, read, i) => advanceNotFoundStreak(acc, key, toNotFoundBudgetRead(read), from + i), state);
|
|
61
|
+
|
|
62
|
+
describe('getDetailedStatusRefetchInterval', () => {
|
|
63
|
+
// Both terminal states of the `SubmitSwapTxStatusV2` wire contract. `'failed'` is unreachable via
|
|
64
|
+
// `getDetailedStatus` today (the SDK routes abandoned records to the solver) — asserted here as
|
|
65
|
+
// the hook's own contract, so a terminal record is never polled forever if that routing changes.
|
|
66
|
+
it.each(['solved', 'failed'])('stops on a backend record at the terminal status %s', status => {
|
|
67
|
+
expect(getDetailedStatusRefetchInterval(ok(backend(status)), 0)).toBe(false);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it.each([
|
|
71
|
+
'pending',
|
|
72
|
+
'relaying',
|
|
73
|
+
'relayed',
|
|
74
|
+
'posting_execution',
|
|
75
|
+
'posted_execution',
|
|
76
|
+
])('keeps polling a backend record at %s', status => {
|
|
77
|
+
expect(getDetailedStatusRefetchInterval(ok(backend(status)), 0)).toBe(STATUS_POLL_MS);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// A backend record is never stopped by the solver's budget — different vocabulary.
|
|
81
|
+
it('keeps polling an in-flight backend record even at the cutoff', () => {
|
|
82
|
+
expect(getDetailedStatusRefetchInterval(ok(backend('relaying')), MAX_NOT_FOUND_POLLS)).toBe(STATUS_POLL_MS);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it.each([SolverIntentStatusCode.SOLVED, SolverIntentStatusCode.FAILED])('stops on solver code %s', status => {
|
|
86
|
+
expect(getDetailedStatusRefetchInterval(ok(solver(status)), 0)).toBe(false);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it.each([
|
|
90
|
+
SolverIntentStatusCode.NOT_STARTED_YET,
|
|
91
|
+
SolverIntentStatusCode.STARTED_NOT_FINISHED,
|
|
92
|
+
])('never stops in-flight solver code %s, even at a high count', status => {
|
|
93
|
+
expect(getDetailedStatusRefetchInterval(ok(solver(status)), 100)).toBe(STATUS_POLL_MS);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it('inherits the useStatus NOT_FOUND cutoff: polls below it, stops at it', () => {
|
|
97
|
+
const notFound = ok(solver(SolverIntentStatusCode.NOT_FOUND));
|
|
98
|
+
expect(getDetailedStatusRefetchInterval(notFound, MAX_NOT_FOUND_POLLS - 1)).toBe(STATUS_POLL_MS);
|
|
99
|
+
expect(getDetailedStatusRefetchInterval(notFound, MAX_NOT_FOUND_POLLS)).toBe(false);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('spends the budget on an undelivered relay packet, rather than polling it forever', () => {
|
|
103
|
+
expect(getDetailedStatusRefetchInterval(notDelivered, MAX_NOT_FOUND_POLLS - 1)).toBe(STATUS_POLL_MS);
|
|
104
|
+
expect(getDetailedStatusRefetchInterval(notDelivered, MAX_NOT_FOUND_POLLS)).toBe(false);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// An outage is recoverable and polling is how it recovers — budgeting it would strand the read.
|
|
108
|
+
it('never stops on a dependency outage, however long it lasts', () => {
|
|
109
|
+
expect(getDetailedStatusRefetchInterval(outage, MAX_NOT_FOUND_POLLS)).toBe(STATUS_POLL_MS);
|
|
110
|
+
expect(getDetailedStatusRefetchInterval(outage, 10_000)).toBe(STATUS_POLL_MS);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('keeps polling before the first read lands', () => {
|
|
114
|
+
expect(getDetailedStatusRefetchInterval(undefined, 0)).toBe(STATUS_POLL_MS);
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
describe('toNotFoundBudgetRead', () => {
|
|
119
|
+
it('passes the solver arm through, neutralises the backend arm, counts a failed read', () => {
|
|
120
|
+
expect(toNotFoundBudgetRead(ok(solver(SolverIntentStatusCode.STARTED_NOT_FINISHED)))).toEqual({
|
|
121
|
+
ok: true,
|
|
122
|
+
value: { status: SolverIntentStatusCode.STARTED_NOT_FINISHED },
|
|
123
|
+
});
|
|
124
|
+
expect(toNotFoundBudgetRead(ok(backend('relaying')))).toBeUndefined();
|
|
125
|
+
expect(toNotFoundBudgetRead(undefined)).toBeUndefined();
|
|
126
|
+
// Only the undelivered-packet miss is budgeted; an outage is not.
|
|
127
|
+
expect(toNotFoundBudgetRead(notDelivered)).toEqual({
|
|
128
|
+
ok: true,
|
|
129
|
+
value: { status: SolverIntentStatusCode.NOT_FOUND },
|
|
130
|
+
});
|
|
131
|
+
expect(toNotFoundBudgetRead(outage)).toBeUndefined();
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
describe('detailed-status budget', () => {
|
|
136
|
+
it('counts consecutive solver NOT_FOUND reads up to the cutoff, then stops', () => {
|
|
137
|
+
const notFound = ok(solver(SolverIntentStatusCode.NOT_FOUND));
|
|
138
|
+
const state = advance({ ...INITIAL_NOT_FOUND_STREAK }, Array(MAX_NOT_FOUND_POLLS).fill(notFound));
|
|
139
|
+
|
|
140
|
+
expect(state.consecutiveNotFound).toBe(MAX_NOT_FOUND_POLLS);
|
|
141
|
+
expect(getDetailedStatusRefetchInterval(notFound, state.consecutiveNotFound)).toBe(false);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
// The regression this guards: a swap whose relay packet never lands used to poll forever, because
|
|
145
|
+
// every LOOKUP_FAILED reset the budget it should have been spending.
|
|
146
|
+
it('counts consecutive undelivered reads up to the cutoff, then stops', () => {
|
|
147
|
+
const state = advance({ ...INITIAL_NOT_FOUND_STREAK }, Array(MAX_NOT_FOUND_POLLS).fill(notDelivered));
|
|
148
|
+
|
|
149
|
+
expect(state.consecutiveNotFound).toBe(MAX_NOT_FOUND_POLLS);
|
|
150
|
+
expect(getDetailedStatusRefetchInterval(notDelivered, state.consecutiveNotFound)).toBe(false);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
// The regression this guards: a 2-minute solver or relay outage used to exhaust the budget and
|
|
154
|
+
// stop the poll for good, turning recoverable downtime into a permanently stuck status.
|
|
155
|
+
it('never exhausts the budget on an outage, however long it runs', () => {
|
|
156
|
+
const state = advance({ ...INITIAL_NOT_FOUND_STREAK }, Array(MAX_NOT_FOUND_POLLS * 2).fill(outage));
|
|
157
|
+
|
|
158
|
+
expect(state.consecutiveNotFound).toBe(0);
|
|
159
|
+
expect(getDetailedStatusRefetchInterval(outage, state.consecutiveNotFound)).toBe(STATUS_POLL_MS);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('lets a transient failure be forgiven once a real status arrives', () => {
|
|
163
|
+
const state = advance({ ...INITIAL_NOT_FOUND_STREAK }, [
|
|
164
|
+
notDelivered,
|
|
165
|
+
notDelivered,
|
|
166
|
+
ok(solver(SolverIntentStatusCode.STARTED_NOT_FINISHED)),
|
|
167
|
+
]);
|
|
168
|
+
|
|
169
|
+
expect(state.consecutiveNotFound).toBe(0);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
// The backend answering mid-run is not an unresolved read, so the budget starts over.
|
|
173
|
+
it('resets the budget when a backend record answers after a NOT_FOUND run', () => {
|
|
174
|
+
const state = advance(
|
|
175
|
+
{ pollKey: KEY_A, seenUpdates: 39, consecutiveNotFound: 39 },
|
|
176
|
+
[ok(backend('relaying'))],
|
|
177
|
+
KEY_A,
|
|
178
|
+
40,
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
expect(state.consecutiveNotFound).toBe(0);
|
|
182
|
+
expect(getDetailedStatusRefetchInterval(ok(backend('relaying')), state.consecutiveNotFound)).toBe(STATUS_POLL_MS);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it('starts a fresh budget when the composite pollKey changes', () => {
|
|
186
|
+
const state = advance(
|
|
187
|
+
{ pollKey: KEY_A, seenUpdates: 39, consecutiveNotFound: 39 },
|
|
188
|
+
[ok(solver(SolverIntentStatusCode.NOT_FOUND))],
|
|
189
|
+
KEY_B,
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
expect(state.consecutiveNotFound).toBe(1);
|
|
193
|
+
expect(state.pollKey).toBe(KEY_B);
|
|
194
|
+
});
|
|
195
|
+
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { DetailedStatusError, DetailedSwapStatus, Result, SpokeChainKey } from '@sodax/sdk';
|
|
2
|
+
import { useRef } from 'react';
|
|
3
|
+
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
|
|
4
|
+
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
5
|
+
import type { ReadHookParams } from '../shared/types.js';
|
|
6
|
+
import {
|
|
7
|
+
advanceNotFoundStreak,
|
|
8
|
+
getDetailedStatusRefetchInterval,
|
|
9
|
+
INITIAL_NOT_FOUND_STREAK,
|
|
10
|
+
toNotFoundBudgetRead,
|
|
11
|
+
} from './getSwapStatusRefetchInterval.js';
|
|
12
|
+
|
|
13
|
+
export type UseDetailedStatusResult = Result<DetailedSwapStatus, DetailedStatusError> | undefined;
|
|
14
|
+
|
|
15
|
+
export type UseDetailedStatusParams = ReadHookParams<
|
|
16
|
+
UseDetailedStatusResult,
|
|
17
|
+
{ srcChainKey: SpokeChainKey | undefined; srcTxHash: string | undefined }
|
|
18
|
+
>;
|
|
19
|
+
|
|
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, and — like `useStatus` — after 40
|
|
29
|
+
* consecutive *ambiguous* reads: a solver `NOT_FOUND`, or a `LOOKUP_FAILED` whose relay has no
|
|
30
|
+
* 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
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export const useDetailedStatus = ({
|
|
42
|
+
params,
|
|
43
|
+
queryOptions,
|
|
44
|
+
}: UseDetailedStatusParams = {}): UseQueryResult<UseDetailedStatusResult> => {
|
|
45
|
+
const { sodax } = useSodaxContext();
|
|
46
|
+
const srcChainKey = params?.srcChainKey;
|
|
47
|
+
const srcTxHash = params?.srcTxHash;
|
|
48
|
+
// Composite identity: a new swap must start its own NOT_FOUND budget.
|
|
49
|
+
const pollKey = srcChainKey && srcTxHash ? `${srcChainKey}:${srcTxHash}` : undefined;
|
|
50
|
+
const notFoundStreakRef = useRef({ ...INITIAL_NOT_FOUND_STREAK });
|
|
51
|
+
|
|
52
|
+
return useQuery({
|
|
53
|
+
queryKey: ['swap', 'detailedStatus', srcChainKey, srcTxHash],
|
|
54
|
+
queryFn: async () => {
|
|
55
|
+
if (!srcChainKey || !srcTxHash) return undefined;
|
|
56
|
+
return sodax.swaps.getDetailedStatus({ srcChainKey, srcTxHash });
|
|
57
|
+
},
|
|
58
|
+
enabled: !!srcChainKey && !!srcTxHash,
|
|
59
|
+
refetchInterval: query => {
|
|
60
|
+
notFoundStreakRef.current = advanceNotFoundStreak(
|
|
61
|
+
notFoundStreakRef.current,
|
|
62
|
+
pollKey,
|
|
63
|
+
toNotFoundBudgetRead(query.state.data),
|
|
64
|
+
query.state.dataUpdateCount,
|
|
65
|
+
);
|
|
66
|
+
return getDetailedStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
|
|
67
|
+
},
|
|
68
|
+
...queryOptions,
|
|
69
|
+
});
|
|
70
|
+
};
|
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import type { Hex, SolverErrorResponse, SolverIntentStatusResponse } from '@sodax/sdk';
|
|
2
2
|
import type { Result } from '@sodax/sdk';
|
|
3
|
+
import { useRef } from 'react';
|
|
3
4
|
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
|
|
4
5
|
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
5
6
|
import type { ReadHookParams } from '../shared/types.js';
|
|
7
|
+
import {
|
|
8
|
+
advanceNotFoundStreak,
|
|
9
|
+
getSwapStatusRefetchInterval,
|
|
10
|
+
INITIAL_NOT_FOUND_STREAK,
|
|
11
|
+
} from './getSwapStatusRefetchInterval.js';
|
|
6
12
|
|
|
7
13
|
export type UseStatusParams = ReadHookParams<
|
|
8
14
|
Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined,
|
|
@@ -12,6 +18,10 @@ export type UseStatusParams = ReadHookParams<
|
|
|
12
18
|
/**
|
|
13
19
|
* Hook for monitoring the status of an intent-based swap.
|
|
14
20
|
*
|
|
21
|
+
* Polls every 3s while the intent is in flight. Stops on `SOLVED` (3) or `FAILED` (4). Stops after
|
|
22
|
+
* 40 consecutive successful fetches while status stays `NOT_FOUND` (~2 min) — a forgotten intent
|
|
23
|
+
* never changes. An in-flight status resets that streak. Override with `queryOptions.refetchInterval`.
|
|
24
|
+
*
|
|
15
25
|
* @example
|
|
16
26
|
* ```typescript
|
|
17
27
|
* const { data: status, isLoading } = useStatus({ params: { intentTxHash } });
|
|
@@ -23,6 +33,7 @@ export const useStatus = ({
|
|
|
23
33
|
}: UseStatusParams = {}): UseQueryResult<Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined> => {
|
|
24
34
|
const { sodax } = useSodaxContext();
|
|
25
35
|
const intentTxHash = params?.intentTxHash;
|
|
36
|
+
const notFoundStreakRef = useRef({ ...INITIAL_NOT_FOUND_STREAK });
|
|
26
37
|
|
|
27
38
|
return useQuery({
|
|
28
39
|
queryKey: ['swap', 'status', intentTxHash],
|
|
@@ -31,7 +42,15 @@ export const useStatus = ({
|
|
|
31
42
|
return sodax.swaps.getStatus({ intent_tx_hash: intentTxHash });
|
|
32
43
|
},
|
|
33
44
|
enabled: !!intentTxHash,
|
|
34
|
-
refetchInterval:
|
|
45
|
+
refetchInterval: query => {
|
|
46
|
+
notFoundStreakRef.current = advanceNotFoundStreak(
|
|
47
|
+
notFoundStreakRef.current,
|
|
48
|
+
intentTxHash,
|
|
49
|
+
query.state.data,
|
|
50
|
+
query.state.dataUpdateCount,
|
|
51
|
+
);
|
|
52
|
+
return getSwapStatusRefetchInterval(query.state.data, notFoundStreakRef.current.consecutiveNotFound);
|
|
53
|
+
},
|
|
35
54
|
...queryOptions,
|
|
36
55
|
});
|
|
37
56
|
};
|