@sodax/dapp-kit 2.1.0-rc.6 → 2.1.0-rc.8
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 +91 -15
- package/dist/index.mjs +111 -37
- package/package.json +3 -3
- package/src/hooks/_mutationContract.test.ts +1 -0
- package/src/hooks/bridgeApi/index.ts +2 -1
- package/src/hooks/bridgeApi/useBridgeApiApprove.ts +7 -4
- package/src/hooks/bridgeApi/useBridgeApiApproveAndBroadcast.test.ts +267 -0
- package/src/hooks/bridgeApi/useBridgeApiApproveAndBroadcast.ts +76 -0
- package/src/hooks/swapsApi/useSwapsApiApproveAndBroadcast.test.ts +36 -0
- package/src/hooks/swapsApi/useSwapsApiApproveAndBroadcast.ts +16 -68
- package/src/utils/approvalPlan.ts +193 -0
- package/src/utils/index.ts +1 -0
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, 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';
|
|
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, RawTxReturnType, 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';
|
|
@@ -177,7 +177,7 @@ declare function getStellarTrustlineCheckQueryOptions({ sodax, token, amount, ch
|
|
|
177
177
|
chainId: SpokeChainKey | undefined;
|
|
178
178
|
walletAddress: string | undefined;
|
|
179
179
|
}): {
|
|
180
|
-
queryKey: readonly ["shared", "stellarTrustlineCheck", "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" | undefined, string | undefined, string | undefined, string | undefined];
|
|
180
|
+
queryKey: readonly ["shared", "stellarTrustlineCheck", "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" | "robinhood" | undefined, string | undefined, string | undefined, string | undefined];
|
|
181
181
|
queryFn: () => Promise<boolean>;
|
|
182
182
|
enabled: boolean;
|
|
183
183
|
};
|
|
@@ -387,7 +387,7 @@ type UseXBalancesParams = ReadHookParams<Record<string, bigint>, XBalancesInputs
|
|
|
387
387
|
* tests and for advanced callers that compose their own `useQuery` wrapper.
|
|
388
388
|
*/
|
|
389
389
|
declare function getXBalancesQueryOptions({ xService, xChainId, xTokens, address }: XBalancesInputs): {
|
|
390
|
-
queryKey: readonly ["shared", "xBalances", "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" | undefined, (readonly [string, string])[], string | undefined];
|
|
390
|
+
queryKey: readonly ["shared", "xBalances", "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" | "robinhood" | undefined, (readonly [string, string])[], string | undefined];
|
|
391
391
|
queryFn: () => Promise<Record<string, bigint>>;
|
|
392
392
|
enabled: boolean;
|
|
393
393
|
refetchInterval: number;
|
|
@@ -747,9 +747,9 @@ declare function getSwapQuoteQueryOptions({ sodax, payload, }: {
|
|
|
747
747
|
}): {
|
|
748
748
|
queryKey: (string | {
|
|
749
749
|
token_src: string;
|
|
750
|
-
token_src_blockchain_id: "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";
|
|
750
|
+
token_src_blockchain_id: "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" | "robinhood";
|
|
751
751
|
token_dst: string;
|
|
752
|
-
token_dst_blockchain_id: "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";
|
|
752
|
+
token_dst_blockchain_id: "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" | "robinhood";
|
|
753
753
|
amount: string;
|
|
754
754
|
quote_type: "exact_input";
|
|
755
755
|
partnerFee: _sodax_sdk.PartnerFeePercentage | {
|
|
@@ -1131,16 +1131,59 @@ type UseSwapsApiApproveVars = {
|
|
|
1131
1131
|
*/
|
|
1132
1132
|
declare const useSwapsApiApprove: ({ mutationOptions, }?: MutationHookParams<ApproveResponseV2, UseSwapsApiApproveVars>) => SafeUseMutationResult<ApproveResponseV2, Error, UseSwapsApiApproveVars>;
|
|
1133
1133
|
|
|
1134
|
-
/** Hashes of the transactions
|
|
1135
|
-
type
|
|
1134
|
+
/** Hashes of the transactions an approval plan broadcast, in the order they were sent. */
|
|
1135
|
+
type ApprovalHashes = {
|
|
1136
1136
|
/** Present only when the source token needed its stale allowance cleared first. */
|
|
1137
1137
|
readonly resetTxHash?: string;
|
|
1138
1138
|
readonly approveTxHash: string;
|
|
1139
1139
|
};
|
|
1140
|
+
/** The unsigned transactions a backend approve route hands back, in broadcast order. */
|
|
1141
|
+
type ApprovalPlan = {
|
|
1142
|
+
readonly tx: RawTxReturnType;
|
|
1143
|
+
readonly resetTx?: RawTxReturnType;
|
|
1144
|
+
};
|
|
1145
|
+
type ApprovalStepId = 'allowance-reset' | 'approve';
|
|
1146
|
+
type ApprovalPhase = 'signing' | 'broadcast' | 'confirmed' | 'failed';
|
|
1147
|
+
/** Where an approval has got to. A guarded token takes two transactions, every other token one. */
|
|
1148
|
+
type ApprovalProgress = {
|
|
1149
|
+
readonly step: ApprovalStepId;
|
|
1150
|
+
readonly phase: ApprovalPhase;
|
|
1151
|
+
/** 1-based position in `total`. */
|
|
1152
|
+
readonly index: number;
|
|
1153
|
+
readonly total: number;
|
|
1154
|
+
/** Present from `broadcast` onwards. */
|
|
1155
|
+
readonly hash?: string;
|
|
1156
|
+
/** Only on `failed`. */
|
|
1157
|
+
readonly error?: unknown;
|
|
1158
|
+
};
|
|
1159
|
+
type ApprovalProgressListener = (progress: ApprovalProgress) => void;
|
|
1160
|
+
/**
|
|
1161
|
+
* Broadcasts an approval plan in the only order that can work: `resetTx` mined first, then the
|
|
1162
|
+
* approve, which is not a valid state transition until the allowance has been zeroed on-chain.
|
|
1163
|
+
*
|
|
1164
|
+
* Not a pure helper like its neighbours here — it signs and sends through the caller's wallet
|
|
1165
|
+
* provider — but it is framework-free, and shared by the swaps and bridge approve-and-broadcast
|
|
1166
|
+
* hooks so the ordering is not re-derived per feature. `hookName` prefixes the errors.
|
|
1167
|
+
*
|
|
1168
|
+
* `onProgress` reports which transaction the user is being prompted for — `isPending` alone cannot
|
|
1169
|
+
* say whether a popup is the reset or the approve.
|
|
1170
|
+
*/
|
|
1171
|
+
declare function runApprovalPlan({ plan, srcChainKey, walletProvider, hookName, onProgress, }: {
|
|
1172
|
+
plan: ApprovalPlan;
|
|
1173
|
+
srcChainKey: SpokeChainKey;
|
|
1174
|
+
walletProvider: GetWalletProviderType<SpokeChainKey>;
|
|
1175
|
+
hookName: string;
|
|
1176
|
+
onProgress?: ApprovalProgressListener;
|
|
1177
|
+
}): Promise<ApprovalHashes>;
|
|
1178
|
+
|
|
1179
|
+
/** Hashes of the transactions this hook broadcast, in the order they were sent. */
|
|
1180
|
+
type SwapsApiApprovalHashes = ApprovalHashes;
|
|
1140
1181
|
type UseSwapsApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeChainKey> = {
|
|
1141
1182
|
body: CreateIntentParamsV2;
|
|
1142
1183
|
walletProvider: GetWalletProviderType<K>;
|
|
1143
1184
|
apiConfig?: RequestOverrideConfig;
|
|
1185
|
+
/** Per-step progress. In the vars, not the hook options, so it is never a stale closure. */
|
|
1186
|
+
onProgress?: ApprovalProgressListener;
|
|
1144
1187
|
};
|
|
1145
1188
|
/**
|
|
1146
1189
|
* React hook that runs the whole swaps-API approval: asks the API for the transactions, then signs,
|
|
@@ -1165,7 +1208,7 @@ type UseSwapsApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeChainKey>
|
|
|
1165
1208
|
* if (!result.ok) return;
|
|
1166
1209
|
* const { resetTxHash, approveTxHash } = result.value; // resetTxHash only on a guarded token
|
|
1167
1210
|
*/
|
|
1168
|
-
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>>;
|
|
1211
|
+
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" | "robinhood">({ mutationOptions, }?: MutationHookParams<SwapsApiApprovalHashes, UseSwapsApiApproveAndBroadcastVars<K>>) => SafeUseMutationResult<SwapsApiApprovalHashes, Error, UseSwapsApiApproveAndBroadcastVars<K>>;
|
|
1169
1212
|
|
|
1170
1213
|
/**
|
|
1171
1214
|
* Mutation variables for {@link useSwapsApiCreateIntent}. The per-request `apiConfig` override
|
|
@@ -1500,16 +1543,49 @@ type UseBridgeApiApproveVars = {
|
|
|
1500
1543
|
apiConfig?: RequestOverrideConfig;
|
|
1501
1544
|
};
|
|
1502
1545
|
/**
|
|
1503
|
-
* React hook to build
|
|
1504
|
-
* API — `sodax.api.bridge.approve`. Returns `{ tx }` (chain-specific unsigned
|
|
1505
|
-
* broadcast yourself; it does not change state, so no queries are invalidated.
|
|
1546
|
+
* React hook to build the unsigned token-approval transaction(s) for the source token via the bridge
|
|
1547
|
+
* API — `sodax.api.bridge.approve`. Returns `{ tx, resetTx? }` (chain-specific unsigned txs) to sign
|
|
1548
|
+
* and broadcast yourself; it does not change state, so no queries are invalidated.
|
|
1549
|
+
*
|
|
1550
|
+
* `resetTx`, when present, must be MINED before `tx` is a valid state transition. Prefer
|
|
1551
|
+
* {@link useBridgeApiApproveAndBroadcast}, which owns that ordering and invalidates the allowance query.
|
|
1506
1552
|
*
|
|
1507
1553
|
* @example
|
|
1508
1554
|
* const { mutateAsync: approve } = useBridgeApiApprove();
|
|
1509
|
-
* const { tx } = await approve({ body: createBridgeIntentParams });
|
|
1555
|
+
* const { tx, resetTx } = await approve({ body: createBridgeIntentParams });
|
|
1510
1556
|
*/
|
|
1511
1557
|
declare const useBridgeApiApprove: ({ mutationOptions, }?: MutationHookParams<BridgeApproveResponseV2, UseBridgeApiApproveVars>) => SafeUseMutationResult<BridgeApproveResponseV2, Error, UseBridgeApiApproveVars>;
|
|
1512
1558
|
|
|
1559
|
+
type BridgeApiApprovalHashes = ApprovalHashes;
|
|
1560
|
+
type UseBridgeApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeChainKey> = {
|
|
1561
|
+
body: CreateBridgeIntentParamsV2;
|
|
1562
|
+
walletProvider: GetWalletProviderType<K>;
|
|
1563
|
+
apiConfig?: RequestOverrideConfig;
|
|
1564
|
+
/** Per-step progress. In the vars, not the hook options, so it is never a stale closure. */
|
|
1565
|
+
onProgress?: ApprovalProgressListener;
|
|
1566
|
+
};
|
|
1567
|
+
/**
|
|
1568
|
+
* React hook that runs the whole bridge-API approval: asks the API for the transactions, then signs,
|
|
1569
|
+
* broadcasts, and waits for each one.
|
|
1570
|
+
*
|
|
1571
|
+
* Prefer this over {@link useBridgeApiApprove}, which hands back the unsigned `{ tx, resetTx? }` and
|
|
1572
|
+
* leaves the ordering — reset mined first, then approve — to the caller. Confirmation happens inside
|
|
1573
|
+
* the hook, so it invalidates `['bridgeApi','allowance']` itself.
|
|
1574
|
+
*
|
|
1575
|
+
* Supports the chains the bridge API can approve on — the hub (Sonic), EVM spokes, and Stellar.
|
|
1576
|
+
* Every other chain reports its allowance as always sufficient, so approval never runs for it.
|
|
1577
|
+
*
|
|
1578
|
+
* `onProgress` reports each transaction as `{ step, phase, index, total }`, so the UI can name the
|
|
1579
|
+
* wallet prompt the user is looking at instead of one flat "Approving…" across two signatures.
|
|
1580
|
+
*
|
|
1581
|
+
* @example
|
|
1582
|
+
* const { mutateAsyncSafe: approve } = useBridgeApiApproveAndBroadcast();
|
|
1583
|
+
* const result = await approve({ body: createBridgeIntentParams, walletProvider, onProgress: setStep });
|
|
1584
|
+
* if (!result.ok) return;
|
|
1585
|
+
* const { resetTxHash, approveTxHash } = result.value; // resetTxHash only on a guarded token
|
|
1586
|
+
*/
|
|
1587
|
+
declare const useBridgeApiApproveAndBroadcast: <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" | "robinhood">({ mutationOptions, }?: MutationHookParams<BridgeApiApprovalHashes, UseBridgeApiApproveAndBroadcastVars<K>>) => SafeUseMutationResult<BridgeApiApprovalHashes, Error, UseBridgeApiApproveAndBroadcastVars<K>>;
|
|
1588
|
+
|
|
1513
1589
|
type UseBridgeApiBridgeableAmountParams = ReadHookParams<BridgeableAmountResponseV2 | undefined, {
|
|
1514
1590
|
body: BridgeQuoteRequestV2 | undefined;
|
|
1515
1591
|
apiConfig?: RequestOverrideConfig;
|
|
@@ -2391,9 +2467,9 @@ declare function getLeverageYieldQuoteQueryOptions({ sodax, payload, }: {
|
|
|
2391
2467
|
}): {
|
|
2392
2468
|
queryKey: (string | {
|
|
2393
2469
|
token_src: string;
|
|
2394
|
-
token_src_blockchain_id: "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";
|
|
2470
|
+
token_src_blockchain_id: "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" | "robinhood";
|
|
2395
2471
|
token_dst: string;
|
|
2396
|
-
token_dst_blockchain_id: "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";
|
|
2472
|
+
token_dst_blockchain_id: "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" | "robinhood";
|
|
2397
2473
|
amount: string;
|
|
2398
2474
|
quote_type: "exact_input";
|
|
2399
2475
|
partnerFee: _sodax_sdk.PartnerFeePercentage | {
|
|
@@ -2790,4 +2866,4 @@ interface NearStorageGateState {
|
|
|
2790
2866
|
*/
|
|
2791
2867
|
declare function resolveNearStorageGate(chainKey: SpokeChainKey, check: NearStorageCheckResult): NearStorageGateState;
|
|
2792
2868
|
|
|
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 };
|
|
2869
|
+
export { type ATokenData, type ApprovalHashes, type ApprovalPlan, type ApprovalProgress, type ApprovalProgressListener, type BackendPaginationParams, type BitcoinTradingSetup, type BridgeApiApprovalHashes, 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 UseBridgeApiApproveAndBroadcastVars, 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, runApprovalPlan, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useActivateStellarAccount, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOrderbook, useBackendUserIntents, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApiAllowance, useBridgeApiApprove, useBridgeApiApproveAndBroadcast, useBridgeApiBridgeableAmount, useBridgeApiCreateBridgeIntent, useBridgeApiFee, useBridgeApiIsBridgeable, useBridgeApiSubmitTx, useBridgeApiSubmitTxStatus, useBridgeApiTokens, useBridgeApiTokensByChain, useBridgeApprove, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDetailedStatus, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, 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,
|
|
1
|
+
import { isSodaxError, ChainKeys, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, RadfiApiError, normalizePsbtToBase64, ClService, SPONSOR_CONFIG_TTL_MS, Sodax, SolverIntentStatusCode, DETAILED_STATUS_NOT_DELIVERED, isApprovalSupportedChainKeyType, isHubChainKeyType, isEvmSpokeOnlyChainKeyType, isStellarChainKeyType } from '@sodax/sdk';
|
|
2
2
|
export * from '@sodax/sdk';
|
|
3
3
|
import { useMutation, useQuery, useQueryClient, useQueries, QueryClient, MutationCache } from '@tanstack/react-query';
|
|
4
4
|
import { createContext, useCallback, useContext, useRef, useState, useEffect, useMemo } from 'react';
|
|
@@ -1599,7 +1599,82 @@ var useSwapsApiApprove = ({
|
|
|
1599
1599
|
mutationFn: async ({ body, apiConfig }) => unwrapResult(await sodax.api.swaps.approve(body, apiConfig))
|
|
1600
1600
|
});
|
|
1601
1601
|
};
|
|
1602
|
+
var stepLabel = (step) => step === "allowance-reset" ? "allowance reset" : "approve";
|
|
1602
1603
|
var isRevertedEvmReceiptStatus = (status) => status === "reverted" || status === "0x0";
|
|
1604
|
+
function resolveChainSender(srcChainKey, walletProvider, hookName) {
|
|
1605
|
+
const fail = (message) => new Error(`[${hookName}] ${message}`);
|
|
1606
|
+
if (!isApprovalSupportedChainKeyType(srcChainKey)) {
|
|
1607
|
+
throw fail(
|
|
1608
|
+
`${srcChainKey} cannot be approved \u2014 SODAX approve routes support the hub (Sonic), EVM spokes, and Stellar.`
|
|
1609
|
+
);
|
|
1610
|
+
}
|
|
1611
|
+
if (isHubChainKeyType(srcChainKey) || isEvmSpokeOnlyChainKeyType(srcChainKey)) {
|
|
1612
|
+
const evm = walletProvider;
|
|
1613
|
+
return {
|
|
1614
|
+
send: (raw) => evm.sendTransaction(raw),
|
|
1615
|
+
confirm: async (hash, step) => {
|
|
1616
|
+
const receipt = await evm.waitForTransactionReceipt(hash);
|
|
1617
|
+
if (isRevertedEvmReceiptStatus(receipt.status)) {
|
|
1618
|
+
throw fail(`the ${stepLabel(step)} transaction ${hash} reverted on chain.`);
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
};
|
|
1622
|
+
}
|
|
1623
|
+
if (isStellarChainKeyType(srcChainKey)) {
|
|
1624
|
+
const stellar = walletProvider;
|
|
1625
|
+
if (!stellar.signAndSendTransaction) {
|
|
1626
|
+
throw fail("this Stellar wallet provider does not implement signAndSendTransaction.");
|
|
1627
|
+
}
|
|
1628
|
+
const signAndSend = stellar.signAndSendTransaction.bind(stellar);
|
|
1629
|
+
return {
|
|
1630
|
+
send: (raw) => signAndSend(raw),
|
|
1631
|
+
confirm: async (hash, step) => {
|
|
1632
|
+
const receipt = await stellar.waitForTransactionReceipt(hash);
|
|
1633
|
+
if (receipt.successful === false) {
|
|
1634
|
+
throw fail(`the ${stepLabel(step)} transaction ${hash} failed on chain.`);
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
};
|
|
1638
|
+
}
|
|
1639
|
+
throw fail(
|
|
1640
|
+
`${srcChainKey} cannot be approved \u2014 SODAX approve routes support the hub (Sonic), EVM spokes, and Stellar.`
|
|
1641
|
+
);
|
|
1642
|
+
}
|
|
1643
|
+
async function runApprovalPlan({
|
|
1644
|
+
plan,
|
|
1645
|
+
srcChainKey,
|
|
1646
|
+
walletProvider,
|
|
1647
|
+
hookName,
|
|
1648
|
+
onProgress
|
|
1649
|
+
}) {
|
|
1650
|
+
const sender = resolveChainSender(srcChainKey, walletProvider, hookName);
|
|
1651
|
+
const total = plan.resetTx === void 0 ? 1 : 2;
|
|
1652
|
+
const report = (step, phase, extra) => {
|
|
1653
|
+
try {
|
|
1654
|
+
onProgress?.({ step, phase, index: step === "approve" ? total : 1, total, ...extra });
|
|
1655
|
+
} catch {
|
|
1656
|
+
}
|
|
1657
|
+
};
|
|
1658
|
+
const sendAndWait = async (raw, step) => {
|
|
1659
|
+
let hash;
|
|
1660
|
+
report(step, "signing");
|
|
1661
|
+
try {
|
|
1662
|
+
hash = await sender.send(raw);
|
|
1663
|
+
report(step, "broadcast", { hash });
|
|
1664
|
+
await sender.confirm(hash, step);
|
|
1665
|
+
} catch (error) {
|
|
1666
|
+
report(step, "failed", { hash, error });
|
|
1667
|
+
throw error;
|
|
1668
|
+
}
|
|
1669
|
+
report(step, "confirmed", { hash });
|
|
1670
|
+
return hash;
|
|
1671
|
+
};
|
|
1672
|
+
const resetTxHash = plan.resetTx === void 0 ? void 0 : await sendAndWait(plan.resetTx, "allowance-reset");
|
|
1673
|
+
const approveTxHash = await sendAndWait(plan.tx, "approve");
|
|
1674
|
+
return resetTxHash === void 0 ? { approveTxHash } : { resetTxHash, approveTxHash };
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
// src/hooks/swapsApi/useSwapsApiApproveAndBroadcast.ts
|
|
1603
1678
|
var useSwapsApiApproveAndBroadcast = ({
|
|
1604
1679
|
mutationOptions
|
|
1605
1680
|
} = {}) => {
|
|
@@ -1608,43 +1683,18 @@ var useSwapsApiApproveAndBroadcast = ({
|
|
|
1608
1683
|
return useSafeMutation({
|
|
1609
1684
|
mutationKey: ["swapsApi", "approveAndBroadcast"],
|
|
1610
1685
|
...mutationOptions,
|
|
1611
|
-
mutationFn: async ({ body, walletProvider, apiConfig }) => {
|
|
1612
|
-
const
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
throw new Error(`[useSwapsApiApproveAndBroadcast] the ${step} transaction ${hash} reverted on chain.`);
|
|
1621
|
-
}
|
|
1622
|
-
return hash;
|
|
1623
|
-
}
|
|
1624
|
-
if (isStellarChainKeyType(srcChainKey)) {
|
|
1625
|
-
const stellar = walletProvider;
|
|
1626
|
-
if (!stellar.signAndSendTransaction) {
|
|
1627
|
-
throw new Error(
|
|
1628
|
-
"[useSwapsApiApproveAndBroadcast] this Stellar wallet provider does not implement signAndSendTransaction."
|
|
1629
|
-
);
|
|
1630
|
-
}
|
|
1631
|
-
const hash = await stellar.signAndSendTransaction(raw);
|
|
1632
|
-
const receipt = await stellar.waitForTransactionReceipt(hash);
|
|
1633
|
-
if (receipt.successful === false) {
|
|
1634
|
-
throw new Error(`[useSwapsApiApproveAndBroadcast] the ${step} transaction ${hash} failed on chain.`);
|
|
1635
|
-
}
|
|
1636
|
-
return hash;
|
|
1637
|
-
}
|
|
1638
|
-
throw new Error(
|
|
1639
|
-
`[useSwapsApiApproveAndBroadcast] ${srcChainKey} cannot be approved \u2014 the swaps API supports the hub (Sonic), EVM spokes, and Stellar.`
|
|
1640
|
-
);
|
|
1641
|
-
};
|
|
1642
|
-
const resetTxHash = resetTx === void 0 ? void 0 : await sendAndWait(resetTx, "allowance reset");
|
|
1643
|
-
const approveTxHash = await sendAndWait(tx, "approve");
|
|
1644
|
-
return resetTxHash === void 0 ? { approveTxHash } : { resetTxHash, approveTxHash };
|
|
1686
|
+
mutationFn: async ({ body, walletProvider, apiConfig, onProgress }) => {
|
|
1687
|
+
const plan = unwrapResult(await sodax.api.swaps.approve(body, apiConfig));
|
|
1688
|
+
return runApprovalPlan({
|
|
1689
|
+
plan,
|
|
1690
|
+
srcChainKey: body.srcChainKey,
|
|
1691
|
+
walletProvider,
|
|
1692
|
+
hookName: "useSwapsApiApproveAndBroadcast",
|
|
1693
|
+
onProgress
|
|
1694
|
+
});
|
|
1645
1695
|
},
|
|
1646
1696
|
onSuccess: async (data, vars, ctx) => {
|
|
1647
|
-
queryClient.invalidateQueries({ queryKey: ["swapsApi", "allowance"] });
|
|
1697
|
+
await queryClient.invalidateQueries({ queryKey: ["swapsApi", "allowance"] });
|
|
1648
1698
|
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
1649
1699
|
}
|
|
1650
1700
|
});
|
|
@@ -2050,6 +2100,30 @@ var useBridgeApiApprove = ({
|
|
|
2050
2100
|
mutationFn: async ({ body, apiConfig }) => unwrapResult(await sodax.api.bridge.approve(body, apiConfig))
|
|
2051
2101
|
});
|
|
2052
2102
|
};
|
|
2103
|
+
var useBridgeApiApproveAndBroadcast = ({
|
|
2104
|
+
mutationOptions
|
|
2105
|
+
} = {}) => {
|
|
2106
|
+
const { sodax } = useSodaxContext();
|
|
2107
|
+
const queryClient = useQueryClient();
|
|
2108
|
+
return useSafeMutation({
|
|
2109
|
+
mutationKey: ["bridgeApi", "approveAndBroadcast"],
|
|
2110
|
+
...mutationOptions,
|
|
2111
|
+
mutationFn: async ({ body, walletProvider, apiConfig, onProgress }) => {
|
|
2112
|
+
const plan = unwrapResult(await sodax.api.bridge.approve(body, apiConfig));
|
|
2113
|
+
return runApprovalPlan({
|
|
2114
|
+
plan,
|
|
2115
|
+
srcChainKey: body.srcChainKey,
|
|
2116
|
+
walletProvider,
|
|
2117
|
+
hookName: "useBridgeApiApproveAndBroadcast",
|
|
2118
|
+
onProgress
|
|
2119
|
+
});
|
|
2120
|
+
},
|
|
2121
|
+
onSuccess: async (data, vars, ctx) => {
|
|
2122
|
+
await queryClient.invalidateQueries({ queryKey: ["bridgeApi", "allowance"] });
|
|
2123
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
2124
|
+
}
|
|
2125
|
+
});
|
|
2126
|
+
};
|
|
2053
2127
|
var useBridgeApiBridgeableAmount = ({
|
|
2054
2128
|
params,
|
|
2055
2129
|
queryOptions
|
|
@@ -3783,4 +3857,4 @@ function createSodaxQueryClient({
|
|
|
3783
3857
|
});
|
|
3784
3858
|
}
|
|
3785
3859
|
|
|
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 };
|
|
3860
|
+
export { SodaxProvider, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getLeverageYieldQuoteQueryOptions, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, getSwapQuoteQueryOptions, getXBalancesQueryOptions, isTerminalSwapIntentStatus, isUserRejectedError, loadRadfiSession, resolveNearStorageGate, resolveStellarGate, runApprovalPlan, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useActivateStellarAccount, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOrderbook, useBackendUserIntents, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApiAllowance, useBridgeApiApprove, useBridgeApiApproveAndBroadcast, useBridgeApiBridgeableAmount, useBridgeApiCreateBridgeIntent, useBridgeApiFee, useBridgeApiIsBridgeable, useBridgeApiSubmitTx, useBridgeApiSubmitTxStatus, useBridgeApiTokens, useBridgeApiTokensByChain, useBridgeApprove, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDetailedStatus, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, 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.8",
|
|
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.8"
|
|
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": {
|
|
@@ -71,6 +71,7 @@ const HOOKS: Array<{ path: string; nativeThrow?: true }> = [
|
|
|
71
71
|
{ path: 'swapsApi/useSwapsApiSubmitIntent.ts' },
|
|
72
72
|
{ path: 'swapsApi/useSwapsApiSubmitTx.ts' },
|
|
73
73
|
{ path: 'bridgeApi/useBridgeApiApprove.ts' },
|
|
74
|
+
{ path: 'bridgeApi/useBridgeApiApproveAndBroadcast.ts' },
|
|
74
75
|
{ path: 'bridgeApi/useBridgeApiCreateBridgeIntent.ts' },
|
|
75
76
|
{ path: 'bridgeApi/useBridgeApiSubmitTx.ts' },
|
|
76
77
|
];
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// Distinct from the on-chain `bridge/` hooks (which call `sodax.bridge.*` directly).
|
|
3
3
|
|
|
4
4
|
export * from './useBridgeApiAllowance.js'; // query
|
|
5
|
-
export * from './useBridgeApiApprove.js'; // mutation
|
|
5
|
+
export * from './useBridgeApiApprove.js'; // mutation (unsigned txs only)
|
|
6
|
+
export * from './useBridgeApiApproveAndBroadcast.js'; // mutation (request → sign → broadcast → wait)
|
|
6
7
|
export * from './useBridgeApiBridgeableAmount.js'; // query (deposit capacity / withdrawal liquidity)
|
|
7
8
|
export * from './useBridgeApiCreateBridgeIntent.js'; // mutation
|
|
8
9
|
export * from './useBridgeApiFee.js'; // query (partner fee — per-request override or configured default)
|
|
@@ -15,13 +15,16 @@ export type UseBridgeApiApproveVars = {
|
|
|
15
15
|
};
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
|
-
* React hook to build
|
|
19
|
-
* API — `sodax.api.bridge.approve`. Returns `{ tx }` (chain-specific unsigned
|
|
20
|
-
* broadcast yourself; it does not change state, so no queries are invalidated.
|
|
18
|
+
* React hook to build the unsigned token-approval transaction(s) for the source token via the bridge
|
|
19
|
+
* API — `sodax.api.bridge.approve`. Returns `{ tx, resetTx? }` (chain-specific unsigned txs) to sign
|
|
20
|
+
* and broadcast yourself; it does not change state, so no queries are invalidated.
|
|
21
|
+
*
|
|
22
|
+
* `resetTx`, when present, must be MINED before `tx` is a valid state transition. Prefer
|
|
23
|
+
* {@link useBridgeApiApproveAndBroadcast}, which owns that ordering and invalidates the allowance query.
|
|
21
24
|
*
|
|
22
25
|
* @example
|
|
23
26
|
* const { mutateAsync: approve } = useBridgeApiApprove();
|
|
24
|
-
* const { tx } = await approve({ body: createBridgeIntentParams });
|
|
27
|
+
* const { tx, resetTx } = await approve({ body: createBridgeIntentParams });
|
|
25
28
|
*/
|
|
26
29
|
export const useBridgeApiApprove = ({
|
|
27
30
|
mutationOptions,
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bridge 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.
|
|
4
|
+
*
|
|
5
|
+
* Follows the package convention of testing hooks without a renderer: the React Query wrapper is
|
|
6
|
+
* mocked so `mutationFn` can be captured and driven directly.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { ChainKeys } from '@sodax/sdk';
|
|
10
|
+
import type { ApprovalProgress } from '../../utils/approvalPlan.js';
|
|
11
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
12
|
+
|
|
13
|
+
const approve = vi.fn();
|
|
14
|
+
const invalidateQueries = vi.fn();
|
|
15
|
+
|
|
16
|
+
// biome-ignore lint/suspicious/noExplicitAny: the captured mutation options are driven directly.
|
|
17
|
+
let captured: any;
|
|
18
|
+
|
|
19
|
+
vi.mock('../shared/useSodaxContext.js', () => ({
|
|
20
|
+
useSodaxContext: () => ({ sodax: { api: { bridge: { approve } } } }),
|
|
21
|
+
}));
|
|
22
|
+
vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
|
|
23
|
+
vi.mock('../shared/useSafeMutation.js', () => ({
|
|
24
|
+
// biome-ignore lint/suspicious/noExplicitAny: mirrors the real wrapper's opaque options bag.
|
|
25
|
+
useSafeMutation: (options: any) => {
|
|
26
|
+
captured = options;
|
|
27
|
+
return {};
|
|
28
|
+
},
|
|
29
|
+
}));
|
|
30
|
+
|
|
31
|
+
const { useBridgeApiApproveAndBroadcast } = await import('./useBridgeApiApproveAndBroadcast.js');
|
|
32
|
+
|
|
33
|
+
const RESET_TX = { from: '0x1', to: '0x2', value: 0n, data: '0xreset' };
|
|
34
|
+
const APPROVE_TX = { from: '0x1', to: '0x2', value: 0n, data: '0xapprove' };
|
|
35
|
+
const RESET_HASH = '0xreset-hash';
|
|
36
|
+
const APPROVE_HASH = '0xapprove-hash';
|
|
37
|
+
|
|
38
|
+
const body = (srcChainKey: string) => ({ srcChainKey, inputToken: '0xtoken', inputAmount: '1' });
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Records the interleaving of sends and waits so ordering can be asserted, not assumed.
|
|
42
|
+
* `onWait` either throws (the receipt never arrives) or returns the mined status.
|
|
43
|
+
*/
|
|
44
|
+
function evmProvider(calls: string[], onWait?: (hash: string) => string | void) {
|
|
45
|
+
return {
|
|
46
|
+
sendTransaction: vi.fn(async (tx: { data: string }) => {
|
|
47
|
+
calls.push(`send:${tx.data}`);
|
|
48
|
+
return tx.data === '0xreset' ? RESET_HASH : APPROVE_HASH;
|
|
49
|
+
}),
|
|
50
|
+
waitForTransactionReceipt: vi.fn(async (hash: string) => {
|
|
51
|
+
calls.push(`wait:${hash}`);
|
|
52
|
+
return { status: onWait?.(hash) ?? 'success' };
|
|
53
|
+
}),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const onEvent = (sink: ApprovalProgress[]) => (progress: ApprovalProgress) => {
|
|
58
|
+
sink.push(progress);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** Compact rendering, so a sequence can be asserted as one readable list. */
|
|
62
|
+
const trace = (p: ApprovalProgress): string => `${p.step}:${p.phase}:${p.index}/${p.total}`;
|
|
63
|
+
|
|
64
|
+
/** One render, then the captured `mutationFn` invoked with `vars`. */
|
|
65
|
+
// biome-ignore lint/suspicious/noExplicitAny: vars mirror the hook's generic mutation variables.
|
|
66
|
+
const run = (vars: any) => {
|
|
67
|
+
useBridgeApiApproveAndBroadcast();
|
|
68
|
+
return captured.mutationFn(vars);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
beforeEach(() => {
|
|
72
|
+
vi.clearAllMocks();
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
describe('useBridgeApiApproveAndBroadcast', () => {
|
|
76
|
+
it('broadcasts the reset, waits for it, then approves — and reports both hashes', async () => {
|
|
77
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
|
|
78
|
+
const calls: string[] = [];
|
|
79
|
+
const walletProvider = evmProvider(calls);
|
|
80
|
+
|
|
81
|
+
const result = await run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider });
|
|
82
|
+
|
|
83
|
+
expect(result).toEqual({ resetTxHash: RESET_HASH, approveTxHash: APPROVE_HASH });
|
|
84
|
+
// The wait has to sit between the two sends; approving over an unconfirmed reset reverts.
|
|
85
|
+
expect(calls).toEqual(['send:0xreset', `wait:${RESET_HASH}`, 'send:0xapprove', `wait:${APPROVE_HASH}`]);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('never sends the approve when the reset is mined but reverts', async () => {
|
|
89
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
|
|
90
|
+
const calls: string[] = [];
|
|
91
|
+
const walletProvider = evmProvider(calls, hash => (hash === RESET_HASH ? 'reverted' : 'success'));
|
|
92
|
+
|
|
93
|
+
await expect(run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider })).rejects.toThrow(
|
|
94
|
+
/allowance reset transaction .* reverted on chain/,
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
// Mined is not succeeded: the allowance never moved, so the approve would revert too.
|
|
98
|
+
expect(walletProvider.sendTransaction).toHaveBeenCalledTimes(1);
|
|
99
|
+
expect(calls).toEqual(['send:0xreset', `wait:${RESET_HASH}`]);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('sends one transaction and omits resetTxHash for an ordinary token', async () => {
|
|
103
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
|
|
104
|
+
const calls: string[] = [];
|
|
105
|
+
const walletProvider = evmProvider(calls);
|
|
106
|
+
|
|
107
|
+
const result = await run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider });
|
|
108
|
+
|
|
109
|
+
expect(result).toEqual({ approveTxHash: APPROVE_HASH });
|
|
110
|
+
expect(calls).toEqual(['send:0xapprove', `wait:${APPROVE_HASH}`]);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('works on the hub chain, not just EVM spokes', async () => {
|
|
114
|
+
// Bridge approves the caller's own hub wallet router on Sonic — a different spender to swaps,
|
|
115
|
+
// but the same EVM broadcast path, so the hub must not fall through to the unsupported branch.
|
|
116
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
|
|
117
|
+
const calls: string[] = [];
|
|
118
|
+
|
|
119
|
+
const result = await run({ body: body(ChainKeys.SONIC_MAINNET), walletProvider: evmProvider(calls) });
|
|
120
|
+
|
|
121
|
+
expect(result).toEqual({ approveTxHash: APPROVE_HASH });
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('signs a Stellar trustline through signAndSendTransaction', async () => {
|
|
125
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
|
|
126
|
+
const walletProvider = {
|
|
127
|
+
signAndSendTransaction: vi.fn(async () => APPROVE_HASH),
|
|
128
|
+
waitForTransactionReceipt: vi.fn(async () => ({ successful: true })),
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const result = await run({ body: body(ChainKeys.STELLAR_MAINNET), walletProvider });
|
|
132
|
+
|
|
133
|
+
expect(result).toEqual({ approveTxHash: APPROVE_HASH });
|
|
134
|
+
expect(walletProvider.signAndSendTransaction).toHaveBeenCalledOnce();
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('reports a Stellar trustline that Horizon records as unsuccessful', async () => {
|
|
138
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
|
|
139
|
+
const walletProvider = {
|
|
140
|
+
signAndSendTransaction: vi.fn(async () => APPROVE_HASH),
|
|
141
|
+
waitForTransactionReceipt: vi.fn(async () => ({ successful: false })),
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
await expect(run({ body: body(ChainKeys.STELLAR_MAINNET), walletProvider })).rejects.toThrow(
|
|
145
|
+
/approve transaction .* failed on chain/,
|
|
146
|
+
);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('rejects a chain the bridge API cannot approve on', async () => {
|
|
150
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
|
|
151
|
+
|
|
152
|
+
await expect(run({ body: body(ChainKeys.SOLANA_MAINNET), walletProvider: {} })).rejects.toThrow(
|
|
153
|
+
/cannot be approved/,
|
|
154
|
+
);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('names this hook, not the swaps one, in an error from the shared plan runner', async () => {
|
|
158
|
+
// The runner is shared with useSwapsApiApproveAndBroadcast; a hard-coded prefix there would
|
|
159
|
+
// point a bridge integrator at the wrong hook.
|
|
160
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
|
|
161
|
+
|
|
162
|
+
await expect(run({ body: body(ChainKeys.SOLANA_MAINNET), walletProvider: {} })).rejects.toThrow(
|
|
163
|
+
/\[useBridgeApiApproveAndBroadcast\]/,
|
|
164
|
+
);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it('invalidates the bridge allowance query once the approval has confirmed', async () => {
|
|
168
|
+
useBridgeApiApproveAndBroadcast();
|
|
169
|
+
|
|
170
|
+
await captured.onSuccess({ approveTxHash: APPROVE_HASH }, {}, undefined);
|
|
171
|
+
|
|
172
|
+
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['bridgeApi', 'allowance'] });
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it('awaits the allowance refetch before resolving — a stale cache must not re-enable Approve', async () => {
|
|
176
|
+
useBridgeApiApproveAndBroadcast();
|
|
177
|
+
const order: string[] = [];
|
|
178
|
+
// A macrotask, not a microtask: any resolution that happens without awaiting invalidateQueries
|
|
179
|
+
// would land before this fires, so a regression here proves the mutation returned too early.
|
|
180
|
+
invalidateQueries.mockImplementationOnce(
|
|
181
|
+
() =>
|
|
182
|
+
new Promise<void>(resolve => {
|
|
183
|
+
setTimeout(() => {
|
|
184
|
+
order.push('invalidate:done');
|
|
185
|
+
resolve();
|
|
186
|
+
}, 0);
|
|
187
|
+
}),
|
|
188
|
+
);
|
|
189
|
+
|
|
190
|
+
await captured.onSuccess({ approveTxHash: APPROVE_HASH }, {}, undefined);
|
|
191
|
+
order.push('onSuccess:resolved');
|
|
192
|
+
|
|
193
|
+
expect(order).toEqual(['invalidate:done', 'onSuccess:resolved']);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
describe('onProgress', () => {
|
|
197
|
+
it('walks each transaction through its phases, numbered against the total', async () => {
|
|
198
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
|
|
199
|
+
const events: ApprovalProgress[] = [];
|
|
200
|
+
|
|
201
|
+
await run({
|
|
202
|
+
body: body(ChainKeys.ARBITRUM_MAINNET),
|
|
203
|
+
walletProvider: evmProvider([]),
|
|
204
|
+
onProgress: onEvent(events),
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
expect(events.map(trace)).toEqual([
|
|
208
|
+
'allowance-reset:signing:1/2',
|
|
209
|
+
'allowance-reset:broadcast:1/2',
|
|
210
|
+
'allowance-reset:confirmed:1/2',
|
|
211
|
+
'approve:signing:2/2',
|
|
212
|
+
'approve:broadcast:2/2',
|
|
213
|
+
'approve:confirmed:2/2',
|
|
214
|
+
]);
|
|
215
|
+
// The first report lands before the first wallet prompt, so "1/2" is on screen when it opens.
|
|
216
|
+
expect(events[0]?.phase).toBe('signing');
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it('carries the hash from broadcast onwards', async () => {
|
|
220
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
|
|
221
|
+
const events: ApprovalProgress[] = [];
|
|
222
|
+
|
|
223
|
+
await run({
|
|
224
|
+
body: body(ChainKeys.ARBITRUM_MAINNET),
|
|
225
|
+
walletProvider: evmProvider([]),
|
|
226
|
+
onProgress: onEvent(events),
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
expect(events.map(trace)).toEqual(['approve:signing:1/1', 'approve:broadcast:1/1', 'approve:confirmed:1/1']);
|
|
230
|
+
expect(events.map(e => e.hash)).toEqual([undefined, APPROVE_HASH, APPROVE_HASH]);
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
it('ends the failing step as failed, with its error, and reports nothing after it', async () => {
|
|
234
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
|
|
235
|
+
const events: ApprovalProgress[] = [];
|
|
236
|
+
const walletProvider = evmProvider([], hash => (hash === RESET_HASH ? 'reverted' : 'success'));
|
|
237
|
+
|
|
238
|
+
await expect(
|
|
239
|
+
run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider, onProgress: onEvent(events) }),
|
|
240
|
+
).rejects.toThrow(/reverted on chain/);
|
|
241
|
+
|
|
242
|
+
expect(events.map(trace)).toEqual([
|
|
243
|
+
'allowance-reset:signing:1/2',
|
|
244
|
+
'allowance-reset:broadcast:1/2',
|
|
245
|
+
'allowance-reset:failed:1/2',
|
|
246
|
+
]);
|
|
247
|
+
const failed = events.at(-1) as ApprovalProgress;
|
|
248
|
+
expect(failed.error).toBeInstanceOf(Error);
|
|
249
|
+
// Broadcast before it failed, so the hash is the one thing a user can still look up.
|
|
250
|
+
expect(failed.hash).toBe(RESET_HASH);
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
it('survives a listener that throws — reporting must never cost the user a transaction', async () => {
|
|
254
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
|
|
255
|
+
|
|
256
|
+
const result = await run({
|
|
257
|
+
body: body(ChainKeys.ARBITRUM_MAINNET),
|
|
258
|
+
walletProvider: evmProvider([]),
|
|
259
|
+
onProgress: () => {
|
|
260
|
+
throw new Error('UI bug');
|
|
261
|
+
},
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
expect(result).toEqual({ resetTxHash: RESET_HASH, approveTxHash: APPROVE_HASH });
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
});
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
BridgeApproveResponseV2,
|
|
3
|
+
CreateBridgeIntentParamsV2,
|
|
4
|
+
GetWalletProviderType,
|
|
5
|
+
RequestOverrideConfig,
|
|
6
|
+
SpokeChainKey,
|
|
7
|
+
} from '@sodax/sdk';
|
|
8
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
9
|
+
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
10
|
+
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
11
|
+
import type { MutationHookParams } from '../shared/types.js';
|
|
12
|
+
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
13
|
+
import { runApprovalPlan, type ApprovalHashes, type ApprovalProgressListener } from '../../utils/approvalPlan.js';
|
|
14
|
+
|
|
15
|
+
export type BridgeApiApprovalHashes = ApprovalHashes;
|
|
16
|
+
|
|
17
|
+
export type UseBridgeApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeChainKey> = {
|
|
18
|
+
body: CreateBridgeIntentParamsV2;
|
|
19
|
+
walletProvider: GetWalletProviderType<K>;
|
|
20
|
+
apiConfig?: RequestOverrideConfig;
|
|
21
|
+
/** Per-step progress. In the vars, not the hook options, so it is never a stale closure. */
|
|
22
|
+
onProgress?: ApprovalProgressListener;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* React hook that runs the whole bridge-API approval: asks the API for the transactions, then signs,
|
|
27
|
+
* broadcasts, and waits for each one.
|
|
28
|
+
*
|
|
29
|
+
* Prefer this over {@link useBridgeApiApprove}, which hands back the unsigned `{ tx, resetTx? }` and
|
|
30
|
+
* leaves the ordering — reset mined first, then approve — to the caller. Confirmation happens inside
|
|
31
|
+
* the hook, so it invalidates `['bridgeApi','allowance']` itself.
|
|
32
|
+
*
|
|
33
|
+
* Supports the chains the bridge API can approve on — the hub (Sonic), EVM spokes, and Stellar.
|
|
34
|
+
* Every other chain reports its allowance as always sufficient, so approval never runs for it.
|
|
35
|
+
*
|
|
36
|
+
* `onProgress` reports each transaction as `{ step, phase, index, total }`, so the UI can name the
|
|
37
|
+
* wallet prompt the user is looking at instead of one flat "Approving…" across two signatures.
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* const { mutateAsyncSafe: approve } = useBridgeApiApproveAndBroadcast();
|
|
41
|
+
* const result = await approve({ body: createBridgeIntentParams, walletProvider, onProgress: setStep });
|
|
42
|
+
* if (!result.ok) return;
|
|
43
|
+
* const { resetTxHash, approveTxHash } = result.value; // resetTxHash only on a guarded token
|
|
44
|
+
*/
|
|
45
|
+
export const useBridgeApiApproveAndBroadcast = <K extends SpokeChainKey = SpokeChainKey>({
|
|
46
|
+
mutationOptions,
|
|
47
|
+
}: MutationHookParams<BridgeApiApprovalHashes, UseBridgeApiApproveAndBroadcastVars<K>> = {}): SafeUseMutationResult<
|
|
48
|
+
BridgeApiApprovalHashes,
|
|
49
|
+
Error,
|
|
50
|
+
UseBridgeApiApproveAndBroadcastVars<K>
|
|
51
|
+
> => {
|
|
52
|
+
const { sodax } = useSodaxContext();
|
|
53
|
+
const queryClient = useQueryClient();
|
|
54
|
+
|
|
55
|
+
return useSafeMutation<BridgeApiApprovalHashes, Error, UseBridgeApiApproveAndBroadcastVars<K>>({
|
|
56
|
+
mutationKey: ['bridgeApi', 'approveAndBroadcast'],
|
|
57
|
+
...mutationOptions,
|
|
58
|
+
mutationFn: async ({ body, walletProvider, apiConfig, onProgress }): Promise<BridgeApiApprovalHashes> => {
|
|
59
|
+
const plan: BridgeApproveResponseV2 = unwrapResult(await sodax.api.bridge.approve(body, apiConfig));
|
|
60
|
+
|
|
61
|
+
return runApprovalPlan({
|
|
62
|
+
plan,
|
|
63
|
+
srcChainKey: body.srcChainKey as SpokeChainKey,
|
|
64
|
+
walletProvider,
|
|
65
|
+
hookName: 'useBridgeApiApproveAndBroadcast',
|
|
66
|
+
onProgress,
|
|
67
|
+
});
|
|
68
|
+
},
|
|
69
|
+
onSuccess: async (data, vars, ctx) => {
|
|
70
|
+
// Awaited: the mutation must not resolve — re-enabling Approve — before the allowance query
|
|
71
|
+
// has actually refetched, or a stale cached `valid: false` re-enables a duplicate approval.
|
|
72
|
+
await queryClient.invalidateQueries({ queryKey: ['bridgeApi', 'allowance'] });
|
|
73
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
};
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { ChainKeys } from '@sodax/sdk';
|
|
12
|
+
import type { ApprovalProgress } from '../../utils/approvalPlan.js';
|
|
12
13
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
13
14
|
|
|
14
15
|
const approve = vi.fn();
|
|
@@ -189,4 +190,39 @@ describe('useSwapsApiApproveAndBroadcast', () => {
|
|
|
189
190
|
// The hook owns confirmation now, so unlike useSwapsApiApprove it can refresh this itself.
|
|
190
191
|
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['swapsApi', 'allowance'] });
|
|
191
192
|
});
|
|
193
|
+
|
|
194
|
+
it('awaits the allowance refetch before resolving — a stale cache must not re-enable Approve', async () => {
|
|
195
|
+
useSwapsApiApproveAndBroadcast();
|
|
196
|
+
const order: string[] = [];
|
|
197
|
+
// A macrotask, not a microtask: any resolution that happens without awaiting invalidateQueries
|
|
198
|
+
// would land before this fires, so a regression here proves the mutation returned too early.
|
|
199
|
+
invalidateQueries.mockImplementationOnce(
|
|
200
|
+
() =>
|
|
201
|
+
new Promise<void>(resolve => {
|
|
202
|
+
setTimeout(() => {
|
|
203
|
+
order.push('invalidate:done');
|
|
204
|
+
resolve();
|
|
205
|
+
}, 0);
|
|
206
|
+
}),
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
await captured.onSuccess({ approveTxHash: APPROVE_HASH }, {}, undefined);
|
|
210
|
+
order.push('onSuccess:resolved');
|
|
211
|
+
|
|
212
|
+
expect(order).toEqual(['invalidate:done', 'onSuccess:resolved']);
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it('reports progress too — the runner is shared, so swaps must not be left without it', async () => {
|
|
216
|
+
approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
|
|
217
|
+
const events: ApprovalProgress[] = [];
|
|
218
|
+
|
|
219
|
+
await run({
|
|
220
|
+
body: body(ChainKeys.ARBITRUM_MAINNET),
|
|
221
|
+
walletProvider: evmProvider([]),
|
|
222
|
+
onProgress: (progress: ApprovalProgress) => events.push(progress),
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
expect(events).toHaveLength(6);
|
|
226
|
+
expect(events.at(-1)).toMatchObject({ step: 'approve', phase: 'confirmed', index: 2, total: 2 });
|
|
227
|
+
});
|
|
192
228
|
});
|
|
@@ -1,44 +1,26 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
ApproveResponseV2,
|
|
3
3
|
CreateIntentParamsV2,
|
|
4
|
-
EvmRawTransaction,
|
|
5
4
|
GetWalletProviderType,
|
|
6
|
-
Hex,
|
|
7
|
-
IEvmWalletProvider,
|
|
8
|
-
IStellarWalletProvider,
|
|
9
|
-
RawTxReturnType,
|
|
10
5
|
RequestOverrideConfig,
|
|
11
6
|
SpokeChainKey,
|
|
12
|
-
StellarRawTransaction,
|
|
13
7
|
} from '@sodax/sdk';
|
|
14
|
-
import { isEvmSpokeOnlyChainKeyType, isHubChainKeyType, isStellarChainKeyType } from '@sodax/sdk';
|
|
15
8
|
import { useQueryClient } from '@tanstack/react-query';
|
|
16
9
|
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
17
10
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
18
11
|
import type { MutationHookParams } from '../shared/types.js';
|
|
19
12
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
13
|
+
import { runApprovalPlan, type ApprovalHashes, type ApprovalProgressListener } from '../../utils/approvalPlan.js';
|
|
20
14
|
|
|
21
15
|
/** 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';
|
|
16
|
+
export type SwapsApiApprovalHashes = ApprovalHashes;
|
|
37
17
|
|
|
38
18
|
export type UseSwapsApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeChainKey> = {
|
|
39
19
|
body: CreateIntentParamsV2;
|
|
40
20
|
walletProvider: GetWalletProviderType<K>;
|
|
41
21
|
apiConfig?: RequestOverrideConfig;
|
|
22
|
+
/** Per-step progress. In the vars, not the hook options, so it is never a stale closure. */
|
|
23
|
+
onProgress?: ApprovalProgressListener;
|
|
42
24
|
};
|
|
43
25
|
|
|
44
26
|
/**
|
|
@@ -77,55 +59,21 @@ export const useSwapsApiApproveAndBroadcast = <K extends SpokeChainKey = SpokeCh
|
|
|
77
59
|
return useSafeMutation<SwapsApiApprovalHashes, Error, UseSwapsApiApproveAndBroadcastVars<K>>({
|
|
78
60
|
mutationKey: ['swapsApi', 'approveAndBroadcast'],
|
|
79
61
|
...mutationOptions,
|
|
80
|
-
mutationFn: async ({ body, walletProvider, apiConfig }): Promise<SwapsApiApprovalHashes> => {
|
|
81
|
-
const
|
|
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');
|
|
62
|
+
mutationFn: async ({ body, walletProvider, apiConfig, onProgress }): Promise<SwapsApiApprovalHashes> => {
|
|
63
|
+
const plan: ApproveResponseV2 = unwrapResult(await sodax.api.swaps.approve(body, apiConfig));
|
|
124
64
|
|
|
125
|
-
return
|
|
65
|
+
return runApprovalPlan({
|
|
66
|
+
plan,
|
|
67
|
+
srcChainKey: body.srcChainKey as SpokeChainKey,
|
|
68
|
+
walletProvider,
|
|
69
|
+
hookName: 'useSwapsApiApproveAndBroadcast',
|
|
70
|
+
onProgress,
|
|
71
|
+
});
|
|
126
72
|
},
|
|
127
73
|
onSuccess: async (data, vars, ctx) => {
|
|
128
|
-
|
|
74
|
+
// Awaited: the mutation must not resolve — re-enabling Approve — before the allowance query
|
|
75
|
+
// has actually refetched, or a stale cached `valid: false` re-enables a duplicate approval.
|
|
76
|
+
await queryClient.invalidateQueries({ queryKey: ['swapsApi', 'allowance'] });
|
|
129
77
|
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
130
78
|
},
|
|
131
79
|
});
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
EvmRawTransaction,
|
|
3
|
+
GetWalletProviderType,
|
|
4
|
+
Hex,
|
|
5
|
+
IEvmWalletProvider,
|
|
6
|
+
IStellarWalletProvider,
|
|
7
|
+
RawTxReturnType,
|
|
8
|
+
SpokeChainKey,
|
|
9
|
+
StellarRawTransaction,
|
|
10
|
+
} from '@sodax/sdk';
|
|
11
|
+
import {
|
|
12
|
+
isApprovalSupportedChainKeyType,
|
|
13
|
+
isEvmSpokeOnlyChainKeyType,
|
|
14
|
+
isHubChainKeyType,
|
|
15
|
+
isStellarChainKeyType,
|
|
16
|
+
} from '@sodax/sdk';
|
|
17
|
+
|
|
18
|
+
/** Hashes of the transactions an approval plan broadcast, in the order they were sent. */
|
|
19
|
+
export type ApprovalHashes = {
|
|
20
|
+
/** Present only when the source token needed its stale allowance cleared first. */
|
|
21
|
+
readonly resetTxHash?: string;
|
|
22
|
+
readonly approveTxHash: string;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** The unsigned transactions a backend approve route hands back, in broadcast order. */
|
|
26
|
+
export type ApprovalPlan = {
|
|
27
|
+
readonly tx: RawTxReturnType;
|
|
28
|
+
readonly resetTx?: RawTxReturnType;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
type ApprovalStepId = 'allowance-reset' | 'approve';
|
|
32
|
+
type ApprovalPhase = 'signing' | 'broadcast' | 'confirmed' | 'failed';
|
|
33
|
+
|
|
34
|
+
/** Where an approval has got to. A guarded token takes two transactions, every other token one. */
|
|
35
|
+
export type ApprovalProgress = {
|
|
36
|
+
readonly step: ApprovalStepId;
|
|
37
|
+
readonly phase: ApprovalPhase;
|
|
38
|
+
/** 1-based position in `total`. */
|
|
39
|
+
readonly index: number;
|
|
40
|
+
readonly total: number;
|
|
41
|
+
/** Present from `broadcast` onwards. */
|
|
42
|
+
readonly hash?: string;
|
|
43
|
+
/** Only on `failed`. */
|
|
44
|
+
readonly error?: unknown;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export type ApprovalProgressListener = (progress: ApprovalProgress) => void;
|
|
48
|
+
|
|
49
|
+
/** Sends one transaction and decides whether it landed, for one chain family. */
|
|
50
|
+
type ChainSender = {
|
|
51
|
+
send: (raw: RawTxReturnType) => Promise<string>;
|
|
52
|
+
/** Resolves once the transaction has landed successfully; throws when it did not. */
|
|
53
|
+
confirm: (hash: string, step: ApprovalStepId) => Promise<void>;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** Reads better than the id inside an error sentence. */
|
|
57
|
+
const stepLabel = (step: ApprovalStepId): string => (step === 'allowance-reset' ? 'allowance reset' : 'approve');
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* `EvmRawTransactionReceipt.status` is documented as the JSON-RPC hex flag, but `EvmWalletProvider`
|
|
61
|
+
* passes viem's `'reverted'` through unchanged, so both spellings reach here. A receipt without a
|
|
62
|
+
* status is pre-Byzantium and inconclusive — not a revert.
|
|
63
|
+
*/
|
|
64
|
+
const isRevertedEvmReceiptStatus = (status: string | undefined): boolean => status === 'reverted' || status === '0x0';
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* How to send and confirm on the chains a SODAX approve route can act on — the hub (Sonic), EVM
|
|
68
|
+
* spokes, and Stellar. Every other chain reports its allowance as always sufficient, so approval
|
|
69
|
+
* never runs for it.
|
|
70
|
+
*
|
|
71
|
+
* Resolved once, before anything is sent: an unsupported chain or a Stellar wallet that cannot sign
|
|
72
|
+
* then fails without first asking the user for a signature that could never be broadcast.
|
|
73
|
+
*/
|
|
74
|
+
function resolveChainSender(
|
|
75
|
+
srcChainKey: SpokeChainKey,
|
|
76
|
+
walletProvider: GetWalletProviderType<SpokeChainKey>,
|
|
77
|
+
hookName: string,
|
|
78
|
+
): ChainSender {
|
|
79
|
+
const fail = (message: string): Error => new Error(`[${hookName}] ${message}`);
|
|
80
|
+
|
|
81
|
+
// Single SDK-exported source for "which chains support approval" — the same partition
|
|
82
|
+
// SpokeService's approve-params guards resolve to, so a chain added there isn't silently
|
|
83
|
+
// missed here too.
|
|
84
|
+
if (!isApprovalSupportedChainKeyType(srcChainKey)) {
|
|
85
|
+
throw fail(
|
|
86
|
+
`${srcChainKey} cannot be approved — SODAX approve routes support the hub (Sonic), EVM spokes, and Stellar.`,
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (isHubChainKeyType(srcChainKey) || isEvmSpokeOnlyChainKeyType(srcChainKey)) {
|
|
91
|
+
const evm = walletProvider as IEvmWalletProvider;
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
send: raw => evm.sendTransaction(raw as EvmRawTransaction),
|
|
95
|
+
confirm: async (hash, step) => {
|
|
96
|
+
const receipt = await evm.waitForTransactionReceipt(hash as Hex);
|
|
97
|
+
// Mined is not succeeded: a revert here would let the approve go out over an unmoved allowance.
|
|
98
|
+
if (isRevertedEvmReceiptStatus(receipt.status)) {
|
|
99
|
+
throw fail(`the ${stepLabel(step)} transaction ${hash} reverted on chain.`);
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (isStellarChainKeyType(srcChainKey)) {
|
|
106
|
+
const stellar = walletProvider as IStellarWalletProvider;
|
|
107
|
+
// Optional on the interface — not every Stellar wallet implements it.
|
|
108
|
+
if (!stellar.signAndSendTransaction) {
|
|
109
|
+
throw fail('this Stellar wallet provider does not implement signAndSendTransaction.');
|
|
110
|
+
}
|
|
111
|
+
const signAndSend = stellar.signAndSendTransaction.bind(stellar);
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
send: raw => signAndSend(raw as StellarRawTransaction),
|
|
115
|
+
confirm: async (hash, step) => {
|
|
116
|
+
const receipt = await stellar.waitForTransactionReceipt(hash);
|
|
117
|
+
if (receipt.successful === false) {
|
|
118
|
+
throw fail(`the ${stepLabel(step)} transaction ${hash} failed on chain.`);
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Unreachable: isApprovalSupportedChainKeyType above already confirmed srcChainKey is hub, EVM-spoke,
|
|
125
|
+
// or Stellar, and the two branches above cover all three — kept only to satisfy TypeScript's
|
|
126
|
+
// return-path check (the guard is a plain boolean, so it doesn't narrow srcChainKey's type here).
|
|
127
|
+
throw fail(
|
|
128
|
+
`${srcChainKey} cannot be approved — SODAX approve routes support the hub (Sonic), EVM spokes, and Stellar.`,
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Broadcasts an approval plan in the only order that can work: `resetTx` mined first, then the
|
|
134
|
+
* approve, which is not a valid state transition until the allowance has been zeroed on-chain.
|
|
135
|
+
*
|
|
136
|
+
* Not a pure helper like its neighbours here — it signs and sends through the caller's wallet
|
|
137
|
+
* provider — but it is framework-free, and shared by the swaps and bridge approve-and-broadcast
|
|
138
|
+
* hooks so the ordering is not re-derived per feature. `hookName` prefixes the errors.
|
|
139
|
+
*
|
|
140
|
+
* `onProgress` reports which transaction the user is being prompted for — `isPending` alone cannot
|
|
141
|
+
* say whether a popup is the reset or the approve.
|
|
142
|
+
*/
|
|
143
|
+
export async function runApprovalPlan({
|
|
144
|
+
plan,
|
|
145
|
+
srcChainKey,
|
|
146
|
+
walletProvider,
|
|
147
|
+
hookName,
|
|
148
|
+
onProgress,
|
|
149
|
+
}: {
|
|
150
|
+
plan: ApprovalPlan;
|
|
151
|
+
srcChainKey: SpokeChainKey;
|
|
152
|
+
walletProvider: GetWalletProviderType<SpokeChainKey>;
|
|
153
|
+
hookName: string;
|
|
154
|
+
onProgress?: ApprovalProgressListener;
|
|
155
|
+
}): Promise<ApprovalHashes> {
|
|
156
|
+
const sender = resolveChainSender(srcChainKey, walletProvider, hookName);
|
|
157
|
+
const total = plan.resetTx === undefined ? 1 : 2;
|
|
158
|
+
|
|
159
|
+
// Advisory: a listener that throws must not abort a broadcast the user has already paid for.
|
|
160
|
+
const report = (step: ApprovalStepId, phase: ApprovalPhase, extra?: { hash?: string; error?: unknown }): void => {
|
|
161
|
+
try {
|
|
162
|
+
onProgress?.({ step, phase, index: step === 'approve' ? total : 1, total, ...extra });
|
|
163
|
+
} catch {
|
|
164
|
+
// ignored on purpose
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
// Sending and confirming are coupled deliberately: returning before confirmation would hand the
|
|
169
|
+
// ordering hazard back to the caller.
|
|
170
|
+
const sendAndWait = async (raw: RawTxReturnType, step: ApprovalStepId): Promise<string> => {
|
|
171
|
+
let hash: string | undefined;
|
|
172
|
+
report(step, 'signing');
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
hash = await sender.send(raw);
|
|
176
|
+
report(step, 'broadcast', { hash });
|
|
177
|
+
await sender.confirm(hash, step);
|
|
178
|
+
} catch (error) {
|
|
179
|
+
report(step, 'failed', { hash, error });
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
report(step, 'confirmed', { hash });
|
|
184
|
+
return hash;
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
// A throw aborts before the approve is sent: an unconfirmed reset leaves the allowance untouched,
|
|
188
|
+
// so a retry re-plans and costs a single transaction.
|
|
189
|
+
const resetTxHash = plan.resetTx === undefined ? undefined : await sendAndWait(plan.resetTx, 'allowance-reset');
|
|
190
|
+
const approveTxHash = await sendAndWait(plan.tx, 'approve');
|
|
191
|
+
|
|
192
|
+
return resetTxHash === undefined ? { approveTxHash } : { resetTxHash, approveTxHash };
|
|
193
|
+
}
|
package/src/utils/index.ts
CHANGED