@sodax/dapp-kit 0.0.1-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.
Files changed (78) hide show
  1. package/README.md +260 -0
  2. package/dist/contexts/index.d.ts +7 -0
  3. package/dist/contexts/index.d.ts.map +1 -0
  4. package/dist/core/index.d.ts +4 -0
  5. package/dist/core/index.d.ts.map +1 -0
  6. package/dist/hooks/index.d.ts +5 -0
  7. package/dist/hooks/index.d.ts.map +1 -0
  8. package/dist/hooks/mm/index.d.ts +7 -0
  9. package/dist/hooks/mm/index.d.ts.map +1 -0
  10. package/dist/hooks/mm/useBorrow.d.ts +26 -0
  11. package/dist/hooks/mm/useBorrow.d.ts.map +1 -0
  12. package/dist/hooks/mm/useHubWalletAddress.d.ts +24 -0
  13. package/dist/hooks/mm/useHubWalletAddress.d.ts.map +1 -0
  14. package/dist/hooks/mm/useRepay.d.ts +26 -0
  15. package/dist/hooks/mm/useRepay.d.ts.map +1 -0
  16. package/dist/hooks/mm/useSupply.d.ts +32 -0
  17. package/dist/hooks/mm/useSupply.d.ts.map +1 -0
  18. package/dist/hooks/mm/useUserReservesData.d.ts +9 -0
  19. package/dist/hooks/mm/useUserReservesData.d.ts.map +1 -0
  20. package/dist/hooks/mm/useWithdraw.d.ts +26 -0
  21. package/dist/hooks/mm/useWithdraw.d.ts.map +1 -0
  22. package/dist/hooks/provider/index.d.ts +3 -0
  23. package/dist/hooks/provider/index.d.ts.map +1 -0
  24. package/dist/hooks/provider/useHubProvider.d.ts +3 -0
  25. package/dist/hooks/provider/useHubProvider.d.ts.map +1 -0
  26. package/dist/hooks/provider/useSpokeProvider.d.ts +4 -0
  27. package/dist/hooks/provider/useSpokeProvider.d.ts.map +1 -0
  28. package/dist/hooks/shared/index.d.ts +4 -0
  29. package/dist/hooks/shared/index.d.ts.map +1 -0
  30. package/dist/hooks/shared/useAllowance.d.ts +3 -0
  31. package/dist/hooks/shared/useAllowance.d.ts.map +1 -0
  32. package/dist/hooks/shared/useApprove.d.ts +10 -0
  33. package/dist/hooks/shared/useApprove.d.ts.map +1 -0
  34. package/dist/hooks/shared/useSodaxContext.d.ts +8 -0
  35. package/dist/hooks/shared/useSodaxContext.d.ts.map +1 -0
  36. package/dist/hooks/swap/index.d.ts +4 -0
  37. package/dist/hooks/swap/index.d.ts.map +1 -0
  38. package/dist/hooks/swap/useCreateIntentOrder.d.ts +33 -0
  39. package/dist/hooks/swap/useCreateIntentOrder.d.ts.map +1 -0
  40. package/dist/hooks/swap/useQuote.d.ts +39 -0
  41. package/dist/hooks/swap/useQuote.d.ts.map +1 -0
  42. package/dist/hooks/swap/useStatus.d.ts +31 -0
  43. package/dist/hooks/swap/useStatus.d.ts.map +1 -0
  44. package/dist/index.d.ts +4 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +363 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/index.mjs +341 -0
  49. package/dist/index.mjs.map +1 -0
  50. package/dist/providers/SodaxProvider.d.ts +10 -0
  51. package/dist/providers/SodaxProvider.d.ts.map +1 -0
  52. package/dist/providers/index.d.ts +2 -0
  53. package/dist/providers/index.d.ts.map +1 -0
  54. package/package.json +54 -0
  55. package/src/contexts/index.ts +9 -0
  56. package/src/core/index.ts +42 -0
  57. package/src/hooks/index.ts +4 -0
  58. package/src/hooks/mm/index.ts +6 -0
  59. package/src/hooks/mm/useBorrow.ts +55 -0
  60. package/src/hooks/mm/useHubWalletAddress.ts +49 -0
  61. package/src/hooks/mm/useRepay.ts +56 -0
  62. package/src/hooks/mm/useSupply.ts +62 -0
  63. package/src/hooks/mm/useUserReservesData.ts +58 -0
  64. package/src/hooks/mm/useWithdraw.ts +59 -0
  65. package/src/hooks/provider/index.ts +2 -0
  66. package/src/hooks/provider/useHubProvider.ts +27 -0
  67. package/src/hooks/provider/useSpokeProvider.ts +23 -0
  68. package/src/hooks/shared/index.ts +3 -0
  69. package/src/hooks/shared/useAllowance.ts +31 -0
  70. package/src/hooks/shared/useApprove.ts +53 -0
  71. package/src/hooks/shared/useSodaxContext.ts +16 -0
  72. package/src/hooks/swap/index.ts +3 -0
  73. package/src/hooks/swap/useCreateIntentOrder.ts +57 -0
  74. package/src/hooks/swap/useQuote.ts +55 -0
  75. package/src/hooks/swap/useStatus.ts +44 -0
  76. package/src/index.ts +3 -0
  77. package/src/providers/SodaxProvider.tsx +16 -0
  78. package/src/providers/index.ts +1 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,341 @@
