@sodax/dapp-kit 2.1.0-rc.2 → 2.1.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1065,6 +1065,42 @@ type UseSwapsApiApproveVars = {
1065
1065
  */
1066
1066
  declare const useSwapsApiApprove: ({ mutationOptions, }?: MutationHookParams<ApproveResponseV2, UseSwapsApiApproveVars>) => SafeUseMutationResult<ApproveResponseV2, Error, UseSwapsApiApproveVars>;
1067
1067
 
1068
+ /** Hashes of the transactions this hook broadcast, in the order they were sent. */
1069
+ type SwapsApiApprovalHashes = {
1070
+ /** Present only when the source token needed its stale allowance cleared first. */
1071
+ readonly resetTxHash?: string;
1072
+ readonly approveTxHash: string;
1073
+ };
1074
+ type UseSwapsApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeChainKey> = {
1075
+ body: CreateIntentParamsV2;
1076
+ walletProvider: GetWalletProviderType<K>;
1077
+ apiConfig?: RequestOverrideConfig;
1078
+ };
1079
+ /**
1080
+ * React hook that runs the whole swaps-API approval: asks the API for the transactions, then signs,
1081
+ * broadcasts, and waits for each one.
1082
+ *
1083
+ * Prefer this over {@link useSwapsApiApprove}, which returns the unsigned `{ tx, resetTx? }` and
1084
+ * leaves the rest to you. A source token of the 2017 TetherToken lineage rejects an allowance change
1085
+ * from one non-zero value to another, so the API can hand back a **reset** transaction that must be
1086
+ * mined **before** the approve is even a valid state transition. Broadcasting them out of order, or
1087
+ * without waiting, spends the user's gas on a transaction that is certain to revert — and that is
1088
+ * ordering the package should own rather than every integration re-deriving it.
1089
+ *
1090
+ * Because confirmation now happens inside the hook, it can invalidate `['swapsApi','allowance']`
1091
+ * itself; callers of `useSwapsApiApprove` have to refetch by hand.
1092
+ *
1093
+ * Supports the chains the swaps API can approve on — the hub (Sonic), EVM spokes, and Stellar.
1094
+ * Every other chain reports its allowance as always sufficient, so approval never runs for it.
1095
+ *
1096
+ * @example
1097
+ * const { mutateAsyncSafe: approve } = useSwapsApiApproveAndBroadcast();
1098
+ * const result = await approve({ body: createIntentParams, walletProvider });
1099
+ * if (!result.ok) return;
1100
+ * const { resetTxHash, approveTxHash } = result.value; // resetTxHash only on a guarded token
1101
+ */
1102
+ declare const useSwapsApiApproveAndBroadcast: <K extends SpokeChainKey = "0xa86a.avax" | "0xa4b1.arbitrum" | "0x2105.base" | "0x38.bsc" | "injective-1" | "sonic" | "0x1.icon" | "sui" | "0xa.optimism" | "0x89.polygon" | "solana" | "stellar" | "hyper" | "lightlink" | "near" | "ethereum" | "bitcoin" | "redbelly" | "0x2019.kaia" | "stacks" | "hedera">({ mutationOptions, }?: MutationHookParams<SwapsApiApprovalHashes, UseSwapsApiApproveAndBroadcastVars<K>>) => SafeUseMutationResult<SwapsApiApprovalHashes, Error, UseSwapsApiApproveAndBroadcastVars<K>>;
1103
+
1068
1104
  /**
1069
1105
  * Mutation variables for {@link useSwapsApiCreateIntent}. The per-request `apiConfig` override
1070
1106
  * belongs here rather than at the hook level.
@@ -2616,4 +2652,4 @@ interface NearStorageGateState {
2616
2652
  */
2617
2653
  declare function resolveNearStorageGate(chainKey: SpokeChainKey, check: NearStorageCheckResult): NearStorageGateState;
2618
2654
 
2619
- 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 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 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 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, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, 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, 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, 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 };
2655
+ 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 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, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, 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, 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, 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 } 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';
@@ -1492,6 +1492,56 @@ var useSwapsApiApprove = ({
1492
1492
  mutationFn: async ({ body, apiConfig }) => unwrapResult(await sodax.api.swaps.approve(body, apiConfig))
1493
1493
  });
1494
1494
  };
