@sodax/dapp-kit 2.0.0 → 2.1.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 +128 -115
- package/dist/index.d.ts +155 -11
- package/dist/index.mjs +237 -45
- package/package.json +2 -2
- package/src/hooks/_mutationContract.test.ts +2 -0
- package/src/hooks/backend/types.ts +1 -1
- package/src/hooks/bridge/useBridgeApprove.ts +2 -1
- package/src/hooks/index.ts +1 -0
- package/src/hooks/migrate/useMigrationApprove.ts +1 -3
- package/src/hooks/mm/useWithdraw.ts +5 -1
- package/src/hooks/partner/useApproveToken.ts +1 -2
- package/src/hooks/shared/index.ts +2 -0
- package/src/hooks/shared/useEstablishTrustline.test.ts +89 -0
- package/src/hooks/shared/useEstablishTrustline.ts +72 -0
- package/src/hooks/shared/useRequestTrustline.test.ts +115 -0
- package/src/hooks/shared/useRequestTrustline.ts +41 -56
- package/src/hooks/shared/useSafeMutation.ts +1 -4
- package/src/hooks/shared/useStellarGate.test.ts +99 -0
- package/src/hooks/shared/useStellarGate.ts +102 -0
- package/src/hooks/shared/useStellarTrustlineCheck.test.ts +2 -2
- package/src/hooks/sponsoring/index.ts +4 -0
- package/src/hooks/sponsoring/useActivateStellarAccount.test.ts +74 -0
- package/src/hooks/sponsoring/useActivateStellarAccount.ts +38 -0
- package/src/hooks/sponsoring/useSponsorConfig.test.ts +46 -0
- package/src/hooks/sponsoring/useSponsorConfig.ts +31 -0
- package/src/hooks/sponsoring/useStellarAccountActive.test.ts +50 -0
- package/src/hooks/sponsoring/useStellarAccountActive.ts +45 -0
- package/src/hooks/sponsoring/useStellarAccountStatus.test.ts +90 -0
- package/src/hooks/sponsoring/useStellarAccountStatus.ts +57 -0
- package/src/hooks/staking/useStakingConfig.ts +1 -3
- package/src/hooks/staking/useStakingInfo.ts +4 -4
- package/src/hooks/staking/useUnstake.ts +5 -1
- package/src/hooks/swap/useCreateLimitOrder.ts +1 -2
- package/src/hooks/swap/useSwap.ts +1 -5
- package/src/index.ts +1 -1
- package/src/providers/createSodaxQueryClient.ts +1 -5
- package/src/utils/dex-utils.ts +1 -4
- package/src/utils/index.ts +1 -0
- package/src/utils/stellarGate.test.ts +196 -0
- package/src/utils/stellarGate.ts +84 -0
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { isSodaxError, ChainKeys, RadfiApiError, normalizePsbtToBase64, ClService, Sodax } from '@sodax/sdk';
|
|
1
|
+
import { isSodaxError, ChainKeys, STELLAR_TRUSTLINE_MIN_XLM_STROOPS, RadfiApiError, normalizePsbtToBase64, ClService, SPONSOR_CONFIG_TTL_MS, Sodax } from '@sodax/sdk';
|
|
2
2
|
export * from '@sodax/sdk';
|
|
3
3
|
import { useMutation, useQuery, useQueryClient, useQueries, QueryClient, MutationCache } from '@tanstack/react-query';
|
|
4
|
-
import { createContext, useCallback, useContext,
|
|
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';
|
|
7
7
|
|
|
@@ -111,52 +111,64 @@ function useStellarTrustlineCheck({
|
|
|
111
111
|
...queryOptions
|
|
112
112
|
});
|
|
113
113
|
}
|
|
114
|
-
function
|
|
114
|
+
function useEstablishTrustline({
|
|
115
|
+
mutationOptions
|
|
116
|
+
} = {}) {
|
|
115
117
|
const { sodax } = useSodaxContext();
|
|
116
118
|
const queryClient = useQueryClient();
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
token: token2,
|
|
124
|
-
amount,
|
|
125
|
-
srcChainKey,
|
|
126
|
-
walletProvider
|
|
127
|
-
}) => {
|
|
128
|
-
if (!token2 || !amount) {
|
|
129
|
-
const error2 = new Error("Token and amount are required");
|
|
130
|
-
setError(error2);
|
|
131
|
-
throw error2;
|
|
119
|
+
return useSafeMutation({
|
|
120
|
+
mutationKey: ["shared", "establishTrustline"],
|
|
121
|
+
...mutationOptions,
|
|
122
|
+
mutationFn: async ({ token, amount, srcChainKey, walletProvider }) => {
|
|
123
|
+
if (!token || !amount) {
|
|
124
|
+
throw new Error("Token and amount are required");
|
|
132
125
|
}
|
|
133
|
-
|
|
134
|
-
|
|
126
|
+
const srcAddress = await walletProvider.getWalletAddress();
|
|
127
|
+
return sodax.spoke.stellar.requestTrustline({
|
|
128
|
+
raw: false,
|
|
129
|
+
srcChainKey,
|
|
130
|
+
srcAddress,
|
|
131
|
+
token,
|
|
132
|
+
amount,
|
|
133
|
+
walletProvider
|
|
134
|
+
});
|
|
135
|
+
},
|
|
136
|
+
onSuccess: async (data, vars, ctx) => {
|
|
137
|
+
const srcAddress = await vars.walletProvider.getWalletAddress().catch(() => void 0);
|
|
138
|
+
queryClient.invalidateQueries({
|
|
139
|
+
queryKey: srcAddress ? ["shared", "stellarTrustlineCheck", vars.srcChainKey, vars.token, srcAddress] : ["shared", "stellarTrustlineCheck"]
|
|
140
|
+
});
|
|
141
|
+
queryClient.invalidateQueries({
|
|
142
|
+
queryKey: srcAddress ? ["sponsoring", "stellarAccountStatus", srcAddress] : ["sponsoring", "stellarAccountStatus"]
|
|
143
|
+
});
|
|
144
|
+
queryClient.invalidateQueries({ queryKey: ["shared", "xBalances", ChainKeys.STELLAR_MAINNET] });
|
|
145
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
function useRequestTrustline(token) {
|
|
150
|
+
const { mutateAsync, isPending, isSuccess, error, data } = useEstablishTrustline();
|
|
151
|
+
const requested = useRef(false);
|
|
152
|
+
const lastData = useRef(null);
|
|
153
|
+
if (isSuccess) requested.current = true;
|
|
154
|
+
if (data !== void 0) lastData.current = data;
|
|
155
|
+
const requestTrustline = useCallback(
|
|
156
|
+
async (params) => {
|
|
135
157
|
try {
|
|
136
|
-
|
|
137
|
-
const result = await sodax.spoke.stellar.requestTrustline({
|
|
138
|
-
raw: false,
|
|
139
|
-
srcChainKey,
|
|
140
|
-
srcAddress,
|
|
141
|
-
token: token2,
|
|
142
|
-
amount,
|
|
143
|
-
walletProvider
|
|
144
|
-
});
|
|
145
|
-
setData(result);
|
|
146
|
-
setIsRequested(true);
|
|
147
|
-
queryClient.invalidateQueries({ queryKey: ["shared", "stellarTrustlineCheck", srcChainKey, token2, srcAddress] });
|
|
148
|
-
return result;
|
|
158
|
+
return await mutateAsync(params);
|
|
149
159
|
} catch (err) {
|
|
150
|
-
|
|
151
|
-
setError(error2);
|
|
152
|
-
throw error2;
|
|
153
|
-
} finally {
|
|
154
|
-
setIsLoading(false);
|
|
160
|
+
throw err instanceof Error ? err : new Error("Unknown error occurred");
|
|
155
161
|
}
|
|
156
162
|
},
|
|
157
|
-
[
|
|
163
|
+
[mutateAsync]
|
|
158
164
|
);
|
|
159
|
-
return {
|
|
165
|
+
return {
|
|
166
|
+
requestTrustline,
|
|
167
|
+
isLoading: isPending,
|
|
168
|
+
isRequested: requested.current,
|
|
169
|
+
error,
|
|
170
|
+
data: lastData.current
|
|
171
|
+
};
|
|
160
172
|
}
|
|
161
173
|
function useNearStorageCheck({
|
|
162
174
|
params,
|
|
@@ -229,6 +241,140 @@ function useNearStorageGate({
|
|
|
229
241
|
registerStorage
|
|
230
242
|
};
|
|
231
243
|
}
|
|
244
|
+
function unresolved(check) {
|
|
245
|
+
return check.isLoading || check.data === void 0;
|
|
246
|
+
}
|
|
247
|
+
var NOT_STELLAR = {
|
|
248
|
+
isStellar: false,
|
|
249
|
+
needsActivation: false,
|
|
250
|
+
needsFunding: false,
|
|
251
|
+
needsTrustline: false,
|
|
252
|
+
checkFailed: false,
|
|
253
|
+
blocksAction: false
|
|
254
|
+
};
|
|
255
|
+
function resolveStellarGate(chainKey, inputs) {
|
|
256
|
+
const { statusCheck, trustlineCheck, isNativeToken } = inputs;
|
|
257
|
+
if (chainKey !== ChainKeys.STELLAR_MAINNET) return NOT_STELLAR;
|
|
258
|
+
const base = {
|
|
259
|
+
isStellar: true,
|
|
260
|
+
needsActivation: false,
|
|
261
|
+
needsFunding: false,
|
|
262
|
+
needsTrustline: false,
|
|
263
|
+
checkFailed: false
|
|
264
|
+
};
|
|
265
|
+
if (statusCheck.isError) return { ...base, checkFailed: true, blocksAction: true };
|
|
266
|
+
const status = statusCheck.data;
|
|
267
|
+
if (statusCheck.isLoading || status === void 0) return { ...base, blocksAction: true };
|
|
268
|
+
if (!status.exists) return { ...base, needsActivation: true, blocksAction: true };
|
|
269
|
+
if (isNativeToken) return { ...base, blocksAction: false };
|
|
270
|
+
if (trustlineCheck.isError) return { ...base, checkFailed: true, blocksAction: true };
|
|
271
|
+
if (unresolved(trustlineCheck)) return { ...base, blocksAction: true };
|
|
272
|
+
if (trustlineCheck.data === true) return { ...base, blocksAction: false };
|
|
273
|
+
if (!status.canAffordTrustline) return { ...base, needsFunding: true, blocksAction: true };
|
|
274
|
+
return { ...base, needsTrustline: true, blocksAction: true };
|
|
275
|
+
}
|
|
276
|
+
function useActivateStellarAccount({
|
|
277
|
+
mutationOptions
|
|
278
|
+
} = {}) {
|
|
279
|
+
const { sodax } = useSodaxContext();
|
|
280
|
+
const queryClient = useQueryClient();
|
|
281
|
+
return useSafeMutation({
|
|
282
|
+
mutationKey: ["sponsoring", "activateStellarAccount"],
|
|
283
|
+
...mutationOptions,
|
|
284
|
+
mutationFn: async (vars) => unwrapResult(await sodax.sponsoring.activateStellarAccount(vars)),
|
|
285
|
+
onSuccess: async (data, vars, ctx) => {
|
|
286
|
+
queryClient.invalidateQueries({ queryKey: ["sponsoring", "stellarAccountActive", vars.address] });
|
|
287
|
+
queryClient.invalidateQueries({ queryKey: ["sponsoring", "stellarAccountStatus", vars.address] });
|
|
288
|
+
queryClient.invalidateQueries({ queryKey: ["shared", "stellarTrustlineCheck"] });
|
|
289
|
+
queryClient.invalidateQueries({ queryKey: ["shared", "xBalances", ChainKeys.STELLAR_MAINNET] });
|
|
290
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
function getStellarAccountStatusQueryOptions({
|
|
295
|
+
sodax,
|
|
296
|
+
address
|
|
297
|
+
}) {
|
|
298
|
+
return {
|
|
299
|
+
queryKey: ["sponsoring", "stellarAccountStatus", address],
|
|
300
|
+
queryFn: async () => {
|
|
301
|
+
if (!address) {
|
|
302
|
+
return {
|
|
303
|
+
exists: false,
|
|
304
|
+
nativeBalanceStroops: 0n,
|
|
305
|
+
availableBalanceStroops: 0n,
|
|
306
|
+
canAffordTrustline: false,
|
|
307
|
+
// No account to read the network reserve for; the published value is the best guess.
|
|
308
|
+
trustlineMinXlmStroops: STELLAR_TRUSTLINE_MIN_XLM_STROOPS
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
const result = await sodax.sponsoring.getStellarAccountStatus({ address });
|
|
312
|
+
if (!result.ok) throw result.error;
|
|
313
|
+
return result.value;
|
|
314
|
+
},
|
|
315
|
+
enabled: !!address
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
function useStellarAccountStatus({
|
|
319
|
+
params,
|
|
320
|
+
queryOptions
|
|
321
|
+
} = {}) {
|
|
322
|
+
const { sodax } = useSodaxContext();
|
|
323
|
+
return useQuery({
|
|
324
|
+
...getStellarAccountStatusQueryOptions({ sodax, address: params?.address }),
|
|
325
|
+
...queryOptions
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// src/hooks/shared/useStellarGate.ts
|
|
330
|
+
function useStellarGate({
|
|
331
|
+
dstChainKey,
|
|
332
|
+
token,
|
|
333
|
+
amount,
|
|
334
|
+
address,
|
|
335
|
+
walletProvider
|
|
336
|
+
}) {
|
|
337
|
+
const { sodax } = useSodaxContext();
|
|
338
|
+
const isStellarDestination = dstChainKey === ChainKeys.STELLAR_MAINNET;
|
|
339
|
+
const stellarWalletProvider = walletProvider?.chainType === "STELLAR" ? walletProvider : void 0;
|
|
340
|
+
const gatedAddress = isStellarDestination ? address : void 0;
|
|
341
|
+
const statusCheck = useStellarAccountStatus({ params: { address: gatedAddress } });
|
|
342
|
+
const trustlineAddress = statusCheck.data?.exists === true ? gatedAddress : void 0;
|
|
343
|
+
const trustlineCheck = useStellarTrustlineCheck({
|
|
344
|
+
params: { token, amount, chainId: dstChainKey, walletAddress: trustlineAddress }
|
|
345
|
+
});
|
|
346
|
+
const isNativeToken = isStellarDestination && !!token && !sodax.spoke.stellar.requiresTrustline(token);
|
|
347
|
+
const state = resolveStellarGate(dstChainKey, { statusCheck, trustlineCheck, isNativeToken });
|
|
348
|
+
const { mutateAsyncSafe: activateAccount, isPending: isActivating } = useActivateStellarAccount();
|
|
349
|
+
const { mutateAsyncSafe: establishTrustline, isPending: isRequestingTrustline } = useEstablishTrustline();
|
|
350
|
+
const activate = async () => {
|
|
351
|
+
if (!stellarWalletProvider || !address) return void 0;
|
|
352
|
+
return activateAccount({ address, walletProvider: stellarWalletProvider });
|
|
353
|
+
};
|
|
354
|
+
const requestTrustline = async () => {
|
|
355
|
+
if (!stellarWalletProvider || !token || amount === void 0) return void 0;
|
|
356
|
+
return establishTrustline({
|
|
357
|
+
token,
|
|
358
|
+
amount,
|
|
359
|
+
srcChainKey: ChainKeys.STELLAR_MAINNET,
|
|
360
|
+
walletProvider: stellarWalletProvider
|
|
361
|
+
});
|
|
362
|
+
};
|
|
363
|
+
const retry = () => {
|
|
364
|
+
void statusCheck.refetch();
|
|
365
|
+
void trustlineCheck.refetch();
|
|
366
|
+
};
|
|
367
|
+
return {
|
|
368
|
+
...state,
|
|
369
|
+
isChecking: statusCheck.isLoading || trustlineCheck.isLoading,
|
|
370
|
+
error: statusCheck.error ?? trustlineCheck.error ?? void 0,
|
|
371
|
+
retry,
|
|
372
|
+
isActivating,
|
|
373
|
+
isRequestingTrustline,
|
|
374
|
+
activate,
|
|
375
|
+
requestTrustline
|
|
376
|
+
};
|
|
377
|
+
}
|
|
232
378
|
var SESSION_KEY = (address) => `radfi_session_${address}`;
|
|
233
379
|
function saveRadfiSession(address, session) {
|
|
234
380
|
try {
|
|
@@ -1843,7 +1989,10 @@ function useCancelUnstake({
|
|
|
1843
1989
|
}
|
|
1844
1990
|
});
|
|
1845
1991
|
}
|
|
1846
|
-
function useStakingInfo({
|
|
1992
|
+
function useStakingInfo({
|
|
1993
|
+
params,
|
|
1994
|
+
queryOptions
|
|
1995
|
+
} = {}) {
|
|
1847
1996
|
const { sodax } = useSodaxContext();
|
|
1848
1997
|
const srcAddress = params?.srcAddress;
|
|
1849
1998
|
const srcChainKey = params?.srcChainKey;
|
|
@@ -1884,9 +2033,7 @@ function useUnstakingInfoWithPenalty({
|
|
|
1884
2033
|
...queryOptions
|
|
1885
2034
|
});
|
|
1886
2035
|
}
|
|
1887
|
-
function useStakingConfig({
|
|
1888
|
-
queryOptions
|
|
1889
|
-
} = {}) {
|
|
2036
|
+
function useStakingConfig({ queryOptions } = {}) {
|
|
1890
2037
|
const { sodax } = useSodaxContext();
|
|
1891
2038
|
return useQuery({
|
|
1892
2039
|
queryKey: ["staking", "config"],
|
|
@@ -3196,6 +3343,51 @@ function useLeverageYieldWithdraw({
|
|
|
3196
3343
|
mutationFn: async (vars) => unwrapResult(await sodax.leverageYield.withdraw(vars))
|
|
3197
3344
|
});
|
|
3198
3345
|
}
|
|
3346
|
+
function getSponsorConfigQueryOptions({ sodax }) {
|
|
3347
|
+
return {
|
|
3348
|
+
queryKey: ["sponsoring", "sponsorConfig"],
|
|
3349
|
+
queryFn: async () => {
|
|
3350
|
+
const result = await sodax.sponsoring.getStellarSponsorConfig();
|
|
3351
|
+
if (!result.ok) throw result.error;
|
|
3352
|
+
return result.value;
|
|
3353
|
+
},
|
|
3354
|
+
staleTime: SPONSOR_CONFIG_TTL_MS
|
|
3355
|
+
};
|
|
3356
|
+
}
|
|
3357
|
+
function useSponsorConfig({
|
|
3358
|
+
queryOptions
|
|
3359
|
+
} = {}) {
|
|
3360
|
+
const { sodax } = useSodaxContext();
|
|
3361
|
+
return useQuery({
|
|
3362
|
+
...getSponsorConfigQueryOptions({ sodax }),
|
|
3363
|
+
...queryOptions
|
|
3364
|
+
});
|
|
3365
|
+
}
|
|
3366
|
+
function getStellarAccountActiveQueryOptions({
|
|
3367
|
+
sodax,
|
|
3368
|
+
address
|
|
3369
|
+
}) {
|
|
3370
|
+
return {
|
|
3371
|
+
queryKey: ["sponsoring", "stellarAccountActive", address],
|
|
3372
|
+
queryFn: async () => {
|
|
3373
|
+
if (!address) return false;
|
|
3374
|
+
const result = await sodax.sponsoring.isStellarAccountActive({ address });
|
|
3375
|
+
if (!result.ok) throw result.error;
|
|
3376
|
+
return result.value;
|
|
3377
|
+
},
|
|
3378
|
+
enabled: !!address
|
|
3379
|
+
};
|
|
3380
|
+
}
|
|
3381
|
+
function useStellarAccountActive({
|
|
3382
|
+
params,
|
|
3383
|
+
queryOptions
|
|
3384
|
+
} = {}) {
|
|
3385
|
+
const { sodax } = useSodaxContext();
|
|
3386
|
+
return useQuery({
|
|
3387
|
+
...getStellarAccountActiveQueryOptions({ sodax, address: params?.address }),
|
|
3388
|
+
...queryOptions
|
|
3389
|
+
});
|
|
3390
|
+
}
|
|
3199
3391
|
var SodaxProvider = ({ children, config }) => {
|
|
3200
3392
|
const sodax = useMemo(() => new Sodax(config), [config]);
|
|
3201
3393
|
const contextValue = useMemo(() => ({ sodax }), [sodax]);
|
|
@@ -3227,4 +3419,4 @@ function createSodaxQueryClient({
|
|
|
3227
3419
|
});
|
|
3228
3420
|
}
|
|
3229
3421
|
|
|
3230
|
-
export { SodaxProvider, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getStellarTrustlineCheckQueryOptions, getXBalancesQueryOptions, isTerminalSwapIntentStatus, isUserRejectedError, loadRadfiSession, resolveNearStorageGate, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOrderbook, useBackendUserIntents, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApprove, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, useEnsureRadfiAccessToken, useEstimateGas, useExpiredUtxos, useFeeClaimSwap, useFeeClaimWithdraw, useFetchAssetsBalances, useFundTradingWallet, useGetAutoSwapPreferences, useGetBridgeableAmount, useGetBridgeableTokens, useGetIntentDetails, useGetUserHubWalletAddress, useGetUserIntent, useHubAssetBalances, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useIsTokenApproved, useLeverageYieldDeposit, useLeverageYieldEffectiveApr, useLeverageYieldNotifySolver, useLeverageYieldPosition, useLeverageYieldPreviewRedeem, useLeverageYieldShareBalances, useLeverageYieldTotalAssets, useLeverageYieldVaultSwap, useLeverageYieldWithdraw, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrateBaln, useMigrateIcxToSoda, useMigratebnUSD, useMigrationAllowance, useMigrationApprove, useNearStorageCheck, useNearStorageGate, usePartnerCancelIntent, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRegisterNearStorage, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesHumanized, useReservesList, useReservesUsdFormat, useRevertMigrateSodaToIcx, useSafeMutation, useSetSwapPreference, useSodaxContext, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarTrustlineCheck, useSupply, useSupplyLiquidity, useSwap, useSwapAllowance, useSwapApprove, useSwapsApiAllowance, useSwapsApiApprove, useSwapsApiCancelIntent, useSwapsApiCreateIntent, useSwapsApiCreateLimitOrder, useSwapsApiDeadline, useSwapsApiEstimateGas, useSwapsApiFilledIntent, useSwapsApiIntent, useSwapsApiIntentExtraData, useSwapsApiIntentHash, useSwapsApiIntentPacket, useSwapsApiPartnerFee, useSwapsApiQuote, useSwapsApiSolverFee, useSwapsApiStatus, useSwapsApiSubmitIntent, useSwapsApiSubmitTx, useSwapsApiSubmitTxStatus, useSwapsApiTokens, useSwapsApiTokensByChain, useTradingWallet, useTradingWalletBalance, useUnstake, useUnstakeAllowance, useUnstakeApprove, useUnstakingInfo, useUnstakingInfoWithPenalty, useUserFormattedSummary, useUserReservesData, useWithdraw, useWithdrawHubAsset, useXBalances };
|
|
3422
|
+
export { SodaxProvider, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getSponsorConfigQueryOptions, getStellarAccountActiveQueryOptions, getStellarAccountStatusQueryOptions, getStellarTrustlineCheckQueryOptions, getXBalancesQueryOptions, isTerminalSwapIntentStatus, isUserRejectedError, loadRadfiSession, resolveNearStorageGate, resolveStellarGate, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useActivateStellarAccount, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOrderbook, useBackendUserIntents, useBitcoinBalance, useBitcoinTradingSetup, useBorrow, useBridge, useBridgeAllowance, useBridgeApprove, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, useEnsureRadfiAccessToken, useEstablishTrustline, useEstimateGas, useExpiredUtxos, useFeeClaimSwap, useFeeClaimWithdraw, useFetchAssetsBalances, useFundTradingWallet, useGetAutoSwapPreferences, useGetBridgeableAmount, useGetBridgeableTokens, useGetIntentDetails, useGetUserHubWalletAddress, useGetUserIntent, useHubAssetBalances, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useIsTokenApproved, useLeverageYieldDeposit, useLeverageYieldEffectiveApr, useLeverageYieldNotifySolver, useLeverageYieldPosition, useLeverageYieldPreviewRedeem, useLeverageYieldShareBalances, useLeverageYieldTotalAssets, useLeverageYieldVaultSwap, useLeverageYieldWithdraw, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrateBaln, useMigrateIcxToSoda, useMigratebnUSD, useMigrationAllowance, useMigrationApprove, useNearStorageCheck, useNearStorageGate, usePartnerCancelIntent, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRegisterNearStorage, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesHumanized, useReservesList, useReservesUsdFormat, useRevertMigrateSodaToIcx, useSafeMutation, useSetSwapPreference, useSodaxContext, useSponsorConfig, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarAccountActive, useStellarAccountStatus, useStellarGate, useStellarTrustlineCheck, useSupply, useSupplyLiquidity, useSwap, useSwapAllowance, useSwapApprove, useSwapsApiAllowance, useSwapsApiApprove, useSwapsApiCancelIntent, useSwapsApiCreateIntent, useSwapsApiCreateLimitOrder, useSwapsApiDeadline, useSwapsApiEstimateGas, useSwapsApiFilledIntent, useSwapsApiIntent, useSwapsApiIntentExtraData, useSwapsApiIntentHash, useSwapsApiIntentPacket, useSwapsApiPartnerFee, useSwapsApiQuote, useSwapsApiSolverFee, useSwapsApiStatus, useSwapsApiSubmitIntent, useSwapsApiSubmitTx, useSwapsApiSubmitTxStatus, useSwapsApiTokens, useSwapsApiTokensByChain, useTradingWallet, useTradingWalletBalance, useUnstake, useUnstakeAllowance, useUnstakeApprove, useUnstakingInfo, useUnstakingInfoWithPenalty, useUserFormattedSummary, useUserReservesData, useWithdraw, useWithdrawHubAsset, useXBalances };
|
package/package.json
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
7
7
|
"license": "MIT",
|
|
8
|
-
"version": "2.0.
|
|
8
|
+
"version": "2.1.0-rc.1",
|
|
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.0.
|
|
37
|
+
"@sodax/sdk": "2.1.0-rc.1"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@arethetypeswrong/cli": "0.17.4",
|
|
@@ -46,8 +46,10 @@ const HOOKS: Array<{ path: string; nativeThrow?: true }> = [
|
|
|
46
46
|
{ path: 'partner/usePartnerCancelIntent.ts' },
|
|
47
47
|
{ path: 'partner/useSetSwapPreference.ts' },
|
|
48
48
|
{ path: 'recovery/useWithdrawHubAsset.ts' },
|
|
49
|
+
{ path: 'shared/useEstablishTrustline.ts', nativeThrow: true },
|
|
49
50
|
{ path: 'shared/useEstimateGas.ts' },
|
|
50
51
|
{ path: 'shared/useRegisterNearStorage.ts', nativeThrow: true },
|
|
52
|
+
{ path: 'sponsoring/useActivateStellarAccount.ts' },
|
|
51
53
|
{ path: 'staking/useCancelUnstake.ts' },
|
|
52
54
|
{ path: 'staking/useClaim.ts' },
|
|
53
55
|
{ path: 'staking/useInstantUnstake.ts' },
|
|
@@ -34,7 +34,8 @@ export function useBridgeApprove<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
34
34
|
return useSafeMutation<TxReturnType<K, false>, Error, UseBridgeApproveVars<K>>({
|
|
35
35
|
mutationKey: ['bridge', 'approve'],
|
|
36
36
|
...mutationOptions,
|
|
37
|
-
mutationFn: async vars =>
|
|
37
|
+
mutationFn: async vars =>
|
|
38
|
+
unwrapResult(await sodax.bridge.approve({ ...vars, raw: false } as BridgeParams<K, false>)),
|
|
38
39
|
onSuccess: async (data, vars, ctx) => {
|
|
39
40
|
queryClient.invalidateQueries({ queryKey: ['bridge', 'allowance'] });
|
|
40
41
|
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
package/src/hooks/index.ts
CHANGED
|
@@ -49,9 +49,7 @@ export function useMigrationApprove<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
49
49
|
mutationFn: async ({ action, ...actionParams }) =>
|
|
50
50
|
unwrapResult(
|
|
51
51
|
await sodax.migration.approve(
|
|
52
|
-
{ ...actionParams, raw: false } as
|
|
53
|
-
| IcxRevertMigrationAction<false>
|
|
54
|
-
| UnifiedBnUSDMigrateAction<K, false>,
|
|
52
|
+
{ ...actionParams, raw: false } as IcxRevertMigrationAction<false> | UnifiedBnUSDMigrateAction<K, false>,
|
|
55
53
|
action,
|
|
56
54
|
),
|
|
57
55
|
),
|
|
@@ -24,7 +24,11 @@ export type UseWithdrawVars<K extends SpokeChainKey = SpokeChainKey> = Omit<
|
|
|
24
24
|
*/
|
|
25
25
|
export function useWithdraw<K extends SpokeChainKey = SpokeChainKey>({
|
|
26
26
|
mutationOptions,
|
|
27
|
-
}: MutationHookParams<TxHashPair, UseWithdrawVars<K>> = {}): SafeUseMutationResult<
|
|
27
|
+
}: MutationHookParams<TxHashPair, UseWithdrawVars<K>> = {}): SafeUseMutationResult<
|
|
28
|
+
TxHashPair,
|
|
29
|
+
Error,
|
|
30
|
+
UseWithdrawVars<K>
|
|
31
|
+
> {
|
|
28
32
|
const { sodax } = useSodaxContext();
|
|
29
33
|
const queryClient = useQueryClient();
|
|
30
34
|
|
|
@@ -29,8 +29,7 @@ export function useApproveToken({
|
|
|
29
29
|
return useSafeMutation<ApproveTokenData, Error, UseApproveTokenVars>({
|
|
30
30
|
mutationKey: ['partner', 'approveToken'],
|
|
31
31
|
...mutationOptions,
|
|
32
|
-
mutationFn: async vars =>
|
|
33
|
-
unwrapResult(await sodax.partners.feeClaim.approveToken<false>({ ...vars, raw: false })),
|
|
32
|
+
mutationFn: async vars => unwrapResult(await sodax.partners.feeClaim.approveToken<false>({ ...vars, raw: false })),
|
|
34
33
|
onSuccess: async (data, vars, ctx) => {
|
|
35
34
|
const { params } = vars;
|
|
36
35
|
queryClient.invalidateQueries({
|
|
@@ -6,9 +6,11 @@ export * from './useSodaxContext.js';
|
|
|
6
6
|
export * from './useEstimateGas.js';
|
|
7
7
|
export * from './useDeriveUserWalletAddress.js';
|
|
8
8
|
export * from './useStellarTrustlineCheck.js';
|
|
9
|
+
export * from './useEstablishTrustline.js';
|
|
9
10
|
export * from './useRequestTrustline.js';
|
|
10
11
|
export * from './useNearStorageCheck.js';
|
|
11
12
|
export * from './useRegisterNearStorage.js';
|
|
12
13
|
export * from './useNearStorageGate.js';
|
|
14
|
+
export * from './useStellarGate.js';
|
|
13
15
|
export * from './useGetUserHubWalletAddress.js';
|
|
14
16
|
export * from './useXBalances.js';
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { ChainKeys } from '@sodax/sdk';
|
|
2
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
const invalidateQueries = vi.fn();
|
|
5
|
+
const requestTrustline = vi.fn();
|
|
6
|
+
|
|
7
|
+
// The hook is a pure options builder around useSafeMutation, so stubbing the three
|
|
8
|
+
// React-side imports lets the real onSuccess run without a DOM.
|
|
9
|
+
vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
|
|
10
|
+
vi.mock('./useSodaxContext.js', () => ({
|
|
11
|
+
useSodaxContext: () => ({ sodax: { spoke: { stellar: { requestTrustline } } } }),
|
|
12
|
+
}));
|
|
13
|
+
vi.mock('./useSafeMutation.js', () => ({ useSafeMutation: (options: unknown) => options }));
|
|
14
|
+
|
|
15
|
+
const { useEstablishTrustline } = await import('./useEstablishTrustline.js');
|
|
16
|
+
|
|
17
|
+
const TOKEN = 'CBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
|
|
18
|
+
const ADDRESS = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
|
|
19
|
+
|
|
20
|
+
type OnSuccess = (data: string, vars: unknown, ctx: unknown) => Promise<void>;
|
|
21
|
+
type MutationFn = (vars: unknown) => Promise<string>;
|
|
22
|
+
|
|
23
|
+
const vars = (getWalletAddress: () => Promise<string>) => ({
|
|
24
|
+
token: TOKEN,
|
|
25
|
+
amount: 1_000_000n,
|
|
26
|
+
srcChainKey: ChainKeys.STELLAR_MAINNET,
|
|
27
|
+
walletProvider: { getWalletAddress } as never,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const optionsOf = () => useEstablishTrustline() as unknown as { onSuccess: OnSuccess; mutationFn: MutationFn };
|
|
31
|
+
|
|
32
|
+
const invalidatedKeys = () => invalidateQueries.mock.calls.map(([arg]) => arg.queryKey);
|
|
33
|
+
|
|
34
|
+
beforeEach(() => {
|
|
35
|
+
invalidateQueries.mockReset();
|
|
36
|
+
requestTrustline.mockReset();
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
describe('useEstablishTrustline — invalidation after a broadcast trustline', () => {
|
|
40
|
+
it('invalidates the account-scoped keys when the address is readable', async () => {
|
|
41
|
+
await optionsOf().onSuccess(
|
|
42
|
+
'hash',
|
|
43
|
+
vars(async () => ADDRESS),
|
|
44
|
+
undefined,
|
|
45
|
+
);
|
|
46
|
+
|
|
47
|
+
expect(invalidatedKeys()).toEqual([
|
|
48
|
+
['shared', 'stellarTrustlineCheck', ChainKeys.STELLAR_MAINNET, TOKEN, ADDRESS],
|
|
49
|
+
['sponsoring', 'stellarAccountStatus', ADDRESS],
|
|
50
|
+
['shared', 'xBalances', ChainKeys.STELLAR_MAINNET],
|
|
51
|
+
]);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('SURVIVES a wallet that fails right after signing, and still invalidates', async () => {
|
|
55
|
+
// The trustline is already on-chain here: throwing would report success as an
|
|
56
|
+
// error and leave the gate showing "needs a trustline" until a manual refetch.
|
|
57
|
+
const rejecting = vars(async () => {
|
|
58
|
+
throw new Error('wallet is locked');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
await expect(optionsOf().onSuccess('hash', rejecting, undefined)).resolves.toBeUndefined();
|
|
62
|
+
|
|
63
|
+
// Falls back to the whole prefix, because the account is no longer identifiable.
|
|
64
|
+
expect(invalidatedKeys()).toEqual([
|
|
65
|
+
['shared', 'stellarTrustlineCheck'],
|
|
66
|
+
['sponsoring', 'stellarAccountStatus'],
|
|
67
|
+
['shared', 'xBalances', ChainKeys.STELLAR_MAINNET],
|
|
68
|
+
]);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe('useEstablishTrustline — input guard carried over from useRequestTrustline', () => {
|
|
73
|
+
it.each([
|
|
74
|
+
['a zero amount', { amount: 0n }],
|
|
75
|
+
['an empty token', { token: '' }],
|
|
76
|
+
])('rejects %s without reaching the wallet', async (_label, override) => {
|
|
77
|
+
const invalid = { ...vars(async () => ADDRESS), ...override };
|
|
78
|
+
|
|
79
|
+
await expect(optionsOf().mutationFn(invalid)).rejects.toThrow('Token and amount are required');
|
|
80
|
+
expect(requestTrustline).not.toHaveBeenCalled();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('derives srcAddress from the wallet provider for a valid request', async () => {
|
|
84
|
+
requestTrustline.mockResolvedValue('hash');
|
|
85
|
+
|
|
86
|
+
await expect(optionsOf().mutationFn(vars(async () => ADDRESS))).resolves.toBe('hash');
|
|
87
|
+
expect(requestTrustline).toHaveBeenCalledWith(expect.objectContaining({ raw: false, srcAddress: ADDRESS }));
|
|
88
|
+
});
|
|
89
|
+
});
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { IStellarWalletProvider, StellarChainKey } from '@sodax/sdk';
|
|
2
|
+
import { ChainKeys } from '@sodax/sdk';
|
|
3
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
4
|
+
import type { MutationHookParams } from './types.js';
|
|
5
|
+
import { useSafeMutation, type SafeUseMutationResult } from './useSafeMutation.js';
|
|
6
|
+
import { useSodaxContext } from './useSodaxContext.js';
|
|
7
|
+
|
|
8
|
+
export type UseEstablishTrustlineVars = {
|
|
9
|
+
token: string;
|
|
10
|
+
amount: bigint;
|
|
11
|
+
srcChainKey: StellarChainKey;
|
|
12
|
+
walletProvider: IStellarWalletProvider;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Establish a Stellar trustline. The account pays its fee and reserve; use
|
|
17
|
+
* {@link useStellarGate} to verify it can afford them.
|
|
18
|
+
*
|
|
19
|
+
* Supersedes the deprecated `useRequestTrustline`, which keeps the hand-rolled
|
|
20
|
+
* shape released in 2.0.0.
|
|
21
|
+
*/
|
|
22
|
+
export function useEstablishTrustline({
|
|
23
|
+
mutationOptions,
|
|
24
|
+
}: MutationHookParams<string, UseEstablishTrustlineVars> = {}): SafeUseMutationResult<
|
|
25
|
+
string,
|
|
26
|
+
Error,
|
|
27
|
+
UseEstablishTrustlineVars
|
|
28
|
+
> {
|
|
29
|
+
const { sodax } = useSodaxContext();
|
|
30
|
+
const queryClient = useQueryClient();
|
|
31
|
+
|
|
32
|
+
return useSafeMutation<string, Error, UseEstablishTrustlineVars>({
|
|
33
|
+
mutationKey: ['shared', 'establishTrustline'],
|
|
34
|
+
...mutationOptions,
|
|
35
|
+
mutationFn: async ({ token, amount, srcChainKey, walletProvider }): Promise<string> => {
|
|
36
|
+
// Rejecting `0n` preserves the behaviour of the hook this replaced: an amount
|
|
37
|
+
// sizes the trustline check, so zero is a caller bug rather than a request.
|
|
38
|
+
if (!token || !amount) {
|
|
39
|
+
throw new Error('Token and amount are required');
|
|
40
|
+
}
|
|
41
|
+
const srcAddress = await walletProvider.getWalletAddress();
|
|
42
|
+
return sodax.spoke.stellar.requestTrustline<false>({
|
|
43
|
+
raw: false,
|
|
44
|
+
srcChainKey,
|
|
45
|
+
srcAddress,
|
|
46
|
+
token,
|
|
47
|
+
amount,
|
|
48
|
+
walletProvider,
|
|
49
|
+
});
|
|
50
|
+
},
|
|
51
|
+
onSuccess: async (data, vars, ctx) => {
|
|
52
|
+
// The trustline is already broadcast here, so a wallet that locks or switches
|
|
53
|
+
// accounts mid-flow must not turn success into an error — nor skip the
|
|
54
|
+
// invalidations below, which is what an unguarded throw would do.
|
|
55
|
+
const srcAddress = await vars.walletProvider.getWalletAddress().catch(() => undefined);
|
|
56
|
+
// Without the address, invalidate the whole prefix rather than nothing.
|
|
57
|
+
queryClient.invalidateQueries({
|
|
58
|
+
queryKey: srcAddress
|
|
59
|
+
? ['shared', 'stellarTrustlineCheck', vars.srcChainKey, vars.token, srcAddress]
|
|
60
|
+
: ['shared', 'stellarTrustlineCheck'],
|
|
61
|
+
});
|
|
62
|
+
// A new trustline changes spendable XLM for subsequent trustlines.
|
|
63
|
+
queryClient.invalidateQueries({
|
|
64
|
+
queryKey: srcAddress
|
|
65
|
+
? ['sponsoring', 'stellarAccountStatus', srcAddress]
|
|
66
|
+
: ['sponsoring', 'stellarAccountStatus'],
|
|
67
|
+
});
|
|
68
|
+
queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.STELLAR_MAINNET] });
|
|
69
|
+
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
}
|