1
+ import React, { createContext, useContext, useMemo } from 'react';
2
+ import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query';
3
+ import { hubAssets, EvmSpokeProvider, spokeChainConfig, SuiSpokeProvider, getHubChainConfig, EvmHubProvider, EvmWalletAbstraction, getMoneyMarketConfig, Sodax } from '@sodax/sdk';
4
+ import { getXChainType, useWalletProvider, useXAccount } from '@sodax/wallet-sdk';
5
+ import { parseUnits } from 'viem';
6
+ import { CHAIN_IDS } from '@sodax/types';
7
+
8
+ // src/contexts/index.ts
9
+ var SodaxContext = createContext(null);
10
+ var useSodaxContext = () => {
11
+ const context = useContext(SodaxContext);
12
+ if (!context) {
13
+ throw new Error("useSodaxContext must be used within a SodaxProvider");
14
+ }
15
+ return context;
16
+ };
17
+ function useSpokeProvider(spokeChainId) {
18
+ const xChainType = getXChainType(spokeChainId);
19
+ const walletProvider = useWalletProvider(spokeChainId);
20
+ const spokeProvider = useMemo(() => {
21
+ if (!walletProvider) return void 0;
22
+ if (xChainType === "EVM") {
23
+ return new EvmSpokeProvider(walletProvider, spokeChainConfig[spokeChainId]);
24
+ }
25
+ if (xChainType === "SUI") {
26
+ return new SuiSpokeProvider(spokeChainConfig[spokeChainId], walletProvider);
27
+ }
28
+ return void 0;
29
+ }, [walletProvider, xChainType, spokeChainId]);
30
+ return spokeProvider;
31
+ }
32
+ function useAllowance(token, amount) {
33
+ const { sodax } = useSodaxContext();
34
+ const spokeProvider = useSpokeProvider(token.xChainId);
35
+ return useQuery({
36
+ queryKey: ["allowance", token.address, amount],
37
+ queryFn: async () => {
38
+ if (!spokeProvider) {
39
+ return false;
40
+ }
41
+ const allowance = await sodax.moneyMarket.isAllowanceValid(
42
+ {
43
+ token: token.address,
44
+ amount: parseUnits(amount, token.decimals)
45
+ },
46
+ spokeProvider
47
+ );
48
+ if (allowance.ok) {
49
+ return allowance.value;
50
+ }
51
+ return false;
52
+ },
53
+ enabled: !!spokeProvider
54
+ });
55
+ }
56
+ function useApprove(token) {
57
+ const { sodax } = useSodaxContext();
58
+ const spokeProvider = useSpokeProvider(token.xChainId);
59
+ const queryClient = useQueryClient();
60
+ const {
61
+ mutateAsync: approve,
62
+ isPending,
63
+ error,
64
+ reset: resetError
65
+ } = useMutation({
66
+ mutationFn: async (amount) => {
67
+ if (!spokeProvider) {
68
+ throw new Error("Spoke provider not found");
69
+ }
70
+ const allowance = await sodax.moneyMarket.approve(
71
+ token.address,
72
+ parseUnits(amount, token.decimals),
73
+ spokeProvider.chainConfig.addresses.assetManager,
74
+ spokeProvider
75
+ );
76
+ if (!allowance.ok) {
77
+ throw new Error("Failed to approve tokens");
78
+ }
79
+ return allowance.ok;
80
+ },
81
+ onSuccess: () => {
82
+ queryClient.invalidateQueries({ queryKey: ["allowance", token.address] });
83
+ }
84
+ });
85
+ return {
86
+ approve,
87
+ isLoading: isPending,
88
+ error,
89
+ resetError
90
+ };
91
+ }
92
+ function useHubProvider() {
93
+ const { sodax } = useSodaxContext();
94
+ const hubChainId = sodax.config?.hubProviderConfig?.chainConfig.chain.id;
95
+ const hubRpcUrl = sodax.config?.hubProviderConfig?.hubRpcUrl;
96
+ const xChainType = getXChainType(hubChainId);
97
+ const hubProvider = useMemo(() => {
98
+ if (xChainType === "EVM" && hubChainId && hubRpcUrl) {
99
+ const hubChainCfg = getHubChainConfig(hubChainId);
100
+ if (!hubChainCfg) return void 0;
101
+ return new EvmHubProvider({
102
+ hubRpcUrl,
103
+ chainConfig: hubChainCfg
104
+ });
105
+ }
106
+ return void 0;
107
+ }, [xChainType, hubChainId, hubRpcUrl]);
108
+ return hubProvider;
109
+ }
110
+ function useBorrow(hubToken, spokeChainId) {
111
+ const { sodax } = useSodaxContext();
112
+ const spokeProvider = useSpokeProvider(spokeChainId);
113
+ return useMutation({
114
+ mutationFn: async (amount) => {
115
+ if (!spokeProvider) {
116
+ throw new Error("spokeProvider is not found");
117
+ }
118
+ const response = await sodax.moneyMarket.borrowAndSubmit(
119
+ {
120
+ token: hubToken.address,
121
+ amount: parseUnits(amount, hubToken.decimals)
122
+ },
123
+ spokeProvider
124
+ );
125
+ if (!response.ok) {
126
+ throw new Error("Failed to borrow tokens");
127
+ }
128
+ console.log("Borrow transaction submitted:", response);
129
+ return response;
130
+ }
131
+ });
132
+ }
133
+ function useRepay(hubToken, spokeChainId) {
134
+ const { sodax } = useSodaxContext();
135
+ const spokeProvider = useSpokeProvider(spokeChainId);
136
+ return useMutation({
137
+ mutationFn: async (amount) => {
138
+ if (!spokeProvider) {
139
+ throw new Error("spokeProvider is not found");
140
+ }
141
+ const response = await sodax.moneyMarket.repayAndSubmit(
142
+ {
143
+ token: hubToken.address,
144
+ amount: parseUnits(amount, hubToken.decimals)
145
+ },
146
+ spokeProvider
147
+ );
148
+ if (!response.ok) {
149
+ throw new Error("Failed to repay tokens");
150
+ }
151
+ console.log("Repay transaction submitted:", response);
152
+ return response;
153
+ }
154
+ });
155
+ }
156
+ function useSupply(spokeToken) {
157
+ const { sodax } = useSodaxContext();
158
+ const spokeProvider = useSpokeProvider(spokeToken.xChainId);
159
+ return useMutation({
160
+ mutationFn: async (amount) => {
161
+ if (!spokeProvider) {
162
+ throw new Error("spokeProvider is not found");
163
+ }
164
+ const response = await sodax.moneyMarket.supplyAndSubmit(
165
+ {
166
+ token: spokeToken.address,
167
+ amount: parseUnits(amount, spokeToken.decimals)
168
+ },
169
+ spokeProvider
170
+ );
171
+ if (!response.ok) {
172
+ throw new Error("Failed to supply tokens");
173
+ }
174
+ console.log("Supply transaction submitted:", response);
175
+ return response;
176
+ }
177
+ });
178
+ }
179
+ function useWithdraw(hubToken, spokeChainId) {
180
+ const { sodax } = useSodaxContext();
181
+ const spokeProvider = useSpokeProvider(spokeChainId);
182
+ return useMutation({
183
+ mutationFn: async (amount) => {
184
+ if (!spokeProvider) {
185
+ throw new Error("spokeProvider is not found");
186
+ }
187
+ const response = await sodax.moneyMarket.withdrawAndSubmit(
188
+ {
189
+ token: hubToken.address,
190
+ amount: parseUnits(amount, hubToken.decimals)
191
+ },
192
+ spokeProvider
193
+ );
194
+ if (!response.ok) {
195
+ throw new Error("Failed to withdraw tokens");
196
+ }
197
+ console.log("Withdraw transaction submitted:", response);
198
+ return response;
199
+ }
200
+ });
201
+ }
202
+ var allXTokens = [];
203
+ Object.keys(hubAssets).forEach((xChainId) => {
204
+ const tokens = hubAssets[xChainId];
205
+ Object.keys(tokens).forEach((tokenAddress) => {
206
+ const token = tokens[tokenAddress];
207
+ allXTokens.push({
208
+ xChainId,
209
+ symbol: token.symbol,
210
+ name: token.name,
211
+ decimals: token.decimal,
212
+ address: tokenAddress
213
+ });
214
+ allXTokens.push({
215
+ // @ts-ignore
216
+ xChainId: CHAIN_IDS.includes(xChainId) ? "sonic" : "sonic-blaze",
217
+ symbol: token.symbol,
218
+ name: token.name,
219
+ decimals: token.decimal,
220
+ address: token.vault
221
+ });
222
+ });
223
+ });
224
+ var getSpokeTokenAddressByVault = (spokeChainId, vault) => {
225
+ const tokens = hubAssets[spokeChainId];
226
+ const token = Object.keys(tokens).find((tokenAddress) => tokens[tokenAddress].vault === vault);
227
+ if (!token) {
228
+ throw new Error("Token not found");
229
+ }
230
+ return token;
231
+ };
232
+ function useHubWalletAddress(spokeChainId, address, hubProvider) {
233
+ return useQuery({
234
+ queryKey: ["hubWallet", spokeChainId, address],
235
+ queryFn: async () => {
236
+ if (!address) return null;
237
+ try {
238
+ const hubWalletAddress = await EvmWalletAbstraction.getUserHubWalletAddress(
239
+ spokeChainId,
240
+ address,
241
+ hubProvider
242
+ );
243
+ return hubWalletAddress;
244
+ } catch (error) {
245
+ console.log("error", error);
246
+ return null;
247
+ }
248
+ },
249
+ enabled: !!address && !!hubProvider
250
+ });
251
+ }
252
+
253
+ // src/hooks/mm/useUserReservesData.ts
254
+ function useUserReservesData(spokeChainId) {
255
+ const { sodax } = useSodaxContext();
256
+ const hubChainId = sodax.config?.hubProviderConfig?.chainConfig.chain.id ?? "sonic";
257
+ const hubWalletProvider = useWalletProvider(hubChainId);
258
+ const hubProvider = useHubProvider();
259
+ const { address } = useXAccount(spokeChainId);
260
+ const { data: hubWalletAddress } = useHubWalletAddress(
261
+ spokeChainId,
262
+ address,
263
+ hubProvider
264
+ );
265
+ const { data: userReserves } = useQuery({
266
+ queryKey: ["userReserves", hubWalletAddress],
267
+ queryFn: async () => {
268
+ if (!hubWalletProvider) {
269
+ return;
270
+ }
271
+ if (!hubWalletAddress) {
272
+ return;
273
+ }
274
+ const moneyMarketConfig = getMoneyMarketConfig(hubChainId);
275
+ try {
276
+ const [res] = await sodax.moneyMarket.getUserReservesData(
277
+ hubWalletAddress,
278
+ moneyMarketConfig.uiPoolDataProvider,
279
+ moneyMarketConfig.poolAddressesProvider
280
+ );
281
+ return res?.map((r) => {
282
+ return {
283
+ ...r,
284
+ token: allXTokens.find((t) => t.address === r.underlyingAsset)
285
+ };
286
+ });
287
+ } catch (error) {
288
+ console.log("error", error);
289
+ return;
290
+ }
291
+ },
292
+ enabled: !!address && !!hubWalletProvider && !!hubWalletAddress,
293
+ refetchInterval: 5e3
294
+ });
295
+ return userReserves;
296
+ }
297
+ var useQuote = (payload) => {
298
+ const { sodax } = useSodaxContext();
299
+ return useQuery({
300
+ queryKey: [payload],
301
+ queryFn: async () => {
302
+ if (!payload) {
303
+ return void 0;
304
+ }
305
+ return sodax.solver.getQuote(payload);
306
+ },
307
+ enabled: !!payload,
308
+ refetchInterval: 3e3
309
+ });
310
+ };
311
+ function useCreateIntentOrder(chainId) {
312
+ const { sodax } = useSodaxContext();
313
+ const spokeProvider = useSpokeProvider(chainId);
314
+ return useMutation({
315
+ mutationFn: async (params) => {
316
+ if (!spokeProvider) {
317
+ throw new Error("Spoke provider not found");
318
+ }
319
+ return sodax.solver.createAndSubmitIntent(params, spokeProvider);
320
+ }
321
+ });
322
+ }
323
+ var useStatus = (intent_tx_hash) => {
324
+ const { sodax } = useSodaxContext();
325
+ return useQuery({
326
+ queryKey: [intent_tx_hash],
327
+ queryFn: async () => {
328
+ return sodax.solver.getStatus({ intent_tx_hash });
329
+ },
330
+ refetchInterval: 3e3
331
+ // 3s
332
+ });
333
+ };
334
+ var SodaxProvider = ({ children, testnet = false, config }) => {
335
+ const sodax = new Sodax(config);
336
+ return /* @__PURE__ */ React.createElement(SodaxContext.Provider, { value: { sodax, testnet } }, children);
337
+ };
338
+
339
+ export { SodaxProvider, allXTokens, getSpokeTokenAddressByVault, useAllowance, useApprove, useBorrow, useCreateIntentOrder, useHubProvider, useHubWalletAddress, useQuote, useRepay, useSodaxContext, useSpokeProvider, useStatus, useSupply, useUserReservesData, useWithdraw };
340
+ //# sourceMappingURL=index.mjs.map
341
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/contexts/index.ts","../src/hooks/shared/useSodaxContext.ts","../src/hooks/provider/useSpokeProvider.ts","../src/hooks/shared/useAllowance.ts","../src/hooks/shared/useApprove.ts","../src/hooks/provider/useHubProvider.ts","../src/hooks/mm/useBorrow.ts","../src/hooks/mm/useRepay.ts","../src/hooks/mm/useSupply.ts","../src/hooks/mm/useWithdraw.ts","../src/core/index.ts","../src/hooks/mm/useHubWalletAddress.ts","../src/hooks/mm/useUserReservesData.ts","../src/hooks/swap/useQuote.ts","../src/hooks/swap/useCreateIntentOrder.ts","../src/hooks/swap/useStatus.ts","../src/providers/SodaxProvider.tsx"],"names":["parseUnits","getXChainType","useMemo","useMutation","useQuery","useWalletProvider"],"mappings":";;;;;;;;AAQO,IAAM,YAAA,GAAe,cAAuC,IAAI,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A;AAAA,KACtC;AAAA,IACA,OAAA,EAAS,CAAC,CAAC,OAAA;AAAA,IACX,eAAiB,EAAA;AAAA,GAClB,CAAA;AACH;ACZO,SAAS,qBACd,OACkE,EAAA;AAClE,EAAM,MAAA,EAAE,KAAM,EAAA,GAAI,eAAgB,EAAA;AAClC,EAAM,MAAA,aAAA,GAAgB,iBAAiB,OAAO,CAAA;AAE9C,EAAA,OAAOD,WAA2D,CAAA;AAAA,IAChE,UAAA,EAAY,OAAO,MAA+B,KAAA;AAChD,MAAA,IAAI,CAAC,aAAe,EAAA;AAClB,QAAM,MAAA,IAAI,MAAM,0BAA0B,CAAA;AAAA;AAE5C,MAAA,OAAO,KAAM,CAAA,MAAA,CAAO,qBAAsB,CAAA,MAAA,EAAQ,aAAa,CAAA;AAAA;AACjE,GACD,CAAA;AACH;ACxBa,IAAA,SAAA,GAAY,CACvB,cACkF,KAAA;AAClF,EAAM,MAAA,EAAE,KAAM,EAAA,GAAI,eAAgB,EAAA;AAClC,EAAA,OAAOC,QAAS,CAAA;AAAA,IACd,QAAA,EAAU,CAAC,cAAc,CAAA;AAAA,IACzB,SAAS,YAAY;AACnB,MAAA,OAAO,KAAM,CAAA,MAAA,CAAO,SAAU,CAAA,EAAE,gBAAgB,CAAA;AAAA,KAClD;AAAA,IACA,eAAiB,EAAA;AAAA;AAAA,GAClB,CAAA;AACH;AChCO,IAAM,gBAAgB,CAAC,EAAE,UAAU,OAAU,GAAA,KAAA,EAAO,QAA+C,KAAA;AACxG,EAAM,MAAA,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAM,CAAA;AAE9B,EAAO,uBAAA,KAAA,CAAA,aAAA,CAAC,aAAa,QAAb,EAAA,EAAsB,OAAO,EAAE,KAAA,EAAO,OAAQ,EAAA,EAAA,EAAI,QAAS,CAAA;AACrE","file":"index.mjs","sourcesContent":["import { createContext } from 'react';\nimport type { Sodax } from '@sodax/sdk';\n\nexport interface SodaxContextType {\n sodax: Sodax;\n testnet: boolean;\n}\n\nexport const SodaxContext = createContext<SodaxContextType | null>(null);\n","import { SodaxContext, type SodaxContextType } from '@/contexts';\nimport { useContext } from 'react';\n\n/**\n * Hook to access the Sodax context which provides access to the Sodax SDK instance and chain configuration\n * @throws {Error} If used outside of a SodaxProvider\n * @returns {SodaxContextType} The Sodax context containing SDK instance and configuration\n */\n\nexport const useSodaxContext = (): SodaxContextType => {\n const context = useContext(SodaxContext);\n if (!context) {\n throw new Error('useSodaxContext must be used within a SodaxProvider');\n }\n return context;\n};\n","import { EvmSpokeProvider, spokeChainConfig, SuiSpokeProvider } from '@sodax/sdk';\nimport type { SpokeChainId } from '@sodax/types';\nimport { getXChainType, useWalletProvider } from '@sodax/wallet-sdk';\nimport { useMemo } from 'react';\n\nexport function useSpokeProvider(spokeChainId: SpokeChainId) {\n const xChainType = getXChainType(spokeChainId);\n const walletProvider = useWalletProvider(spokeChainId);\n const spokeProvider = useMemo(() => {\n if (!walletProvider) return undefined;\n if (xChainType === 'EVM') {\n // @ts-ignore\n return new EvmSpokeProvider(walletProvider, spokeChainConfig[spokeChainId]);\n }\n if (xChainType === 'SUI') {\n // @ts-ignore\n return new SuiSpokeProvider(spokeChainConfig[spokeChainId], walletProvider);\n }\n return undefined;\n }, [walletProvider, xChainType, spokeChainId]);\n\n return spokeProvider;\n}\n","import { useQuery } from '@tanstack/react-query';\nimport type { SpokeChainId, XToken } from '@sodax/types';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport { useSpokeProvider } from '../provider/useSpokeProvider';\nimport { parseUnits } from 'viem';\n\nexport function useAllowance(token: XToken, amount: string) {\n const { sodax } = useSodaxContext();\n const spokeProvider = useSpokeProvider(token.xChainId as SpokeChainId);\n\n return useQuery({\n queryKey: ['allowance', token.address, amount],\n queryFn: async () => {\n if (!spokeProvider) {\n return false;\n }\n const allowance = await sodax.moneyMarket.isAllowanceValid(\n {\n token: token.address,\n amount: parseUnits(amount, token.decimals),\n },\n spokeProvider,\n );\n if (allowance.ok) {\n return allowance.value;\n }\n return false;\n },\n enabled: !!spokeProvider,\n });\n}\n","import { useSodaxContext } from '../shared/useSodaxContext';\nimport { useSpokeProvider } from '../provider/useSpokeProvider';\nimport type { SpokeChainId, XToken } from '@sodax/types';\nimport { parseUnits } from 'viem';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport type { Address } from '@sodax/sdk';\n\ninterface UseApproveReturn {\n approve: (amount: string) => Promise<boolean>;\n isLoading: boolean;\n error: Error | null;\n resetError: () => void;\n}\n\nexport function useApprove(token: XToken): UseApproveReturn {\n const { sodax } = useSodaxContext();\n const spokeProvider = useSpokeProvider(token.xChainId as SpokeChainId);\n const queryClient = useQueryClient();\n\n const {\n mutateAsync: approve,\n isPending,\n error,\n reset: resetError,\n } = useMutation({\n mutationFn: async (amount: string) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n const allowance = await sodax.moneyMarket.approve(\n token.address as Address,\n parseUnits(amount, token.decimals),\n spokeProvider.chainConfig.addresses.assetManager as Address,\n spokeProvider,\n );\n if (!allowance.ok) {\n throw new Error('Failed to approve tokens');\n }\n return allowance.ok;\n },\n onSuccess: () => {\n // Invalidate allowance query to refetch the new allowance\n queryClient.invalidateQueries({ queryKey: ['allowance', token.address] });\n },\n });\n\n return {\n approve,\n isLoading: isPending,\n error: error as Error | null,\n resetError,\n };\n}\n","import { EvmHubProvider, getHubChainConfig, type HubChainId } from '@sodax/sdk';\nimport { getXChainType } from '@sodax/wallet-sdk';\nimport { useMemo } from 'react';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport function useHubProvider(): EvmHubProvider | undefined {\n const { sodax } = useSodaxContext();\n const hubChainId = sodax.config?.hubProviderConfig?.chainConfig.chain.id;\n const hubRpcUrl = sodax.config?.hubProviderConfig?.hubRpcUrl;\n const xChainType = getXChainType(hubChainId);\n const hubProvider = useMemo(() => {\n if (xChainType === 'EVM' && hubChainId && hubRpcUrl) {\n // @ts-ignore\n const hubChainCfg = getHubChainConfig(hubChainId);\n\n if (!hubChainCfg) return undefined;\n\n return new EvmHubProvider({\n hubRpcUrl: hubRpcUrl,\n chainConfig: hubChainCfg,\n });\n }\n return undefined;\n }, [xChainType, hubChainId, hubRpcUrl]);\n\n return hubProvider;\n}\n","import type { ChainId, XToken } from '@sodax/types';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport { parseUnits } from 'viem';\nimport { useSpokeProvider } from '../provider/useSpokeProvider';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { SpokeChainId } from '@sodax/sdk';\ninterface BorrowResponse {\n ok: true;\n value: [`0x${string}`, `0x${string}`];\n}\n\n/**\n * Hook for borrowing tokens from the Sodax money market.\n *\n * This hook provides functionality to borrow tokens from the money market protocol,\n * handling the entire borrow process including transaction creation, submission,\n * and cross-chain communication.\n *\n * @example\n * ```typescript\n * const { mutateAsync: borrow, isPending, error } = useBorrow(hubToken, spokeChainId);\n * await borrow('100');\n * ```\n *\n * @throws {Error} When:\n * - spokeProvider is not available\n * - Transaction execution fails\n */\nexport function useBorrow(hubToken: XToken, spokeChainId: ChainId): UseMutationResult<BorrowResponse, Error, string> {\n const { sodax } = useSodaxContext();\n const spokeProvider = useSpokeProvider(spokeChainId as SpokeChainId);\n\n return useMutation<BorrowResponse, Error, string>({\n mutationFn: async (amount: string) => {\n if (!spokeProvider) {\n throw new Error('spokeProvider is not found');\n }\n\n const response = await sodax.moneyMarket.borrowAndSubmit(\n {\n token: hubToken.address,\n amount: parseUnits(amount, hubToken.decimals),\n },\n spokeProvider,\n );\n\n if (!response.ok) {\n throw new Error('Failed to borrow tokens');\n }\n\n console.log('Borrow transaction submitted:', response);\n return response;\n },\n });\n}\n","import type { SpokeChainId } from '@sodax/sdk';\nimport type { ChainId, XToken } from '@sodax/types';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport { parseUnits } from 'viem';\nimport { useSpokeProvider } from '../provider/useSpokeProvider';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\ninterface RepayResponse {\n ok: true;\n value: [`0x${string}`, `0x${string}`];\n}\n\n/**\n * Hook for repaying borrowed tokens to the Sodax money market.\n *\n * This hook provides functionality to repay borrowed tokens back to the money market protocol,\n * handling the entire repayment process including transaction creation, submission,\n * and cross-chain communication.\n *\n * @example\n * ```typescript\n * const { mutateAsync: repay, isPending, error } = useRepay(hubToken, spokeChainId);\n * await repay('100');\n * ```\n *\n * @throws {Error} When:\n * - spokeProvider is not available\n * - Transaction execution fails\n */\nexport function useRepay(hubToken: XToken, spokeChainId: ChainId): UseMutationResult<RepayResponse, Error, string> {\n const { sodax } = useSodaxContext();\n const spokeProvider = useSpokeProvider(spokeChainId as SpokeChainId);\n\n return useMutation<RepayResponse, Error, string>({\n mutationFn: async (amount: string) => {\n if (!spokeProvider) {\n throw new Error('spokeProvider is not found');\n }\n\n const response = await sodax.moneyMarket.repayAndSubmit(\n {\n token: hubToken.address,\n amount: parseUnits(amount, hubToken.decimals),\n },\n spokeProvider,\n );\n\n if (!response.ok) {\n throw new Error('Failed to repay tokens');\n }\n\n console.log('Repay transaction submitted:', response);\n return response;\n },\n });\n}\n","import type { SpokeChainId } from '@sodax/sdk';\nimport type { XToken } from '@sodax/types';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport { parseUnits } from 'viem';\nimport { useSpokeProvider } from '../provider/useSpokeProvider';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\ninterface SupplyResponse {\n ok: true;\n value: [`0x${string}`, `0x${string}`];\n}\n\n/**\n * Hook for supplying tokens to the Sodax money market.\n *\n * This hook provides functionality to supply tokens to the money market protocol,\n * handling the entire supply process including transaction creation, submission,\n * and cross-chain communication.\n *\n * @param {XToken} spokeToken - The token to supply on the spoke chain. Must be an XToken with valid address and chain information.\n *\n * @returns {UseMutationResult<SupplyResponse, Error, string>} A mutation result object with the following properties:\n * - mutateAsync: Function to execute the supply transaction\n * - isPending: Boolean indicating if a transaction is in progress\n * - error: Error object if the last transaction failed, null otherwise\n *\n * @example\n * ```typescript\n * const { mutateAsync: supply, isPending, error } = useSupply(spokeToken);\n * await supply('100');\n * ```\n *\n * @throws {Error} When:\n * - spokeProvider is not available\n */\nexport function useSupply(spokeToken: XToken): UseMutationResult<SupplyResponse, Error, string> {\n const { sodax } = useSodaxContext();\n const spokeProvider = useSpokeProvider(spokeToken.xChainId as SpokeChainId);\n\n return useMutation<SupplyResponse, Error, string>({\n mutationFn: async (amount: string) => {\n if (!spokeProvider) {\n throw new Error('spokeProvider is not found');\n }\n\n const response = await sodax.moneyMarket.supplyAndSubmit(\n {\n token: spokeToken.address,\n amount: parseUnits(amount, spokeToken.decimals),\n },\n spokeProvider,\n );\n\n if (!response.ok) {\n throw new Error('Failed to supply tokens');\n }\n\n console.log('Supply transaction submitted:', response);\n return response;\n },\n });\n}\n","import type { SpokeChainId } from '@sodax/sdk';\nimport type { ChainId, XToken } from '@sodax/types';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport { parseUnits } from 'viem';\nimport { useSpokeProvider } from '../provider/useSpokeProvider';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\ninterface WithdrawResponse {\n ok: true;\n value: [`0x${string}`, `0x${string}`];\n}\n\n/**\n * Hook for withdrawing supplied tokens from the Sodax money market.\n *\n * This hook provides functionality to withdraw previously supplied tokens from the money market protocol,\n * handling the entire withdrawal process including transaction creation, submission,\n * and cross-chain communication.\n *\n * @example\n * ```typescript\n * const { mutateAsync: withdraw, isPending, error } = useWithdraw(hubToken, spokeChainId);\n * await withdraw('100');\n * ```\n *\n * @throws {Error} When:\n * - spokeProvider is not available\n * - Transaction execution fails\n */\nexport function useWithdraw(\n hubToken: XToken,\n spokeChainId: ChainId,\n): UseMutationResult<WithdrawResponse, Error, string> {\n const { sodax } = useSodaxContext();\n const spokeProvider = useSpokeProvider(spokeChainId as SpokeChainId);\n\n return useMutation<WithdrawResponse, Error, string>({\n mutationFn: async (amount: string) => {\n if (!spokeProvider) {\n throw new Error('spokeProvider is not found');\n }\n\n const response = await sodax.moneyMarket.withdrawAndSubmit(\n {\n token: hubToken.address,\n amount: parseUnits(amount, hubToken.decimals),\n },\n spokeProvider,\n );\n\n if (!response.ok) {\n throw new Error('Failed to withdraw tokens');\n }\n\n console.log('Withdraw transaction submitted:', response);\n return response;\n },\n });\n}\n","import type { XToken, ChainId } from '@sodax/types';\n\nimport { hubAssets } from '@sodax/sdk';\nimport { CHAIN_IDS } from '@sodax/types';\n\nexport const allXTokens: XToken[] = [];\n\nObject.keys(hubAssets).forEach(xChainId => {\n const tokens = hubAssets[xChainId];\n\n Object.keys(tokens).forEach(tokenAddress => {\n const token = tokens[tokenAddress];\n allXTokens.push({\n xChainId: xChainId as ChainId,\n symbol: token.symbol,\n name: token.name,\n decimals: token.decimal,\n address: tokenAddress,\n });\n\n allXTokens.push({\n // @ts-ignore\n xChainId: CHAIN_IDS.includes(xChainId as ChainId) ? 'sonic' : 'sonic-blaze',\n symbol: token.symbol,\n name: token.name,\n decimals: token.decimal,\n address: token.vault,\n });\n });\n});\n\nexport const getSpokeTokenAddressByVault = (spokeChainId: ChainId, vault: string) => {\n const tokens = hubAssets[spokeChainId];\n\n const token = Object.keys(tokens).find(tokenAddress => tokens[tokenAddress].vault === vault);\n\n if (!token) {\n throw new Error('Token not found');\n }\n\n return token;\n};\n","import { type EvmHubProvider, EvmWalletAbstraction, type SpokeChainId } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook for retrieving the hub wallet address for a given spoke chain and address.\n *\n * This hook fetches the hub wallet address associated with a user's address on a specific spoke chain.\n * It uses the EvmWalletAbstraction to query the hub wallet address from the hub provider.\n *\n * @param spokeChainId - The chain ID of the spoke chain\n * @param address - The user's address on the spoke chain\n * @param hubProvider - The hub provider instance\n *\n * @returns {UseQueryResult<string | null>} A query result object containing:\n * - data: The hub wallet address or null if not found\n * - isLoading: Boolean indicating if the query is in progress\n * - error: Error object if the query failed, null otherwise\n *\n * @example\n * ```typescript\n * const { data: hubWalletAddress, isLoading, error } = useHubWalletAddress(spokeChainId, address, hubProvider);\n * ```\n */\n\nexport function useHubWalletAddress(\n spokeChainId: SpokeChainId,\n address: string | undefined,\n hubProvider: EvmHubProvider,\n): UseQueryResult<string | null> {\n return useQuery({\n queryKey: ['hubWallet', spokeChainId, address],\n queryFn: async () => {\n if (!address) return null;\n\n try {\n const hubWalletAddress = await EvmWalletAbstraction.getUserHubWalletAddress(\n spokeChainId,\n address as `0x${string}`,\n hubProvider,\n );\n return hubWalletAddress;\n } catch (error) {\n console.log('error', error);\n return null;\n }\n },\n enabled: !!address && !!hubProvider,\n });\n}\n","import { allXTokens } from '@/core';\nimport { getMoneyMarketConfig, type EvmHubProvider } from '@sodax/sdk';\nimport type { HubChainId, SpokeChainId } from '@sodax/types';\nimport { useXAccount, useWalletProvider } from '@sodax/wallet-sdk';\nimport type { ChainId } from '@sodax/types';\nimport { useQuery } from '@tanstack/react-query';\nimport { useHubProvider } from '../provider/useHubProvider';\nimport { useHubWalletAddress } from './useHubWalletAddress';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport function useUserReservesData(spokeChainId: ChainId) {\n const { sodax } = useSodaxContext();\n const hubChainId = (sodax.config?.hubProviderConfig?.chainConfig.chain.id ?? 'sonic') as HubChainId;\n const hubWalletProvider = useWalletProvider(hubChainId);\n const hubProvider = useHubProvider();\n const { address } = useXAccount(spokeChainId);\n const { data: hubWalletAddress } = useHubWalletAddress(\n spokeChainId as SpokeChainId,\n address,\n hubProvider as EvmHubProvider,\n );\n\n const { data: userReserves } = useQuery({\n queryKey: ['userReserves', hubWalletAddress],\n queryFn: async () => {\n if (!hubWalletProvider) {\n return;\n }\n\n if (!hubWalletAddress) {\n return;\n }\n\n const moneyMarketConfig = getMoneyMarketConfig(hubChainId);\n try {\n const [res] = await sodax.moneyMarket.getUserReservesData(\n hubWalletAddress as `0x${string}`,\n moneyMarketConfig.uiPoolDataProvider,\n moneyMarketConfig.poolAddressesProvider,\n );\n\n return res?.map(r => {\n return {\n ...r,\n token: allXTokens.find(t => t.address === r.underlyingAsset),\n };\n });\n } catch (error) {\n console.log('error', error);\n return;\n }\n },\n enabled: !!address && !!hubWalletProvider && !!hubWalletAddress,\n refetchInterval: 5000,\n });\n\n return userReserves;\n}\n","import type { IntentErrorResponse, IntentQuoteRequest, IntentQuoteResponse, Result } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook for fetching a quote for an intent-based swap.\n *\n * This hook provides real-time quote data for an intent-based swap.\n *\n * @param {IntentQuoteRequest | undefined} payload - The intent quote request parameters. If undefined, the query will be disabled.\n *\n * @returns {UseQueryResult<Result<IntentQuoteResponse, IntentErrorResponse> | undefined>} A query result object containing:\n * - data: The quote result from the solver\n * - isLoading: Boolean indicating if the quote is being fetched\n * - error: Error object if the quote request failed\n * - refetch: Function to manually trigger a quote refresh\n *\n * @example\n * ```typescript\n * const { data: quote, isLoading } = useQuote({\n * token_src: '0x...',\n * token_src_blockchain_id: '1',\n * token_dst: '0x...',\n * token_dst_blockchain_id: '2',\n * amount: '1000000000000000000',\n * quote_type: 'exact_input',\n * });\n *\n * if (isLoading) return <div>Loading quote...</div>;\n * if (quote) {\n * console.log('Quote received:', quote);\n * }\n * ```\n *\n * @remarks\n * - The quote is automatically refreshed every 3 seconds\n * - The query is disabled when payload is undefined\n * - Uses React Query for efficient caching and state management\n */\nexport const useQuote = (\n payload: IntentQuoteRequest | undefined,\n): UseQueryResult<Result<IntentQuoteResponse, IntentErrorResponse> | undefined> => {\n const { sodax } = useSodaxContext();\n return useQuery({\n queryKey: [payload],\n queryFn: async () => {\n if (!payload) {\n return undefined;\n }\n return sodax.solver.getQuote(payload);\n },\n enabled: !!payload,\n refetchInterval: 3000,\n });\n};\n","import { useSodaxContext } from '../shared/useSodaxContext';\nimport type {\n CreateIntentParams,\n SpokeChainId,\n IntentExecutionResponse,\n Result,\n IntentSubmitErrorCode,\n Intent,\n PacketData,\n IntentSubmitError,\n} from '@sodax/sdk';\nimport { useSpokeProvider } from '../provider/useSpokeProvider';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\n\ntype CreateIntentResult = Result<\n [IntentExecutionResponse, Intent, PacketData],\n IntentSubmitError<IntentSubmitErrorCode>\n>;\n\n/**\n * Hook for creating and submitting an intent order for cross-chain swaps.\n * Uses React Query's useMutation for better state management and caching.\n *\n * @param {SpokeChainId} chainId - The source chain ID where the swap will originate\n * @returns {UseMutationResult} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: createIntent, isPending } = useCreateIntentOrder('0xa4b1.arbitrum');\n *\n * const handleSwap = async () => {\n * const result = await createIntent({\n * token_src: '0x...',\n * token_src_blockchain_id: 'arbitrum',\n * token_dst: '0x...',\n * token_dst_blockchain_id: 'polygon',\n * amount: '1000000000000000000',\n * min_output_amount: '900000000000000000'\n * });\n * };\n * ```\n */\nexport function useCreateIntentOrder(\n chainId: SpokeChainId,\n): UseMutationResult<CreateIntentResult, Error, CreateIntentParams> {\n const { sodax } = useSodaxContext();\n const spokeProvider = useSpokeProvider(chainId);\n\n return useMutation<CreateIntentResult, Error, CreateIntentParams>({\n mutationFn: async (params: CreateIntentParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n return sodax.solver.createAndSubmitIntent(params, spokeProvider);\n },\n });\n}\n","import type { Hex, IntentErrorResponse, IntentStatusResponse, Result } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\n/**\n * Hook for monitoring the status of an intent-based swap.\n *\n * This hook provides real-time status updates for an intent-based swap transaction.\n *\n * @param {Hex} intent_tx_hash - The transaction hash of the intent order on the hub chain\n *\n * @returns {UseQueryResult<Result<IntentStatusResponse, IntentErrorResponse> | undefined>} A query result object containing:\n * - data: The status result from the solver\n * - isLoading: Boolean indicating if the status is being fetched\n * - error: Error object if the status request failed\n * - refetch: Function to manually trigger a status refresh\n *\n * @example\n * ```typescript\n * const { data: status, isLoading } = useStatus('0x...');\n *\n * if (isLoading) return <div>Loading status...</div>;\n * if (status?.ok) {\n * console.log('Status:', status.value);\n * }\n * ```\n *\n * @remarks\n * - The status is automatically refreshed every 3 seconds\n * - Uses React Query for efficient caching and state management\n */\n\nexport const useStatus = (\n intent_tx_hash: Hex,\n): UseQueryResult<Result<IntentStatusResponse, IntentErrorResponse> | undefined> => {\n const { sodax } = useSodaxContext();\n return useQuery({\n queryKey: [intent_tx_hash],\n queryFn: async () => {\n return sodax.solver.getStatus({ intent_tx_hash });\n },\n refetchInterval: 3000, // 3s\n });\n};\n","import type { ReactNode, ReactElement } from 'react';\nimport { Sodax, type SodaxConfig } from '@sodax/sdk';\nimport { SodaxContext } from '@/contexts';\nimport React from 'react';\n\ninterface SodaxProviderProps {\n children: ReactNode;\n testnet?: boolean;\n config: SodaxConfig;\n}\n\nexport const SodaxProvider = ({ children, testnet = false, config }: SodaxProviderProps): ReactElement => {\n const sodax = new Sodax(config);\n\n return <SodaxContext.Provider value={{ sodax, testnet }}>{children}</SodaxContext.Provider>;\n};\n"]}
@@ -0,0 +1,10 @@
1
+ import type { ReactNode, ReactElement } from 'react';
2
+ import { type SodaxConfig } from '@sodax/sdk';
3
+ interface SodaxProviderProps {
4
+ children: ReactNode;
5
+ testnet?: boolean;
6
+ config: SodaxConfig;
7
+ }
8
+ export declare const SodaxProvider: ({ children, testnet, config }: SodaxProviderProps) => ReactElement;
9
+ export {};
10
+ //# sourceMappingURL=SodaxProvider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SodaxProvider.d.ts","sourceRoot":"","sources":["../../src/providers/SodaxProvider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AACrD,OAAO,EAAS,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AAIrD,UAAU,kBAAkB;IAC1B,QAAQ,EAAE,SAAS,CAAC;IACpB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,MAAM,EAAE,WAAW,CAAC;CACrB;AAED,eAAO,MAAM,aAAa,kCAA2C,kBAAkB,KAAG,YAIzF,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { SodaxProvider } from './SodaxProvider';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/providers/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@sodax/dapp-kit",
3
+ "license": "MIT",
4
+ "version": "0.0.1-rc.1",
5
+ "description": "dapp-kit of New World",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "module": "dist/index.mjs",
9
+ "files": [
10
+ "dist",
11
+ "src"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/icon-project/sodax-frontend"
16
+ },
17
+ "dependencies": {
18
+ "viem": "^2.29.2",
19
+ "@sodax/sdk": "0.0.1-rc.2",
20
+ "@sodax/types": "1.0.0",
21
+ "@sodax/wallet-sdk": "0.0.1-rc.1"
22
+ },
23
+ "devDependencies": {
24
+ "@types/react": "^19.0.8",
25
+ "knip": "5.30.5",
26
+ "tsup": "^8.4.0",
27
+ "typescript": "5.5.4"
28
+ },
29
+ "peerDependencies": {
30
+ "@tanstack/react-query": "^5.66.9",
31
+ "react": "^19.0.0"
32
+ },
33
+ "engines": {
34
+ "node": ">=18.0.0"
35
+ },
36
+ "exports": {
37
+ "./package.json": "./package.json",
38
+ ".": {
39
+ "types": "./dist/index.d.ts",
40
+ "import": "./dist/index.mjs",
41
+ "require": "./dist/index.js"
42
+ }
43
+ },
44
+ "scripts": {
45
+ "build": "tsup",
46
+ "dev": "tsup --watch ./src",
47
+ "test": "tsc --noEmit",
48
+ "clean": "rm -rf dist && rm -rf node_modules && rm -rf .turbo",
49
+ "pretty": "biome format . --write",
50
+ "checkTs": "tsc --noEmit",
51
+ "knip": "knip",
52
+ "lint": "biome lint . --write"
53
+ }
54
+ }
@@ -0,0 +1,9 @@
1
+ import { createContext } from 'react';
2
+ import type { Sodax } from '@sodax/sdk';
3
+
4
+ export interface SodaxContextType {
5
+ sodax: Sodax;
6
+ testnet: boolean;
7
+ }
8
+
9
+ export const SodaxContext = createContext<SodaxContextType | null>(null);
@@ -0,0 +1,42 @@
1
+ import type { XToken, ChainId } from '@sodax/types';
2
+
3
+ import { hubAssets } from '@sodax/sdk';
4
+ import { CHAIN_IDS } from '@sodax/types';
5
+
6
+ export const allXTokens: XToken[] = [];
7
+
8
+ Object.keys(hubAssets).forEach(xChainId => {
9
+ const tokens = hubAssets[xChainId];
10
+
11
+ Object.keys(tokens).forEach(tokenAddress => {
12
+ const token = tokens[tokenAddress];
13
+ allXTokens.push({
14
+ xChainId: xChainId as ChainId,
15
+ symbol: token.symbol,
16
+ name: token.name,
17
+ decimals: token.decimal,
18
+ address: tokenAddress,
19
+ });
20
+
21
+ allXTokens.push({
22
+ // @ts-ignore
23
+ xChainId: CHAIN_IDS.includes(xChainId as ChainId) ? 'sonic' : 'sonic-blaze',
24
+ symbol: token.symbol,
25
+ name: token.name,
26
+ decimals: token.decimal,
27
+ address: token.vault,
28
+ });
29
+ });
30
+ });
31
+
32
+ export const getSpokeTokenAddressByVault = (spokeChainId: ChainId, vault: string) => {
33
+ const tokens = hubAssets[spokeChainId];
34
+
35
+ const token = Object.keys(tokens).find(tokenAddress => tokens[tokenAddress].vault === vault);
36
+
37
+ if (!token) {
38
+ throw new Error('Token not found');
39
+ }
40
+
41
+ return token;
42
+ };
@@ -0,0 +1,4 @@
1
+ export * from './shared';
2
+ export * from './provider';
3
+ export * from './mm';
4
+ export * from './swap';
@@ -0,0 +1,6 @@
1
+ export * from './useBorrow';
2
+ export * from './useRepay';
3
+ export * from './useSupply';
4
+ export * from './useWithdraw';
5
+ export * from './useUserReservesData';
6
+ export * from './useHubWalletAddress';
@@ -0,0 +1,55 @@
1
+ import type { ChainId, XToken } from '@sodax/types';
2
+ import { useMutation, type UseMutationResult } from '@tanstack/react-query';
3
+ import { parseUnits } from 'viem';
4
+ import { useSpokeProvider } from '../provider/useSpokeProvider';
5
+ import { useSodaxContext } from '../shared/useSodaxContext';
6
+ import type { SpokeChainId } from '@sodax/sdk';
7
+ interface BorrowResponse {
8
+ ok: true;
9
+ value: [`0x${string}`, `0x${string}`];
10
+ }
11
+
12
+ /**
13
+ * Hook for borrowing tokens from the Sodax money market.
14
+ *
15
+ * This hook provides functionality to borrow tokens from the money market protocol,
16
+ * handling the entire borrow process including transaction creation, submission,
17
+ * and cross-chain communication.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const { mutateAsync: borrow, isPending, error } = useBorrow(hubToken, spokeChainId);
22
+ * await borrow('100');
23
+ * ```
24
+ *
25
+ * @throws {Error} When:
26
+ * - spokeProvider is not available
27
+ * - Transaction execution fails
28
+ */
29
+ export function useBorrow(hubToken: XToken, spokeChainId: ChainId): UseMutationResult<BorrowResponse, Error, string> {
30
+ const { sodax } = useSodaxContext();
31
+ const spokeProvider = useSpokeProvider(spokeChainId as SpokeChainId);
32
+
33
+ return useMutation<BorrowResponse, Error, string>({
34
+ mutationFn: async (amount: string) => {
35
+ if (!spokeProvider) {
36
+ throw new Error('spokeProvider is not found');
37
+ }
38
+
39
+ const response = await sodax.moneyMarket.borrowAndSubmit(
40
+ {
41
+ token: hubToken.address,
42
+ amount: parseUnits(amount, hubToken.decimals),
43
+ },
44
+ spokeProvider,
45
+ );
46
+
47
+ if (!response.ok) {
48
+ throw new Error('Failed to borrow tokens');
49
+ }
50
+
51
+ console.log('Borrow transaction submitted:', response);
52
+ return response;
53
+ },
54
+ });
55
+ }
@@ -0,0 +1,49 @@
1
+ import { type EvmHubProvider, EvmWalletAbstraction, type SpokeChainId } from '@sodax/sdk';
2
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
3
+
4
+ /**
5
+ * Hook for retrieving the hub wallet address for a given spoke chain and address.
6
+ *
7
+ * This hook fetches the hub wallet address associated with a user's address on a specific spoke chain.
8
+ * It uses the EvmWalletAbstraction to query the hub wallet address from the hub provider.
9
+ *
10
+ * @param spokeChainId - The chain ID of the spoke chain
11
+ * @param address - The user's address on the spoke chain
12
+ * @param hubProvider - The hub provider instance
13
+ *
14
+ * @returns {UseQueryResult<string | null>} A query result object containing:
15
+ * - data: The hub wallet address or null if not found
16
+ * - isLoading: Boolean indicating if the query is in progress
17
+ * - error: Error object if the query failed, null otherwise
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const { data: hubWalletAddress, isLoading, error } = useHubWalletAddress(spokeChainId, address, hubProvider);
22
+ * ```
23
+ */
24
+
25
+ export function useHubWalletAddress(
26
+ spokeChainId: SpokeChainId,
27
+ address: string | undefined,
28
+ hubProvider: EvmHubProvider,
29
+ ): UseQueryResult<string | null> {
30
+ return useQuery({
31
+ queryKey: ['hubWallet', spokeChainId, address],
32
+ queryFn: async () => {
33
+ if (!address) return null;
34
+
35
+ try {
36
+ const hubWalletAddress = await EvmWalletAbstraction.getUserHubWalletAddress(
37
+ spokeChainId,
38
+ address as `0x${string}`,
39
+ hubProvider,
40
+ );
41
+ return hubWalletAddress;
42
+ } catch (error) {
43
+ console.log('error', error);
44
+ return null;
45
+ }
46
+ },
47
+ enabled: !!address && !!hubProvider,
48
+ });
49
+ }