1495
+ var isRevertedEvmReceiptStatus = (status) => status === "reverted" || status === "0x0";
1496
+ var useSwapsApiApproveAndBroadcast = ({
1497
+ mutationOptions
1498
+ } = {}) => {
1499
+ const { sodax } = useSodaxContext();
1500
+ const queryClient = useQueryClient();
1501
+ return useSafeMutation({
1502
+ mutationKey: ["swapsApi", "approveAndBroadcast"],
1503
+ ...mutationOptions,
1504
+ mutationFn: async ({ body, walletProvider, apiConfig }) => {
1505
+ const { tx, resetTx } = unwrapResult(await sodax.api.swaps.approve(body, apiConfig));
1506
+ const srcChainKey = body.srcChainKey;
1507
+ const sendAndWait = async (raw, step) => {
1508
+ if (isHubChainKeyType(srcChainKey) || isEvmSpokeOnlyChainKeyType(srcChainKey)) {
1509
+ const evm = walletProvider;
1510
+ const hash = await evm.sendTransaction(raw);
1511
+ const receipt = await evm.waitForTransactionReceipt(hash);
1512
+ if (isRevertedEvmReceiptStatus(receipt.status)) {
1513
+ throw new Error(`[useSwapsApiApproveAndBroadcast] the ${step} transaction ${hash} reverted on chain.`);
1514
+ }
1515
+ return hash;
1516
+ }
1517
+ if (isStellarChainKeyType(srcChainKey)) {
1518
+ const stellar = walletProvider;
1519
+ if (!stellar.signAndSendTransaction) {
1520
+ throw new Error(
1521
+ "[useSwapsApiApproveAndBroadcast] this Stellar wallet provider does not implement signAndSendTransaction."
1522
+ );
1523
+ }
1524
+ const hash = await stellar.signAndSendTransaction(raw);
1525
+ const receipt = await stellar.waitForTransactionReceipt(hash);
1526
+ if (receipt.successful === false) {
1527
+ throw new Error(`[useSwapsApiApproveAndBroadcast] the ${step} transaction ${hash} failed on chain.`);
1528
+ }
1529
+ return hash;
1530
+ }
1531
+ throw new Error(
1532
+ `[useSwapsApiApproveAndBroadcast] ${srcChainKey} cannot be approved \u2014 the swaps API supports the hub (Sonic), EVM spokes, and Stellar.`
1533
+ );
1534
+ };
1535
+ const resetTxHash = resetTx === void 0 ? void 0 : await sendAndWait(resetTx, "allowance reset");
1536
+ const approveTxHash = await sendAndWait(tx, "approve");
1537
+ return resetTxHash === void 0 ? { approveTxHash } : { resetTxHash, approveTxHash };
1538
+ },
1539
+ onSuccess: async (data, vars, ctx) => {
1540
+ queryClient.invalidateQueries({ queryKey: ["swapsApi", "allowance"] });
1541
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
1542
+ }
1543
+ });
1544
+ };
1495
1545
 
1496
1546
  // src/hooks/swapsApi/useSwapsApiCreateIntent.ts
