@sodax/dapp-kit 2.2.0-rc.8 → 2.3.0-rc.1
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/README.md +176 -166
- package/dist/index.d.ts +313 -30
- package/dist/index.mjs +392 -3
- package/package.json +5 -5
- package/src/hooks/_apiKeyWire.test.ts +10 -0
- package/src/hooks/_mutationContract.test.ts +4 -0
- package/src/hooks/bridge/index.ts +2 -0
- package/src/hooks/bridge/useBridgeApprovalStrategy.test.ts +75 -0
- package/src/hooks/bridge/useBridgeApprovalStrategy.ts +53 -0
- package/src/hooks/bridge/useBridgeWithApproval.test.ts +73 -0
- package/src/hooks/bridge/useBridgeWithApproval.ts +48 -0
- package/src/hooks/leverageYield/index.ts +2 -0
- package/src/hooks/leverageYield/useLeverageYieldApprovalStrategy.test.ts +82 -0
- package/src/hooks/leverageYield/useLeverageYieldApprovalStrategy.ts +55 -0
- package/src/hooks/leverageYield/useLeverageYieldVaultSwapWithApproval.test.ts +73 -0
- package/src/hooks/leverageYield/useLeverageYieldVaultSwapWithApproval.ts +48 -0
- package/src/hooks/shared/useNearStorageGate.ts +10 -4
- package/src/hooks/swap/index.ts +3 -0
- package/src/hooks/swap/useSwapApprovalStrategy.test.ts +92 -0
- package/src/hooks/swap/useSwapApprovalStrategy.ts +54 -0
- package/src/hooks/swap/useSwapLifecycle.test.ts +329 -0
- package/src/hooks/swap/useSwapLifecycle.ts +212 -0
- package/src/hooks/swap/useSwapWithApproval.test.ts +63 -0
- package/src/hooks/swap/useSwapWithApproval.ts +45 -0
- package/src/hooks/swapsApi/index.ts +1 -0
- package/src/hooks/swapsApi/useSwapsApiBroadcastWithApproval.test.ts +331 -0
- package/src/hooks/swapsApi/useSwapsApiBroadcastWithApproval.ts +183 -0
- package/src/utils/nearStorageGate.ts +4 -1
- package/src/utils/swapLifecycle.test.ts +292 -0
- package/src/utils/swapLifecycle.ts +183 -0
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { isSodaxError, isAuthFailure, ChainKeys, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, RadfiApiError, normalizePsbtToBase64, DETAILED_STATUS_NOT_DELIVERED, ClService, SPONSOR_CONFIG_TTL_MS, Sodax, SolverIntentStatusCode, isApprovalSupportedChainKeyType, isHubChainKeyType,
|
|
1
|
+
import { isSodaxError, isAuthFailure, ChainKeys, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, RadfiApiError, normalizePsbtToBase64, summarizeSwapStatus, isEvmChainKeyType, resolveApprovalStrategy, isEvmSpokeOnlyChainKeyType, sendApprovalBatch, DEFAULT_RELAY_TX_TIMEOUT, isAtomicBatchRefusal, SodaxError, ATOMIC_BATCH_REFUSED, getEvmViemChain, DETAILED_STATUS_NOT_DELIVERED, ClService, SPONSOR_CONFIG_TTL_MS, Sodax, SolverIntentStatusCode, isApprovalSupportedChainKeyType, isHubChainKeyType, isStellarChainKeyType, ATOMIC_BATCH_UNCONFIRMED } from '@sodax/sdk';
|
|
2
2
|
export * from '@sodax/sdk';
|
|
3
|
-
import { useMutation, useQuery, useQueryClient, useQueries, QueryClient, MutationCache } from '@tanstack/react-query';
|
|
3
|
+
import { useMutation, useQuery, useQueryClient, useIsFetching, useQueries, QueryClient, MutationCache } from '@tanstack/react-query';
|
|
4
4
|
import { createContext, useCallback, useContext, useRef, useState, useEffect, useMemo } from 'react';
|
|
5
5
|
import { isAddress, erc20Abi, parseUnits } from 'viem';
|
|
6
6
|
import { jsx } from 'react/jsx-runtime';
|
|
@@ -250,6 +250,8 @@ function useNearStorageGate({
|
|
|
250
250
|
needsRegistration,
|
|
251
251
|
blocksAction,
|
|
252
252
|
isChecking: storageCheck.isLoading,
|
|
253
|
+
checkFailed: isNear && storageCheck.isError && storageCheck.data === void 0,
|
|
254
|
+
retry: () => void storageCheck.refetch(),
|
|
253
255
|
isRegistering,
|
|
254
256
|
registerStorage
|
|
255
257
|
};
|
|
@@ -1314,6 +1316,227 @@ function useSwapApprove({
|
|
|
1314
1316
|
}
|
|
1315
1317
|
});
|
|
1316
1318
|
}
|
|
1319
|
+
function useSwapApprovalStrategy({
|
|
1320
|
+
params,
|
|
1321
|
+
queryOptions
|
|
1322
|
+
} = {}) {
|
|
1323
|
+
const { sodax } = useSodaxContext();
|
|
1324
|
+
const payload = params?.payload;
|
|
1325
|
+
const walletProvider = params?.walletProvider;
|
|
1326
|
+
const allowAccountUpgrade = params?.allowAccountUpgrade ?? true;
|
|
1327
|
+
return useQuery({
|
|
1328
|
+
queryKey: [
|
|
1329
|
+
"swap",
|
|
1330
|
+
"approvalStrategy",
|
|
1331
|
+
payload?.srcChainKey,
|
|
1332
|
+
payload?.srcAddress,
|
|
1333
|
+
payload?.inputToken,
|
|
1334
|
+
payload?.inputAmount.toString(),
|
|
1335
|
+
allowAccountUpgrade
|
|
1336
|
+
],
|
|
1337
|
+
queryFn: async () => {
|
|
1338
|
+
if (!payload || !walletProvider) throw new Error("payload and walletProvider are required");
|
|
1339
|
+
return unwrapResult(
|
|
1340
|
+
await sodax.swaps.getApprovalStrategy({ params: payload, walletProvider, allowAccountUpgrade })
|
|
1341
|
+
);
|
|
1342
|
+
},
|
|
1343
|
+
enabled: !!payload && !!walletProvider,
|
|
1344
|
+
...queryOptions
|
|
1345
|
+
});
|
|
1346
|
+
}
|
|
1347
|
+
function useSwapWithApproval({
|
|
1348
|
+
mutationOptions
|
|
1349
|
+
} = {}) {
|
|
1350
|
+
const { sodax } = useSodaxContext();
|
|
1351
|
+
const queryClient = useQueryClient();
|
|
1352
|
+
return useSafeMutation({
|
|
1353
|
+
mutationKey: ["swap", "swapWithApproval"],
|
|
1354
|
+
...mutationOptions,
|
|
1355
|
+
mutationFn: async (vars) => unwrapResult(await sodax.swaps.swapWithApproval({ ...vars, raw: false })),
|
|
1356
|
+
onSuccess: async (data, vars, ctx) => {
|
|
1357
|
+
invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
|
|
1358
|
+
queryClient.invalidateQueries({ queryKey: ["swap", "allowance"] });
|
|
1359
|
+
queryClient.invalidateQueries({ queryKey: ["swap", "approvalStrategy"] });
|
|
1360
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
1361
|
+
}
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
function isSameIntent(a, b) {
|
|
1365
|
+
return a.srcChainKey === b.srcChainKey && a.dstChainKey === b.dstChainKey && a.srcAddress === b.srcAddress && a.dstAddress === b.dstAddress && a.inputToken === b.inputToken && a.outputToken === b.outputToken && a.inputAmount === b.inputAmount && a.minOutputAmount === b.minOutputAmount && a.allowPartialFill === b.allowPartialFill && a.solver === b.solver && a.data === b.data && a.hook?.kind === b.hook?.kind && a.deliveryData === b.deliveryData;
|
|
1366
|
+
}
|
|
1367
|
+
function toSwapAttempt(mutation, intentParams) {
|
|
1368
|
+
if (mutation.status === "pending") return { phase: "submitting" };
|
|
1369
|
+
const attempted = mutation.variables?.params;
|
|
1370
|
+
if (mutation.status === "idle" || !attempted) return { phase: "none" };
|
|
1371
|
+
const attempt = toFinishedAttempt(mutation, attempted);
|
|
1372
|
+
const mayStillLand = attempt.phase === "unconfirmed" || attempt.phase === "broadcast" && attempt.error !== void 0;
|
|
1373
|
+
if (mayStillLand || intentParams && isSameIntent(attempted, intentParams)) return attempt;
|
|
1374
|
+
return { phase: "none" };
|
|
1375
|
+
}
|
|
1376
|
+
function toFinishedAttempt(mutation, attempted) {
|
|
1377
|
+
if (mutation.status === "success" && mutation.data) {
|
|
1378
|
+
const { srcChainKey, srcTxHash } = mutation.data.intentDeliveryInfo;
|
|
1379
|
+
return { phase: "broadcast", srcChainKey, srcTxHash };
|
|
1380
|
+
}
|
|
1381
|
+
const error = mutation.error ?? new Error("Swap failed");
|
|
1382
|
+
const context = isSodaxError(error) ? error.context : void 0;
|
|
1383
|
+
if (typeof context?.srcTxHash === "string") {
|
|
1384
|
+
return { phase: "broadcast", srcChainKey: attempted.srcChainKey, srcTxHash: context.srcTxHash, error };
|
|
1385
|
+
}
|
|
1386
|
+
if (context?.reason === ATOMIC_BATCH_UNCONFIRMED && typeof context.batchId === "string") {
|
|
1387
|
+
return typeof context.callCount === "number" ? { phase: "unconfirmed", batchId: context.batchId, callCount: context.callCount, error } : { phase: "unconfirmed", batchId: context.batchId, error };
|
|
1388
|
+
}
|
|
1389
|
+
return { phase: "failed", error };
|
|
1390
|
+
}
|
|
1391
|
+
function resolveSwapLifecycle(inputs) {
|
|
1392
|
+
const { attempt, status } = inputs;
|
|
1393
|
+
if (attempt.phase === "submitting") return { kind: "submitting" };
|
|
1394
|
+
if (attempt.phase === "broadcast") {
|
|
1395
|
+
const { srcChainKey, srcTxHash } = attempt;
|
|
1396
|
+
if (status?.state === "solved") return { kind: "settled", srcChainKey, srcTxHash, fillTxHash: status.fillTxHash };
|
|
1397
|
+
if (status?.state === "failed") {
|
|
1398
|
+
return { kind: "failed", error: attempt.error ?? new Error("Swap failed to settle"), srcChainKey, srcTxHash };
|
|
1399
|
+
}
|
|
1400
|
+
const error = attempt.error ?? inputs.statusError;
|
|
1401
|
+
return error ? { kind: "pending", srcChainKey, srcTxHash, error } : { kind: "pending", srcChainKey, srcTxHash };
|
|
1402
|
+
}
|
|
1403
|
+
if (attempt.phase === "unconfirmed") {
|
|
1404
|
+
const { batchId, callCount, error } = attempt;
|
|
1405
|
+
return callCount === void 0 ? { kind: "unconfirmed", batchId, error } : { kind: "unconfirmed", batchId, callCount, error };
|
|
1406
|
+
}
|
|
1407
|
+
if (attempt.phase === "failed") return { kind: "failed", error: attempt.error };
|
|
1408
|
+
if (!inputs.hasInputs) return { kind: "idle" };
|
|
1409
|
+
const reason = setupReason(inputs);
|
|
1410
|
+
if (reason) return inputs.setupBusy ? { kind: "checking" } : { kind: "needsSetup", reason };
|
|
1411
|
+
if (inputs.stellar.blocksAction || inputs.nearStorage.blocksAction) return { kind: "checking" };
|
|
1412
|
+
if (inputs.isWrongChain) return { kind: "needsChainSwitch" };
|
|
1413
|
+
if (inputs.strategy.error && !inputs.strategy.data) return { kind: "failed", error: inputs.strategy.error };
|
|
1414
|
+
if (!inputs.strategy.data) return { kind: "checking" };
|
|
1415
|
+
return { kind: "ready", approvalStrategy: inputs.strategy.data };
|
|
1416
|
+
}
|
|
1417
|
+
function setupReason({ stellar, nearStorage, externalBlocked }) {
|
|
1418
|
+
if (stellar.needsActivation) return "stellarActivation";
|
|
1419
|
+
if (stellar.needsFunding) return "stellarFunding";
|
|
1420
|
+
if (stellar.needsTrustline) return "stellarTrustline";
|
|
1421
|
+
if (stellar.checkFailed) return "stellarCheckFailed";
|
|
1422
|
+
if (nearStorage.needsRegistration) return "nearStorage";
|
|
1423
|
+
if (nearStorage.checkFailed) return "nearStorageCheckFailed";
|
|
1424
|
+
if (externalBlocked) return "external";
|
|
1425
|
+
return void 0;
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
// src/hooks/swap/useSwapLifecycle.ts
|
|
1429
|
+
function useSwapLifecycle({
|
|
1430
|
+
intentParams,
|
|
1431
|
+
srcWalletProvider,
|
|
1432
|
+
dstWalletProvider,
|
|
1433
|
+
chainSwitch,
|
|
1434
|
+
externalBlocked = false,
|
|
1435
|
+
allowAccountUpgrade,
|
|
1436
|
+
extras,
|
|
1437
|
+
timeout,
|
|
1438
|
+
mutationOptions
|
|
1439
|
+
}) {
|
|
1440
|
+
const approvalStrategy = useSwapApprovalStrategy({
|
|
1441
|
+
params: { payload: intentParams, walletProvider: srcWalletProvider, allowAccountUpgrade }
|
|
1442
|
+
});
|
|
1443
|
+
const swap = useSwapWithApproval({ mutationOptions });
|
|
1444
|
+
const stellar = useStellarGate({
|
|
1445
|
+
dstChainKey: intentParams?.dstChainKey,
|
|
1446
|
+
token: intentParams?.outputToken,
|
|
1447
|
+
// A 0n amount disables the trustline check, which would hold the lifecycle in `checking`.
|
|
1448
|
+
amount: intentParams && (intentParams.minOutputAmount > 0n ? intentParams.minOutputAmount : 1n),
|
|
1449
|
+
address: intentParams?.dstAddress,
|
|
1450
|
+
walletProvider: dstWalletProvider
|
|
1451
|
+
});
|
|
1452
|
+
const nearStorage = useNearStorageGate({
|
|
1453
|
+
dstChainKey: intentParams?.dstChainKey,
|
|
1454
|
+
token: intentParams?.outputToken,
|
|
1455
|
+
accountId: intentParams?.dstAddress,
|
|
1456
|
+
walletProvider: dstWalletProvider
|
|
1457
|
+
});
|
|
1458
|
+
const fetchingSetupChecks = useIsFetching({ queryKey: ["sponsoring", "stellarAccountStatus"] }) + useIsFetching({ queryKey: ["shared", "stellarTrustlineCheck"] }) + useIsFetching({ queryKey: ["shared", "nearStorageCheck"] });
|
|
1459
|
+
const attempt = toSwapAttempt(swap, intentParams);
|
|
1460
|
+
const broadcast = attempt.phase === "broadcast" ? attempt : void 0;
|
|
1461
|
+
const status = useDetailedStatus({
|
|
1462
|
+
params: { srcChainKey: broadcast?.srcChainKey, srcTxHash: broadcast?.srcTxHash }
|
|
1463
|
+
});
|
|
1464
|
+
const state = resolveSwapLifecycle({
|
|
1465
|
+
attempt,
|
|
1466
|
+
status: status.data?.ok ? summarizeSwapStatus(status.data.value) : void 0,
|
|
1467
|
+
statusError: status.data && !status.data.ok && isAuthFailure(status.data.error) ? status.data.error : void 0,
|
|
1468
|
+
hasInputs: !!intentParams && !!srcWalletProvider,
|
|
1469
|
+
stellar,
|
|
1470
|
+
nearStorage,
|
|
1471
|
+
externalBlocked,
|
|
1472
|
+
setupBusy: stellar.isActivating || stellar.isRequestingTrustline || nearStorage.isRegistering || fetchingSetupChecks > 0,
|
|
1473
|
+
isWrongChain: chainSwitch?.isWrongChain ?? false,
|
|
1474
|
+
strategy: { data: approvalStrategy.data, error: approvalStrategy.error }
|
|
1475
|
+
});
|
|
1476
|
+
const reset = () => {
|
|
1477
|
+
if (swap.isPending) return;
|
|
1478
|
+
swap.reset();
|
|
1479
|
+
void approvalStrategy.refetch();
|
|
1480
|
+
};
|
|
1481
|
+
const act = async () => {
|
|
1482
|
+
switch (state.kind) {
|
|
1483
|
+
case "needsChainSwitch":
|
|
1484
|
+
await chainSwitch?.switchChain();
|
|
1485
|
+
return void 0;
|
|
1486
|
+
case "needsSetup":
|
|
1487
|
+
if (state.reason === "stellarActivation") return stellar.activate();
|
|
1488
|
+
if (state.reason === "stellarTrustline") return stellar.requestTrustline();
|
|
1489
|
+
if (state.reason === "nearStorage") return nearStorage.registerStorage();
|
|
1490
|
+
if (state.reason === "stellarCheckFailed") stellar.retry();
|
|
1491
|
+
if (state.reason === "nearStorageCheckFailed") nearStorage.retry();
|
|
1492
|
+
return void 0;
|
|
1493
|
+
case "ready":
|
|
1494
|
+
if (!intentParams || !srcWalletProvider) return void 0;
|
|
1495
|
+
return swap.mutateAsyncSafe({
|
|
1496
|
+
params: intentParams,
|
|
1497
|
+
walletProvider: srcWalletProvider,
|
|
1498
|
+
allowAccountUpgrade,
|
|
1499
|
+
extras,
|
|
1500
|
+
timeout
|
|
1501
|
+
});
|
|
1502
|
+
// Sending it again could swap twice, so this only waits for the batch the wallet already holds.
|
|
1503
|
+
case "unconfirmed":
|
|
1504
|
+
if (!swap.variables) return void 0;
|
|
1505
|
+
return swap.mutateAsyncSafe({
|
|
1506
|
+
...swap.variables,
|
|
1507
|
+
resumeBatchId: state.batchId,
|
|
1508
|
+
resumeBatchCallCount: state.callCount
|
|
1509
|
+
});
|
|
1510
|
+
case "settled":
|
|
1511
|
+
case "failed":
|
|
1512
|
+
reset();
|
|
1513
|
+
return void 0;
|
|
1514
|
+
default:
|
|
1515
|
+
return void 0;
|
|
1516
|
+
}
|
|
1517
|
+
};
|
|
1518
|
+
const acting = useRef(false);
|
|
1519
|
+
const next = async () => {
|
|
1520
|
+
if (acting.current) return void 0;
|
|
1521
|
+
acting.current = true;
|
|
1522
|
+
try {
|
|
1523
|
+
return await act();
|
|
1524
|
+
} finally {
|
|
1525
|
+
acting.current = false;
|
|
1526
|
+
}
|
|
1527
|
+
};
|
|
1528
|
+
return {
|
|
1529
|
+
state,
|
|
1530
|
+
error: state.kind === "failed" || state.kind === "unconfirmed" || state.kind === "pending" ? state.error : void 0,
|
|
1531
|
+
next,
|
|
1532
|
+
reset,
|
|
1533
|
+
approvalStrategy,
|
|
1534
|
+
swap,
|
|
1535
|
+
status,
|
|
1536
|
+
stellar,
|
|
1537
|
+
nearStorage
|
|
1538
|
+
};
|
|
1539
|
+
}
|
|
1317
1540
|
|
|
1318
1541
|
// src/hooks/swap/useCancelSwap.ts
|
|
1319
1542
|
function useCancelSwap({
|
|
@@ -1781,6 +2004,81 @@ var useSwapsApiApproveAndBroadcast = ({
|
|
|
1781
2004
|
}
|
|
1782
2005
|
});
|
|
1783
2006
|
};
|
|
2007
|
+
var HOOK_NAME = "useSwapsApiBroadcastWithApproval";
|
|
2008
|
+
var sameAddress = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
2009
|
+
var useSwapsApiBroadcastWithApproval = ({
|
|
2010
|
+
mutationOptions
|
|
2011
|
+
} = {}) => {
|
|
2012
|
+
const { sodax } = useSodaxContext();
|
|
2013
|
+
const queryClient = useQueryClient();
|
|
2014
|
+
return useSafeMutation({
|
|
2015
|
+
mutationKey: ["swapsApi", "broadcastWithApproval"],
|
|
2016
|
+
...mutationOptions,
|
|
2017
|
+
mutationFn: async ({
|
|
2018
|
+
body,
|
|
2019
|
+
intentTx,
|
|
2020
|
+
walletProvider,
|
|
2021
|
+
apiConfig,
|
|
2022
|
+
allowAccountUpgrade,
|
|
2023
|
+
onProgress,
|
|
2024
|
+
onBatchSent,
|
|
2025
|
+
fallbackOnRefusal = false
|
|
2026
|
+
}) => {
|
|
2027
|
+
const srcChainKey = body.srcChainKey;
|
|
2028
|
+
if (!isEvmChainKeyType(srcChainKey)) {
|
|
2029
|
+
throw new Error(`[${HOOK_NAME}] ${body.srcChainKey} is not an EVM chain; approve and sign it separately.`);
|
|
2030
|
+
}
|
|
2031
|
+
const plan = unwrapResult(await sodax.api.swaps.approve(body, apiConfig));
|
|
2032
|
+
const account = await walletProvider.getWalletAddress();
|
|
2033
|
+
if (!sameAddress(account, body.srcAddress) || !sameAddress(account, intentTx.from)) {
|
|
2034
|
+
throw new Error(`[${HOOK_NAME}] the connected account is not the swap's source address.`);
|
|
2035
|
+
}
|
|
2036
|
+
const strategy = await resolveApprovalStrategy({ srcChainKey, walletProvider, allowAccountUpgrade });
|
|
2037
|
+
if (strategy === "atomic-batch" && isEvmSpokeOnlyChainKeyType(srcChainKey)) {
|
|
2038
|
+
const approvalTxs = plan.resetTx ? [plan.resetTx, plan.tx] : [plan.tx];
|
|
2039
|
+
const txs = [...approvalTxs, intentTx];
|
|
2040
|
+
const sent = await sendApprovalBatch({
|
|
2041
|
+
walletProvider,
|
|
2042
|
+
srcChainKey,
|
|
2043
|
+
txs,
|
|
2044
|
+
timeoutMs: DEFAULT_RELAY_TX_TIMEOUT,
|
|
2045
|
+
feature: "swap",
|
|
2046
|
+
context: { srcChainKey, dstChainKey: body.dstChainKey, action: HOOK_NAME, approvalStrategy: strategy },
|
|
2047
|
+
onBatchSent: onBatchSent && ((batchId) => onBatchSent(batchId, txs.length))
|
|
2048
|
+
});
|
|
2049
|
+
if (sent.ok || !isAtomicBatchRefusal(sent.error) || !fallbackOnRefusal) {
|
|
2050
|
+
return { txHash: unwrapResult(sent).txHash, approvalStrategy: "atomic-batch" };
|
|
2051
|
+
}
|
|
2052
|
+
} else if (!fallbackOnRefusal) {
|
|
2053
|
+
throw new SodaxError(
|
|
2054
|
+
"INTENT_CREATION_FAILED",
|
|
2055
|
+
`[${HOOK_NAME}] the wallet cannot send this approval as a batch.`,
|
|
2056
|
+
{
|
|
2057
|
+
feature: "swap",
|
|
2058
|
+
context: {
|
|
2059
|
+
srcChainKey,
|
|
2060
|
+
dstChainKey: body.dstChainKey,
|
|
2061
|
+
action: HOOK_NAME,
|
|
2062
|
+
approvalStrategy: strategy,
|
|
2063
|
+
phase: "intentCreation",
|
|
2064
|
+
reason: ATOMIC_BATCH_REFUSED
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
);
|
|
2068
|
+
}
|
|
2069
|
+
const approval = await runApprovalPlan({ plan, srcChainKey, walletProvider, hookName: HOOK_NAME, onProgress });
|
|
2070
|
+
await queryClient.invalidateQueries({ queryKey: ["swapsApi", "allowance"] });
|
|
2071
|
+
const txHash = await walletProvider.sendTransaction(intentTx, {
|
|
2072
|
+
expectedChainId: getEvmViemChain(srcChainKey).id
|
|
2073
|
+
});
|
|
2074
|
+
return { txHash, approvalStrategy: "sequential", approval };
|
|
2075
|
+
},
|
|
2076
|
+
onSuccess: async (data, vars, ctx) => {
|
|
2077
|
+
await queryClient.invalidateQueries({ queryKey: ["swapsApi", "allowance"] });
|
|
2078
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
2079
|
+
}
|
|
2080
|
+
});
|
|
2081
|
+
};
|
|
1784
2082
|
|
|
1785
2083
|
// src/hooks/swapsApi/useSwapsApiCreateIntent.ts
|
|
1786
2084
|
var useSwapsApiCreateIntent = ({
|
|
@@ -2149,6 +2447,51 @@ function useBridgeApprove({
|
|
|
2149
2447
|
}
|
|
2150
2448
|
});
|
|
2151
2449
|
}
|
|
2450
|
+
function useBridgeApprovalStrategy({
|
|
2451
|
+
params,
|
|
2452
|
+
queryOptions
|
|
2453
|
+
} = {}) {
|
|
2454
|
+
const { sodax } = useSodaxContext();
|
|
2455
|
+
const payload = params?.payload;
|
|
2456
|
+
const walletProvider = params?.walletProvider;
|
|
2457
|
+
const allowAccountUpgrade = params?.allowAccountUpgrade ?? true;
|
|
2458
|
+
return useQuery({
|
|
2459
|
+
queryKey: [
|
|
2460
|
+
"bridge",
|
|
2461
|
+
"approvalStrategy",
|
|
2462
|
+
payload?.srcChainKey,
|
|
2463
|
+
payload?.srcAddress,
|
|
2464
|
+
payload?.srcToken,
|
|
2465
|
+
payload?.amount.toString(),
|
|
2466
|
+
allowAccountUpgrade
|
|
2467
|
+
],
|
|
2468
|
+
queryFn: async () => {
|
|
2469
|
+
if (!payload || !walletProvider) throw new Error("payload and walletProvider are required");
|
|
2470
|
+
return unwrapResult(
|
|
2471
|
+
await sodax.bridge.getApprovalStrategy({ params: payload, walletProvider, allowAccountUpgrade })
|
|
2472
|
+
);
|
|
2473
|
+
},
|
|
2474
|
+
enabled: !!payload && !!walletProvider,
|
|
2475
|
+
...queryOptions
|
|
2476
|
+
});
|
|
2477
|
+
}
|
|
2478
|
+
function useBridgeWithApproval({
|
|
2479
|
+
mutationOptions
|
|
2480
|
+
} = {}) {
|
|
2481
|
+
const { sodax } = useSodaxContext();
|
|
2482
|
+
const queryClient = useQueryClient();
|
|
2483
|
+
return useSafeMutation({
|
|
2484
|
+
mutationKey: ["bridge", "bridgeWithApproval"],
|
|
2485
|
+
...mutationOptions,
|
|
2486
|
+
mutationFn: async (vars) => unwrapResult(await sodax.bridge.bridgeWithApproval({ ...vars, raw: false })),
|
|
2487
|
+
onSuccess: async (data, vars, ctx) => {
|
|
2488
|
+
invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
|
|
2489
|
+
queryClient.invalidateQueries({ queryKey: ["bridge", "allowance"] });
|
|
2490
|
+
queryClient.invalidateQueries({ queryKey: ["bridge", "approvalStrategy"] });
|
|
2491
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
2492
|
+
}
|
|
2493
|
+
});
|
|
2494
|
+
}
|
|
2152
2495
|
function useGetBridgeableAmount({
|
|
2153
2496
|
params,
|
|
2154
2497
|
queryOptions
|
|
@@ -3924,6 +4267,52 @@ function useLeverageYieldVaultSwap({
|
|
|
3924
4267
|
}
|
|
3925
4268
|
});
|
|
3926
4269
|
}
|
|
4270
|
+
function useLeverageYieldVaultSwapWithApproval({
|
|
4271
|
+
mutationOptions
|
|
4272
|
+
} = {}) {
|
|
4273
|
+
const { sodax } = useSodaxContext();
|
|
4274
|
+
const queryClient = useQueryClient();
|
|
4275
|
+
return useSafeMutation({
|
|
4276
|
+
mutationKey: ["leverageYield", "vaultSwapWithApproval"],
|
|
4277
|
+
...mutationOptions,
|
|
4278
|
+
mutationFn: async (vars) => unwrapResult(await sodax.leverageYield.vaultSwapWithApproval({ ...vars, raw: false })),
|
|
4279
|
+
onSuccess: async (data, vars, ctx) => {
|
|
4280
|
+
invalidateBalances(queryClient, vars.params.srcChainKey, vars.params.dstChainKey);
|
|
4281
|
+
queryClient.invalidateQueries({ queryKey: ["swap", "allowance"] });
|
|
4282
|
+
queryClient.invalidateQueries({ queryKey: ["leverageYield", "approvalStrategy"] });
|
|
4283
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
4284
|
+
}
|
|
4285
|
+
});
|
|
4286
|
+
}
|
|
4287
|
+
function useLeverageYieldApprovalStrategy({
|
|
4288
|
+
params,
|
|
4289
|
+
queryOptions
|
|
4290
|
+
} = {}) {
|
|
4291
|
+
const { sodax } = useSodaxContext();
|
|
4292
|
+
const payload = params?.payload;
|
|
4293
|
+
const walletProvider = params?.walletProvider;
|
|
4294
|
+
const allowAccountUpgrade = params?.allowAccountUpgrade ?? true;
|
|
4295
|
+
return useQuery({
|
|
4296
|
+
queryKey: [
|
|
4297
|
+
"leverageYield",
|
|
4298
|
+
"approvalStrategy",
|
|
4299
|
+
payload?.params.srcChainKey,
|
|
4300
|
+
payload?.params.srcAddress,
|
|
4301
|
+
payload?.params.inputToken,
|
|
4302
|
+
payload?.params.inputAmount.toString(),
|
|
4303
|
+
payload?.hubWalletSwap ?? false,
|
|
4304
|
+
allowAccountUpgrade
|
|
4305
|
+
],
|
|
4306
|
+
queryFn: async () => {
|
|
4307
|
+
if (!payload || !walletProvider) throw new Error("payload and walletProvider are required");
|
|
4308
|
+
return unwrapResult(
|
|
4309
|
+
await sodax.leverageYield.getApprovalStrategy({ ...payload, walletProvider, allowAccountUpgrade })
|
|
4310
|
+
);
|
|
4311
|
+
},
|
|
4312
|
+
enabled: !!payload && !!walletProvider,
|
|
4313
|
+
...queryOptions
|
|
4314
|
+
});
|
|
4315
|
+
}
|
|
3927
4316
|
|
|
3928
4317
|
// src/hooks/leverageYield/useLeverageYieldWithdraw.ts
|
|
3929
4318
|
function useLeverageYieldWithdraw({
|
|
@@ -4825,4 +5214,4 @@ function createSodaxQueryClient({
|
|
|
4825
5214
|
});
|
|
4826
5215
|
}
|
|
4827
5216
|
|
|
4828
|
-
export { SodaxProvider, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getBalancesQueryOptions, getBridgeDetailedStatusRefetchInterval, getLeverageYieldQuoteQueryOptions, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, getSwapQuoteQueryOptions, getXBalancesQueryOptions, invalidateBalances, isBridgeNotDelivered, isTerminalSwapIntentStatus, isUserRejectedError, loadRadfiSession, resolveNearStorageGate, resolveStellarGate, retryUnlessAuthFailure, runApprovalPlan, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useActivateStellarAccount, useApproveLeveragePositionFunding, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOracleCandles, useBackendOracleMarkets, useBackendOrderbook, useBackendUserIntents, useBalances, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApiAllowance, useBridgeApiApprove, useBridgeApiApproveAndBroadcast, useBridgeApiBridgeableAmount, useBridgeApiCreateBridgeIntent, useBridgeApiFee, useBridgeApiIsBridgeable, useBridgeApiSubmitTx, useBridgeApiSubmitTxStatus, useBridgeApiTokens, useBridgeApiTokensByChain, useBridgeApprove, useBridgeDetailedStatus, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDetailedStatus, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, useEModes, useEnsureRadfiAccessToken, useEstablishTrustline, useEstimateGas, useExpiredUtxos, useFeeClaimSwap, useFeeClaimWithdraw, useFetchAssetsBalances, useFundTradingWallet, useGetAutoSwapPreferences, useGetBridgeableAmount, useGetBridgeableTokens, useGetIntentDetails, useGetUserHubWalletAddress, useGetUserIntent, useHubAssetBalances, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useIsTokenApproved, useLeveragePositionAccount, useLeveragePositionCollateral, useLeveragePositionFundingAllowance, useLeveragePositionInfo, useLeveragePositionPayoutAddress, useLeveragePositionPending, useLeveragePositions, useLeveragePositionsForUser, useLeverageYieldApiAllowance, useLeverageYieldApiApprove, useLeverageYieldApiApproveAndBroadcast, useLeverageYieldApiApr, useLeverageYieldApiAsset, useLeverageYieldApiCancelIntent, useLeverageYieldApiCreateDepositIntent, useLeverageYieldApiCreateWithdrawIntent, useLeverageYieldApiDeadline, useLeverageYieldApiDepositQuote, useLeverageYieldApiEffectiveApr, useLeverageYieldApiEstimateGas, useLeverageYieldApiFilledIntent, useLeverageYieldApiIntent, useLeverageYieldApiIntentExtraData, useLeverageYieldApiIntentHash, useLeverageYieldApiIntentPacket, useLeverageYieldApiLsdApr, useLeverageYieldApiMaxWithdraw, useLeverageYieldApiPartnerFee, useLeverageYieldApiPosition, useLeverageYieldApiPreviewDeposit, useLeverageYieldApiPreviewRedeem, useLeverageYieldApiPreviewWithdraw, useLeverageYieldApiShareBalance, useLeverageYieldApiSolverFee, useLeverageYieldApiStatus, useLeverageYieldApiSubmitIntent, useLeverageYieldApiSubmitTx, useLeverageYieldApiSubmitTxStatus, useLeverageYieldApiTotalAssets, useLeverageYieldApiVault, useLeverageYieldApiVaults, useLeverageYieldApiWithdrawQuote, useLeverageYieldDeposit, useLeverageYieldDetailedStatus, useLeverageYieldEffectiveApr, useLeverageYieldNotifySolver, useLeverageYieldPosition, useLeverageYieldPreviewRedeem, useLeverageYieldQuote, useLeverageYieldShareBalances, useLeverageYieldTotalAssets, useLeverageYieldVaultSwap, useLeverageYieldWithdraw, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrateBaln, useMigrateIcxToSoda, useMigratebnUSD, useMigrationAllowance, useMigrationApprove, useNearStorageCheck, useNearStorageGate, useOpenLeveragePosition, usePartnerCancelIntent, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRegisterNearStorage, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesHumanized, useReservesList, useReservesUsdFormat, useRevertMigrateSodaToIcx, useRunLeveragePositionOperation, useSafeMutation, useSetSwapPreference, useSodaxContext, useSponsorConfig, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarAccountActive, useStellarAccountStatus, useStellarGate, useStellarTrustlineCheck, useSubmitLeveragePositionIntent, useSupply, useSupplyLiquidity, useSwap, useSwapAllowance, useSwapApprove, useSwapsApiAllowance, useSwapsApiApprove, useSwapsApiApproveAndBroadcast, useSwapsApiCancelIntent, useSwapsApiCreateIntent, useSwapsApiCreateLimitOrder, useSwapsApiDeadline, useSwapsApiEstimateGas, useSwapsApiFilledIntent, useSwapsApiIntent, useSwapsApiIntentExtraData, useSwapsApiIntentHash, useSwapsApiIntentPacket, useSwapsApiPartnerFee, useSwapsApiQuote, useSwapsApiSolverFee, useSwapsApiStatus, useSwapsApiSubmitIntent, useSwapsApiSubmitTx, useSwapsApiSubmitTxStatus, useSwapsApiTokens, useSwapsApiTokensByChain, useTradingWallet, useTradingWalletBalance, useUnstake, useUnstakeAllowance, useUnstakeApprove, useUnstakingInfo, useUnstakingInfoWithPenalty, useUserFormattedSummary, useUserReservesData, useWithdraw, useWithdrawHubAsset, useXBalances };
|
|
5217
|
+
export { SodaxProvider, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getBalancesQueryOptions, getBridgeDetailedStatusRefetchInterval, getLeverageYieldQuoteQueryOptions, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, getSwapQuoteQueryOptions, getXBalancesQueryOptions, invalidateBalances, isBridgeNotDelivered, isTerminalSwapIntentStatus, isUserRejectedError, loadRadfiSession, resolveNearStorageGate, resolveStellarGate, retryUnlessAuthFailure, runApprovalPlan, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useActivateStellarAccount, useApproveLeveragePositionFunding, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOracleCandles, useBackendOracleMarkets, useBackendOrderbook, useBackendUserIntents, useBalances, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApiAllowance, useBridgeApiApprove, useBridgeApiApproveAndBroadcast, useBridgeApiBridgeableAmount, useBridgeApiCreateBridgeIntent, useBridgeApiFee, useBridgeApiIsBridgeable, useBridgeApiSubmitTx, useBridgeApiSubmitTxStatus, useBridgeApiTokens, useBridgeApiTokensByChain, useBridgeApprovalStrategy, useBridgeApprove, useBridgeDetailedStatus, useBridgeWithApproval, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDetailedStatus, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, useEModes, useEnsureRadfiAccessToken, useEstablishTrustline, useEstimateGas, useExpiredUtxos, useFeeClaimSwap, useFeeClaimWithdraw, useFetchAssetsBalances, useFundTradingWallet, useGetAutoSwapPreferences, useGetBridgeableAmount, useGetBridgeableTokens, useGetIntentDetails, useGetUserHubWalletAddress, useGetUserIntent, useHubAssetBalances, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useIsTokenApproved, useLeveragePositionAccount, useLeveragePositionCollateral, useLeveragePositionFundingAllowance, useLeveragePositionInfo, useLeveragePositionPayoutAddress, useLeveragePositionPending, useLeveragePositions, useLeveragePositionsForUser, useLeverageYieldApiAllowance, useLeverageYieldApiApprove, useLeverageYieldApiApproveAndBroadcast, useLeverageYieldApiApr, useLeverageYieldApiAsset, useLeverageYieldApiCancelIntent, useLeverageYieldApiCreateDepositIntent, useLeverageYieldApiCreateWithdrawIntent, useLeverageYieldApiDeadline, useLeverageYieldApiDepositQuote, useLeverageYieldApiEffectiveApr, useLeverageYieldApiEstimateGas, useLeverageYieldApiFilledIntent, useLeverageYieldApiIntent, useLeverageYieldApiIntentExtraData, useLeverageYieldApiIntentHash, useLeverageYieldApiIntentPacket, useLeverageYieldApiLsdApr, useLeverageYieldApiMaxWithdraw, useLeverageYieldApiPartnerFee, useLeverageYieldApiPosition, useLeverageYieldApiPreviewDeposit, useLeverageYieldApiPreviewRedeem, useLeverageYieldApiPreviewWithdraw, useLeverageYieldApiShareBalance, useLeverageYieldApiSolverFee, useLeverageYieldApiStatus, useLeverageYieldApiSubmitIntent, useLeverageYieldApiSubmitTx, useLeverageYieldApiSubmitTxStatus, useLeverageYieldApiTotalAssets, useLeverageYieldApiVault, useLeverageYieldApiVaults, useLeverageYieldApiWithdrawQuote, useLeverageYieldApprovalStrategy, useLeverageYieldDeposit, useLeverageYieldDetailedStatus, useLeverageYieldEffectiveApr, useLeverageYieldNotifySolver, useLeverageYieldPosition, useLeverageYieldPreviewRedeem, useLeverageYieldQuote, useLeverageYieldShareBalances, useLeverageYieldTotalAssets, useLeverageYieldVaultSwap, useLeverageYieldVaultSwapWithApproval, useLeverageYieldWithdraw, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrateBaln, useMigrateIcxToSoda, useMigratebnUSD, useMigrationAllowance, useMigrationApprove, useNearStorageCheck, useNearStorageGate, useOpenLeveragePosition, usePartnerCancelIntent, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRegisterNearStorage, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesHumanized, useReservesList, useReservesUsdFormat, useRevertMigrateSodaToIcx, useRunLeveragePositionOperation, useSafeMutation, useSetSwapPreference, useSodaxContext, useSponsorConfig, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarAccountActive, useStellarAccountStatus, useStellarGate, useStellarTrustlineCheck, useSubmitLeveragePositionIntent, useSupply, useSupplyLiquidity, useSwap, useSwapAllowance, useSwapApprovalStrategy, useSwapApprove, useSwapLifecycle, useSwapWithApproval, useSwapsApiAllowance, useSwapsApiApprove, useSwapsApiApproveAndBroadcast, useSwapsApiBroadcastWithApproval, 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.
|
|
8
|
+
"version": "2.3.0-rc.1",
|
|
9
9
|
"description": "React hooks for building dApps on the SODAX cross-chain DeFi platform",
|
|
10
10
|
"keywords": [
|
|
11
11
|
"sodax",
|
|
@@ -15,9 +15,9 @@
|
|
|
15
15
|
"hooks",
|
|
16
16
|
"defi"
|
|
17
17
|
],
|
|
18
|
-
"homepage": "https://github.com/
|
|
18
|
+
"homepage": "https://github.com/gosodax/sodax-sdks/tree/main/packages/dapp-kit",
|
|
19
19
|
"bugs": {
|
|
20
|
-
"url": "https://github.com/
|
|
20
|
+
"url": "https://github.com/gosodax/sodax-sdks/issues"
|
|
21
21
|
},
|
|
22
22
|
"type": "module",
|
|
23
23
|
"main": "dist/index.mjs",
|
|
@@ -30,11 +30,11 @@
|
|
|
30
30
|
],
|
|
31
31
|
"repository": {
|
|
32
32
|
"type": "git",
|
|
33
|
-
"url": "https://github.com/
|
|
33
|
+
"url": "https://github.com/gosodax/sodax-sdks"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"viem": "2.29.2",
|
|
37
|
-
"@sodax/sdk": "2.
|
|
37
|
+
"@sodax/sdk": "2.3.0-rc.1"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@arethetypeswrong/cli": "0.17.4",
|
|
@@ -381,6 +381,16 @@ const ROWS: Row[] = [
|
|
|
381
381
|
return captured.mutationFn({ body: CREATE_INTENT_BODY, walletProvider: {}, apiConfig });
|
|
382
382
|
},
|
|
383
383
|
},
|
|
384
|
+
{
|
|
385
|
+
// Same shape: the approve request goes out before any wallet work, and its failed unwrap rejects.
|
|
386
|
+
hook: 'useSwapsApiBroadcastWithApproval',
|
|
387
|
+
path: '/swaps/approve',
|
|
388
|
+
method: 'POST',
|
|
389
|
+
run: apiConfig => {
|
|
390
|
+
swapsApi.useSwapsApiBroadcastWithApproval();
|
|
391
|
+
return captured.mutationFn({ body: CREATE_INTENT_BODY, intentTx: {}, walletProvider: {}, apiConfig });
|
|
392
|
+
},
|
|
393
|
+
},
|
|
384
394
|
// bridgeApi read hooks
|
|
385
395
|
{
|
|
386
396
|
hook: 'useBridgeApiTokens',
|
|
@@ -20,6 +20,7 @@ const HOOKS: Array<{ path: string; nativeThrow?: true }> = [
|
|
|
20
20
|
{ path: 'bitcoin/useRenewUtxos.ts', nativeThrow: true },
|
|
21
21
|
{ path: 'bridge/useBridge.ts' },
|
|
22
22
|
{ path: 'bridge/useBridgeApprove.ts' },
|
|
23
|
+
{ path: 'bridge/useBridgeWithApproval.ts' },
|
|
23
24
|
{ path: 'dex/useClaimRewards.ts' },
|
|
24
25
|
{ path: 'dex/useDecreaseLiquidity.ts' },
|
|
25
26
|
{ path: 'dex/useDexApprove.ts' },
|
|
@@ -30,6 +31,7 @@ const HOOKS: Array<{ path: string; nativeThrow?: true }> = [
|
|
|
30
31
|
{ path: 'leverageYield/useLeverageYieldDeposit.ts' },
|
|
31
32
|
{ path: 'leverageYield/useLeverageYieldNotifySolver.ts' },
|
|
32
33
|
{ path: 'leverageYield/useLeverageYieldVaultSwap.ts' },
|
|
34
|
+
{ path: 'leverageYield/useLeverageYieldVaultSwapWithApproval.ts' },
|
|
33
35
|
{ path: 'leverageYield/useLeverageYieldWithdraw.ts' },
|
|
34
36
|
{ path: 'leverageYield/useApproveLeveragePositionFunding.ts' },
|
|
35
37
|
{ path: 'leverageYield/useOpenLeveragePosition.ts' },
|
|
@@ -74,8 +76,10 @@ const HOOKS: Array<{ path: string; nativeThrow?: true }> = [
|
|
|
74
76
|
{ path: 'swap/useCreateLimitOrder.ts' },
|
|
75
77
|
{ path: 'swap/useSwap.ts' },
|
|
76
78
|
{ path: 'swap/useSwapApprove.ts' },
|
|
79
|
+
{ path: 'swap/useSwapWithApproval.ts' },
|
|
77
80
|
{ path: 'swapsApi/useSwapsApiApprove.ts' },
|
|
78
81
|
{ path: 'swapsApi/useSwapsApiApproveAndBroadcast.ts' },
|
|
82
|
+
{ path: 'swapsApi/useSwapsApiBroadcastWithApproval.ts' },
|
|
79
83
|
{ path: 'swapsApi/useSwapsApiCancelIntent.ts' },
|
|
80
84
|
{ path: 'swapsApi/useSwapsApiCreateIntent.ts' },
|
|
81
85
|
{ path: 'swapsApi/useSwapsApiCreateLimitOrder.ts' },
|
|
@@ -3,5 +3,7 @@ export * from './useBridge.js';
|
|
|
3
3
|
export * from './useBridgeDetailedStatus.js';
|
|
4
4
|
export * from './useBridgeAllowance.js';
|
|
5
5
|
export * from './useBridgeApprove.js';
|
|
6
|
+
export * from './useBridgeApprovalStrategy.js';
|
|
7
|
+
export * from './useBridgeWithApproval.js';
|
|
6
8
|
export * from './useGetBridgeableAmount.js';
|
|
7
9
|
export * from './useGetBridgeableTokens.js';
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { ChainKeys } from '@sodax/sdk';
|
|
2
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
type CapturedQuery = {
|
|
5
|
+
queryKey: unknown[];
|
|
6
|
+
queryFn: () => Promise<unknown>;
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
refetchInterval?: unknown;
|
|
9
|
+
};
|
|
10
|
+
let captured: CapturedQuery;
|
|
11
|
+
const getApprovalStrategy = vi.fn();
|
|
12
|
+
|
|
13
|
+
vi.mock('../shared/useSodaxContext.js', () => ({
|
|
14
|
+
useSodaxContext: () => ({ sodax: { bridge: { getApprovalStrategy } } }),
|
|
15
|
+
}));
|
|
16
|
+
vi.mock('@tanstack/react-query', () => ({
|
|
17
|
+
useQuery: (options: CapturedQuery) => {
|
|
18
|
+
captured = options;
|
|
19
|
+
return {};
|
|
20
|
+
},
|
|
21
|
+
}));
|
|
22
|
+
|
|
23
|
+
const { useBridgeApprovalStrategy } = await import('./useBridgeApprovalStrategy.js');
|
|
24
|
+
|
|
25
|
+
const PAYLOAD = {
|
|
26
|
+
srcAddress: '0x1111111111111111111111111111111111111111',
|
|
27
|
+
srcChainKey: ChainKeys.BSC_MAINNET,
|
|
28
|
+
srcToken: '0x2170Ed0880ac9A755fd29B2688956BD959F933F8',
|
|
29
|
+
amount: 1_000_000n,
|
|
30
|
+
dstChainKey: ChainKeys.ARBITRUM_MAINNET,
|
|
31
|
+
dstToken: '0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f',
|
|
32
|
+
recipient: '0x2222222222222222222222222222222222222222',
|
|
33
|
+
} as const;
|
|
34
|
+
const WALLET = { chainType: 'EVM' } as never;
|
|
35
|
+
|
|
36
|
+
beforeEach(() => {
|
|
37
|
+
vi.clearAllMocks();
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
describe('useBridgeApprovalStrategy', () => {
|
|
41
|
+
it('keys on chain, owner, token and stringified amount', () => {
|
|
42
|
+
useBridgeApprovalStrategy({ params: { payload: PAYLOAD, walletProvider: WALLET } });
|
|
43
|
+
expect(captured.queryKey).toEqual([
|
|
44
|
+
'bridge',
|
|
45
|
+
'approvalStrategy',
|
|
46
|
+
ChainKeys.BSC_MAINNET,
|
|
47
|
+
PAYLOAD.srcAddress,
|
|
48
|
+
PAYLOAD.srcToken,
|
|
49
|
+
'1000000',
|
|
50
|
+
true,
|
|
51
|
+
]);
|
|
52
|
+
expect(captured.enabled).toBe(true);
|
|
53
|
+
expect(captured.refetchInterval).toBeUndefined();
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('unwraps the SDK strategy and forwards allowAccountUpgrade', async () => {
|
|
57
|
+
getApprovalStrategy.mockResolvedValueOnce({ ok: true, value: 'sequential' });
|
|
58
|
+
useBridgeApprovalStrategy({ params: { payload: PAYLOAD, walletProvider: WALLET, allowAccountUpgrade: false } });
|
|
59
|
+
|
|
60
|
+
expect(captured.queryKey.at(-1)).toBe(false);
|
|
61
|
+
await expect(captured.queryFn()).resolves.toBe('sequential');
|
|
62
|
+
expect(getApprovalStrategy).toHaveBeenCalledWith({
|
|
63
|
+
params: PAYLOAD,
|
|
64
|
+
walletProvider: WALLET,
|
|
65
|
+
allowAccountUpgrade: false,
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('stays disabled until both the payload and the wallet are known', () => {
|
|
70
|
+
useBridgeApprovalStrategy({ params: { payload: PAYLOAD, walletProvider: undefined } });
|
|
71
|
+
expect(captured.enabled).toBe(false);
|
|
72
|
+
useBridgeApprovalStrategy({ params: { payload: undefined, walletProvider: WALLET } });
|
|
73
|
+
expect(captured.enabled).toBe(false);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
|
|
2
|
+
import type { ApprovalStrategy, CreateBridgeIntentParams, GetWalletProviderType, SpokeChainKey } from '@sodax/sdk';
|
|
3
|
+
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
4
|
+
import type { ReadHookParams } from '../shared/types.js';
|
|
5
|
+
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
6
|
+
|
|
7
|
+
export type UseBridgeApprovalStrategyParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<
|
|
8
|
+
ApprovalStrategy,
|
|
9
|
+
{
|
|
10
|
+
payload: CreateBridgeIntentParams<K> | undefined;
|
|
11
|
+
walletProvider: GetWalletProviderType<K> | undefined;
|
|
12
|
+
/** `false` keeps a wallet that would first ask to upgrade the account (EIP-5792 `'ready'`) off the batch path. Defaults to `true`. */
|
|
13
|
+
allowAccountUpgrade?: boolean;
|
|
14
|
+
}
|
|
15
|
+
>;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Which approval path {@link useBridgeWithApproval} would take for this bridge: `'not-required'`,
|
|
19
|
+
* `'atomic-batch'` (approve + deposit in one EIP-5792 signature) or `'sequential'` (approve, then
|
|
20
|
+
* bridge). Use it to label the bridge button. Pass the same `allowAccountUpgrade` you give the bridge.
|
|
21
|
+
*
|
|
22
|
+
* Not polled: `useBridgeWithApproval` invalidates it after a successful bridge, and the bridge
|
|
23
|
+
* re-reads the strategy at execution, so a stale label never picks the wrong path.
|
|
24
|
+
*/
|
|
25
|
+
export function useBridgeApprovalStrategy<K extends SpokeChainKey = SpokeChainKey>({
|
|
26
|
+
params,
|
|
27
|
+
queryOptions,
|
|
28
|
+
}: UseBridgeApprovalStrategyParams<K> = {}): UseQueryResult<ApprovalStrategy, Error> {
|
|
29
|
+
const { sodax } = useSodaxContext();
|
|
30
|
+
const payload = params?.payload;
|
|
31
|
+
const walletProvider = params?.walletProvider;
|
|
32
|
+
const allowAccountUpgrade = params?.allowAccountUpgrade ?? true;
|
|
33
|
+
|
|
34
|
+
return useQuery<ApprovalStrategy, Error>({
|
|
35
|
+
queryKey: [
|
|
36
|
+
'bridge',
|
|
37
|
+
'approvalStrategy',
|
|
38
|
+
payload?.srcChainKey,
|
|
39
|
+
payload?.srcAddress,
|
|
40
|
+
payload?.srcToken,
|
|
41
|
+
payload?.amount.toString(),
|
|
42
|
+
allowAccountUpgrade,
|
|
43
|
+
],
|
|
44
|
+
queryFn: async () => {
|
|
45
|
+
if (!payload || !walletProvider) throw new Error('payload and walletProvider are required');
|
|
46
|
+
return unwrapResult(
|
|
47
|
+
await sodax.bridge.getApprovalStrategy({ params: payload, walletProvider, allowAccountUpgrade }),
|
|
48
|
+
);
|
|
49
|
+
},
|
|
50
|
+
enabled: !!payload && !!walletProvider,
|
|
51
|
+
...queryOptions,
|
|
52
|
+
});
|
|
53
|
+
}
|