1497
1547
  var useSwapsApiCreateIntent = ({
@@ -3585,4 +3635,4 @@ function createSodaxQueryClient({
3585
3635
  });
3586
3636
  }
3587
3637
 
3588
- export { SodaxProvider, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, 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, 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, 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 };
3638
+ export { SodaxProvider, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, 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, 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.2",
8
+ "version": "2.1.0-rc.3",
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.2"
37
+ "@sodax/sdk": "2.1.0-rc.3"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@arethetypeswrong/cli": "0.17.4",
@@ -64,6 +64,7 @@ const HOOKS: Array<{ path: string; nativeThrow?: true }> = [
64
64
  { path: 'swap/useSwap.ts' },
65
65
  { path: 'swap/useSwapApprove.ts' },
66
66
  { path: 'swapsApi/useSwapsApiApprove.ts' },
67
+ { path: 'swapsApi/useSwapsApiApproveAndBroadcast.ts' },
67
68
  { path: 'swapsApi/useSwapsApiCancelIntent.ts' },
68
69
  { path: 'swapsApi/useSwapsApiCreateIntent.ts' },
69
70
  { path: 'swapsApi/useSwapsApiCreateLimitOrder.ts' },
@@ -1,6 +1,6 @@
1
1
  # Backend API Hooks
2
2
 
3
- This directory contains React hooks for interacting with the Sodax Backend API through the `BackendApiService`. These hooks provide a React-friendly interface with automatic caching, error handling, and loading states using React Query.
3
+ This directory contains React hooks for interacting with the SODAX Backend API through the `BackendApiService`. These hooks provide a React-friendly interface with automatic caching, error handling, and loading states using React Query.
4
4
 
5
5
  ## Available Hooks
6
6
 
@@ -17,6 +17,7 @@ export * from './useSwapsApiDeadline.js';
17
17
  // Allowance · approve · create intent
18
18
  export * from './useSwapsApiAllowance.js';
19
19
  export * from './useSwapsApiApprove.js';
20
+ export * from './useSwapsApiApproveAndBroadcast.js';
20
21
  export * from './useSwapsApiCreateIntent.js';
21
22
 
22
23
  // Intent lifecycle: submit · status · cancel · hash · packet · extra-data · lookup
@@ -0,0 +1,192 @@
1
+ /**
2
+ * The swaps API can return two approval transactions, and the second is only a valid state
3
+ * transition once the first has been mined. That ordering is what this hook exists to own — before
4
+ * it, every integration re-implemented it and could drop the wait or the abort, which costs the user
5
+ * gas on a transaction certain to revert.
6
+ *
7
+ * Follows the package convention of testing hooks without a renderer: the React Query wrapper is
8
+ * mocked so `mutationFn` can be captured and driven directly.
9
+ */
10
+
11
+ import { ChainKeys } from '@sodax/sdk';
12
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
13
+
14
+ const approve = vi.fn();
15
+ const invalidateQueries = vi.fn();
16
+
17
+ // biome-ignore lint/suspicious/noExplicitAny: the captured mutation options are driven directly.
18
+ let captured: any;
19
+
20
+ vi.mock('../shared/useSodaxContext.js', () => ({
21
+ useSodaxContext: () => ({ sodax: { api: { swaps: { approve } } } }),
22
+ }));
23
+ vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
24
+ vi.mock('../shared/useSafeMutation.js', () => ({
25
+ // biome-ignore lint/suspicious/noExplicitAny: mirrors the real wrapper's opaque options bag.
26
+ useSafeMutation: (options: any) => {
27
+ captured = options;
28
+ return {};
29
+ },
30
+ }));
31
+
32
+ const { useSwapsApiApproveAndBroadcast } = await import('./useSwapsApiApproveAndBroadcast.js');
33
+
34
+ const RESET_TX = { from: '0x1', to: '0x2', value: 0n, data: '0xreset' };
35
+ const APPROVE_TX = { from: '0x1', to: '0x2', value: 0n, data: '0xapprove' };
36
+ const RESET_HASH = '0xreset-hash';
37
+ const APPROVE_HASH = '0xapprove-hash';
38
+
39
+ const body = (srcChainKey: string) => ({ srcChainKey, inputToken: '0xtoken', inputAmount: '1' });
40
+
41
+ /**
42
+ * Records the interleaving of sends and waits so ordering can be asserted, not assumed.
43
+ * `onWait` either throws (the receipt never arrives) or returns the mined status.
44
+ */
45
+ function evmProvider(calls: string[], onWait?: (hash: string) => string | void) {
46
+ return {
47
+ sendTransaction: vi.fn(async (tx: { data: string }) => {
48
+ calls.push(`send:${tx.data}`);
49
+ return tx.data === '0xreset' ? RESET_HASH : APPROVE_HASH;
50
+ }),
51
+ waitForTransactionReceipt: vi.fn(async (hash: string) => {
52
+ calls.push(`wait:${hash}`);
53
+ return { status: onWait?.(hash) ?? 'success' };
54
+ }),
55
+ };
56
+ }
57
+
58
+ /** One render, then the captured `mutationFn` invoked with `vars`. */
59
+ // biome-ignore lint/suspicious/noExplicitAny: vars mirror the hook's generic mutation variables.
60
+ const run = (vars: any) => {
61
+ useSwapsApiApproveAndBroadcast();
62
+ return captured.mutationFn(vars);
63
+ };
64
+
65
+ beforeEach(() => {
66
+ vi.clearAllMocks();
67
+ });
68
+
69
+ describe('useSwapsApiApproveAndBroadcast', () => {
70
+ it('broadcasts the reset, waits for it, then approves — and reports both hashes', async () => {
71
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
72
+ const calls: string[] = [];
73
+ const walletProvider = evmProvider(calls);
74
+
75
+ const result = await run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider });
76
+
77
+ expect(result).toEqual({ resetTxHash: RESET_HASH, approveTxHash: APPROVE_HASH });
78
+ // The wait has to sit between the two sends; approving over an unconfirmed reset reverts.
79
+ expect(calls).toEqual(['send:0xreset', `wait:${RESET_HASH}`, 'send:0xapprove', `wait:${APPROVE_HASH}`]);
80
+ });
81
+
82
+ it('never sends the approve when the reset fails to confirm', async () => {
83
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
84
+ const calls: string[] = [];
85
+ const walletProvider = evmProvider(calls, hash => {
86
+ if (hash === RESET_HASH) throw new Error('reset reverted');
87
+ });
88
+
89
+ await expect(run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider })).rejects.toThrow('reset reverted');
90
+
91
+ // A retry is cheap — the allowance is untouched, so the next plan is a single transaction.
92
+ expect(walletProvider.sendTransaction).toHaveBeenCalledTimes(1);
93
+ expect(calls).toEqual(['send:0xreset', `wait:${RESET_HASH}`]);
94
+ });
95
+
96
+ it('never sends the approve when the reset is mined but reverts', async () => {
97
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
98
+ const calls: string[] = [];
99
+ // A paused or blacklisted token mines the reset and reverts it; the allowance never moved, so
100
+ // the approve that follows is certain to revert too and would be paid for.
101
+ const walletProvider = evmProvider(calls, hash => (hash === RESET_HASH ? 'reverted' : 'success'));
102
+
103
+ await expect(run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider })).rejects.toThrow(
104
+ /allowance reset transaction .* reverted/,
105
+ );
106
+
107
+ expect(walletProvider.sendTransaction).toHaveBeenCalledTimes(1);
108
+ expect(calls).toEqual(['send:0xreset', `wait:${RESET_HASH}`]);
109
+ });
110
+
111
+ it('reports a reverted approve, whichever spelling of the status the provider returns', async () => {
112
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
113
+ // `EvmWalletProvider` forwards viem's `'reverted'`; a provider reading the JSON-RPC receipt
114
+ // directly returns `'0x0'`. Both mean the same thing.
115
+ const walletProvider = evmProvider([], () => '0x0');
116
+
117
+ await expect(run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider })).rejects.toThrow(
118
+ /approve transaction .* reverted/,
119
+ );
120
+ });
121
+
122
+ it('sends one transaction and omits resetTxHash for an ordinary token', async () => {
123
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
124
+ const calls: string[] = [];
125
+ const walletProvider = evmProvider(calls);
126
+
127
+ const result = await run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider });
128
+
129
+ expect(result).toEqual({ approveTxHash: APPROVE_HASH });
130
+ expect(walletProvider.sendTransaction).toHaveBeenCalledTimes(1);
131
+ });
132
+
133
+ it('works on the hub chain, not just EVM spokes', async () => {
134
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
135
+ const walletProvider = evmProvider([]);
136
+
137
+ const result = await run({ body: body(ChainKeys.SONIC_MAINNET), walletProvider });
138
+
139
+ expect(result).toEqual({ approveTxHash: APPROVE_HASH });
140
+ });
141
+
142
+ it('signs a Stellar trustline through signAndSendTransaction', async () => {
143
+ const trustlineTx = { unsignedTx: 'AAAA' };
144
+ approve.mockResolvedValue({ ok: true, value: { tx: trustlineTx } });
145
+ const walletProvider = {
146
+ signAndSendTransaction: vi.fn().mockResolvedValue('stellar-hash'),
147
+ waitForTransactionReceipt: vi.fn().mockResolvedValue({ successful: true }),
148
+ };
149
+
150
+ const result = await run({ body: body(ChainKeys.STELLAR_MAINNET), walletProvider });
151
+
152
+ expect(result).toEqual({ approveTxHash: 'stellar-hash' });
153
+ expect(walletProvider.signAndSendTransaction).toHaveBeenCalledWith(trustlineTx);
154
+ });
155
+
156
+ it('reports a Stellar trustline that Horizon records as unsuccessful', async () => {
157
+ approve.mockResolvedValue({ ok: true, value: { tx: { unsignedTx: 'AAAA' } } });
158
+ const walletProvider = {
159
+ signAndSendTransaction: vi.fn().mockResolvedValue('stellar-hash'),
160
+ waitForTransactionReceipt: vi.fn().mockResolvedValue({ successful: false }),
161
+ };
162
+
163
+ await expect(run({ body: body(ChainKeys.STELLAR_MAINNET), walletProvider })).rejects.toThrow(
164
+ /approve transaction .* failed on chain/,
165
+ );
166
+ });
167
+
168
+ it('names the missing capability when a Stellar wallet cannot sign', async () => {
169
+ approve.mockResolvedValue({ ok: true, value: { tx: { unsignedTx: 'AAAA' } } });
170
+
171
+ await expect(
172
+ run({ body: body(ChainKeys.STELLAR_MAINNET), walletProvider: { waitForTransactionReceipt: vi.fn() } }),
173
+ ).rejects.toThrow(/signAndSendTransaction/);
174
+ });
175
+
176
+ it('rejects a chain the swaps API cannot approve on', async () => {
177
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
178
+
179
+ await expect(run({ body: body(ChainKeys.SOLANA_MAINNET), walletProvider: {} })).rejects.toThrow(
180
+ /the hub \(Sonic\), EVM spokes, and Stellar/,
181
+ );
182
+ });
183
+
184
+ it('invalidates the allowance query once the approval has confirmed', async () => {
185
+ useSwapsApiApproveAndBroadcast();
186
+
187
+ await captured.onSuccess({ approveTxHash: APPROVE_HASH }, {}, undefined);
188
+
189
+ // The hook owns confirmation now, so unlike useSwapsApiApprove it can refresh this itself.
190
+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['swapsApi', 'allowance'] });
191
+ });
192
+ });
@@ -0,0 +1,132 @@
1
+ import type {
2
+ ApproveResponseV2,
3
+ CreateIntentParamsV2,
4
+ EvmRawTransaction,
5
+ GetWalletProviderType,
6
+ Hex,
7
+ IEvmWalletProvider,
8
+ IStellarWalletProvider,
9
+ RawTxReturnType,
10
+ RequestOverrideConfig,
11
+ SpokeChainKey,
12
+ StellarRawTransaction,
13
+ } from '@sodax/sdk';
14
+ import { isEvmSpokeOnlyChainKeyType, isHubChainKeyType, isStellarChainKeyType } from '@sodax/sdk';
15
+ import { useQueryClient } from '@tanstack/react-query';
16
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
17
+ import { unwrapResult } from '../shared/unwrapResult.js';
18
+ import type { MutationHookParams } from '../shared/types.js';
19
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
20
+
21
+ /** Hashes of the transactions this hook broadcast, in the order they were sent. */
22
+ export type SwapsApiApprovalHashes = {
23
+ /** Present only when the source token needed its stale allowance cleared first. */
24
+ readonly resetTxHash?: string;
25
+ readonly approveTxHash: string;
26
+ };
27
+
28
+ /** Names the transaction in an error, so a revert says which of the two steps failed. */
29
+ type ApprovalStep = 'allowance reset' | 'approve';
30
+
31
+ /**
32
+ * `EvmRawTransactionReceipt.status` is documented as the JSON-RPC hex flag, but `EvmWalletProvider`
33
+ * passes viem's `'reverted'` through unchanged, so both spellings reach this hook. A receipt without
34
+ * a status is pre-Byzantium and inconclusive — not a revert.
35
+ */
36
+ const isRevertedEvmReceiptStatus = (status: string | undefined): boolean => status === 'reverted' || status === '0x0';
37
+
38
+ export type UseSwapsApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeChainKey> = {
39
+ body: CreateIntentParamsV2;
40
+ walletProvider: GetWalletProviderType<K>;
41
+ apiConfig?: RequestOverrideConfig;
42
+ };
43
+
44
+ /**
45
+ * React hook that runs the whole swaps-API approval: asks the API for the transactions, then signs,
46
+ * broadcasts, and waits for each one.
47
+ *
48
+ * Prefer this over {@link useSwapsApiApprove}, which returns the unsigned `{ tx, resetTx? }` and
49
+ * leaves the rest to you. A source token of the 2017 TetherToken lineage rejects an allowance change
50
+ * from one non-zero value to another, so the API can hand back a **reset** transaction that must be
51
+ * mined **before** the approve is even a valid state transition. Broadcasting them out of order, or
52
+ * without waiting, spends the user's gas on a transaction that is certain to revert — and that is
53
+ * ordering the package should own rather than every integration re-deriving it.
54
+ *
55
+ * Because confirmation now happens inside the hook, it can invalidate `['swapsApi','allowance']`
56
+ * itself; callers of `useSwapsApiApprove` have to refetch by hand.
57
+ *
58
+ * Supports the chains the swaps API can approve on — the hub (Sonic), EVM spokes, and Stellar.
59
+ * Every other chain reports its allowance as always sufficient, so approval never runs for it.
60
+ *
61
+ * @example
62
+ * const { mutateAsyncSafe: approve } = useSwapsApiApproveAndBroadcast();
63
+ * const result = await approve({ body: createIntentParams, walletProvider });
64
+ * if (!result.ok) return;
65
+ * const { resetTxHash, approveTxHash } = result.value; // resetTxHash only on a guarded token
66
+ */
67
+ export const useSwapsApiApproveAndBroadcast = <K extends SpokeChainKey = SpokeChainKey>({
68
+ mutationOptions,
69
+ }: MutationHookParams<SwapsApiApprovalHashes, UseSwapsApiApproveAndBroadcastVars<K>> = {}): SafeUseMutationResult<
70
+ SwapsApiApprovalHashes,
71
+ Error,
72
+ UseSwapsApiApproveAndBroadcastVars<K>
73
+ > => {
74
+ const { sodax } = useSodaxContext();
75
+ const queryClient = useQueryClient();
76
+
77
+ return useSafeMutation<SwapsApiApprovalHashes, Error, UseSwapsApiApproveAndBroadcastVars<K>>({
78
+ mutationKey: ['swapsApi', 'approveAndBroadcast'],
79
+ ...mutationOptions,
80
+ mutationFn: async ({ body, walletProvider, apiConfig }): Promise<SwapsApiApprovalHashes> => {
81
+ const { tx, resetTx }: ApproveResponseV2 = unwrapResult(await sodax.api.swaps.approve(body, apiConfig));
82
+ const srcChainKey = body.srcChainKey as SpokeChainKey;
83
+
84
+ // Broadcast and wait as one step: the next transaction is only valid once this one has landed,
85
+ // so returning before confirmation would hand the caller back the same ordering hazard.
86
+ const sendAndWait = async (raw: RawTxReturnType, step: ApprovalStep): Promise<string> => {
87
+ if (isHubChainKeyType(srcChainKey) || isEvmSpokeOnlyChainKeyType(srcChainKey)) {
88
+ const evm = walletProvider as IEvmWalletProvider;
89
+ const hash = await evm.sendTransaction(raw as EvmRawTransaction);
90
+ const receipt = await evm.waitForTransactionReceipt(hash as Hex);
91
+ // Mined is not the same as succeeded: a paused or blacklisted token reverts on-chain, and
92
+ // waiting alone would let the next transaction go out over an allowance that never moved.
93
+ if (isRevertedEvmReceiptStatus(receipt.status)) {
94
+ throw new Error(`[useSwapsApiApproveAndBroadcast] the ${step} transaction ${hash} reverted on chain.`);
95
+ }
96
+ return hash;
97
+ }
98
+
99
+ if (isStellarChainKeyType(srcChainKey)) {
100
+ const stellar = walletProvider as IStellarWalletProvider;
101
+ // Optional on the interface — not every Stellar wallet implements it.
102
+ if (!stellar.signAndSendTransaction) {
103
+ throw new Error(
104
+ '[useSwapsApiApproveAndBroadcast] this Stellar wallet provider does not implement signAndSendTransaction.',
105
+ );
106
+ }
107
+ const hash = await stellar.signAndSendTransaction(raw as StellarRawTransaction);
108
+ const receipt = await stellar.waitForTransactionReceipt(hash);
109
+ if (receipt.successful === false) {
110
+ throw new Error(`[useSwapsApiApproveAndBroadcast] the ${step} transaction ${hash} failed on chain.`);
111
+ }
112
+ return hash;
113
+ }
114
+
115
+ throw new Error(
116
+ `[useSwapsApiApproveAndBroadcast] ${srcChainKey} cannot be approved — the swaps API supports the hub (Sonic), EVM spokes, and Stellar.`,
117
+ );
118
+ };
119
+
120
+ // A throw here aborts before the approve is sent, which is the point: an unconfirmed reset
121
+ // leaves the allowance untouched, so a retry re-plans and costs a single transaction.
122
+ const resetTxHash = resetTx === undefined ? undefined : await sendAndWait(resetTx, 'allowance reset');
123
+ const approveTxHash = await sendAndWait(tx, 'approve');
124
+
125
+ return resetTxHash === undefined ? { approveTxHash } : { resetTxHash, approveTxHash };
126
+ },
127
+ onSuccess: async (data, vars, ctx) => {
128
+ queryClient.invalidateQueries({ queryKey: ['swapsApi', 'allowance'] });
129
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
130
+ },
131
+ });
132
+ };