@shogun-sdk/swap 0.0.2-test.4 → 0.0.2-test.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core.cjs +1013 -157
- package/dist/core.d.cts +4 -136
- package/dist/core.d.ts +4 -136
- package/dist/core.js +1012 -129
- package/dist/index-BGHbFEV3.d.cts +401 -0
- package/dist/index-DB1gT72l.d.ts +401 -0
- package/dist/index.cjs +1001 -527
- package/dist/index.d.cts +4 -9
- package/dist/index.d.ts +4 -9
- package/dist/index.js +1000 -496
- package/dist/react.cjs +1557 -485
- package/dist/react.d.cts +285 -88
- package/dist/react.d.ts +285 -88
- package/dist/react.js +1550 -468
- package/dist/{wallet-MmUIz8GE.d.cts → wallet-B9bKceyN.d.cts} +3 -3
- package/dist/{wallet-MmUIz8GE.d.ts → wallet-B9bKceyN.d.ts} +3 -3
- package/dist/wallet-adapter.cjs +25659 -27
- package/dist/wallet-adapter.d.cts +1 -2
- package/dist/wallet-adapter.d.ts +1 -2
- package/dist/wallet-adapter.js +25679 -16
- package/package.json +44 -14
- package/dist/execute-FaLLPp1i.d.cts +0 -147
- package/dist/execute-HX1fQ7wG.d.ts +0 -147
package/dist/react.cjs
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
9
|
var __export = (target, all) => {
|
|
7
10
|
for (var name in all)
|
|
8
11
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -15,107 +18,49 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
18
|
}
|
|
16
19
|
return to;
|
|
17
20
|
};
|
|
21
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
22
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
23
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
24
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
25
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
26
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
27
|
+
mod
|
|
28
|
+
));
|
|
18
29
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
19
31
|
|
|
20
32
|
// src/react/index.ts
|
|
21
33
|
var react_exports = {};
|
|
22
34
|
__export(react_exports, {
|
|
23
|
-
|
|
24
|
-
|
|
35
|
+
ChainId: () => ChainId,
|
|
36
|
+
OrderExecutionType: () => OrderExecutionType,
|
|
37
|
+
SupportedChains: () => SupportedChains,
|
|
38
|
+
SwapProvider: () => SwapProvider,
|
|
39
|
+
buildQuoteParams: () => buildQuoteParams,
|
|
40
|
+
isEvmChain: () => isEvmChain,
|
|
25
41
|
useBalances: () => useBalances,
|
|
26
|
-
|
|
42
|
+
useCancelOrder: () => useCancelOrder,
|
|
43
|
+
useExecuteTransaction: () => useExecuteTransaction,
|
|
44
|
+
useOrders: () => useOrders,
|
|
27
45
|
useQuote: () => useQuote,
|
|
28
|
-
|
|
46
|
+
useSwap: () => useSwap,
|
|
47
|
+
useTokenList: () => useTokenList,
|
|
48
|
+
useTokensData: () => useTokensData
|
|
29
49
|
});
|
|
30
50
|
module.exports = __toCommonJS(react_exports);
|
|
31
51
|
|
|
32
|
-
// src/react/
|
|
52
|
+
// src/react/SwapProvider.tsx
|
|
33
53
|
var import_react = require("react");
|
|
34
54
|
|
|
35
|
-
// src/core/
|
|
36
|
-
var
|
|
37
|
-
|
|
38
|
-
return (0, import_intents_sdk.getTokenList)(params);
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// src/react/useTokenList.ts
|
|
42
|
-
var tokenCache = /* @__PURE__ */ new Map();
|
|
43
|
-
function useTokenList(params) {
|
|
44
|
-
const [data, setData] = (0, import_react.useState)(null);
|
|
45
|
-
const [loading, setLoading] = (0, import_react.useState)(false);
|
|
46
|
-
const [error, setError] = (0, import_react.useState)(null);
|
|
47
|
-
const controllerRef = (0, import_react.useRef)(null);
|
|
48
|
-
const debounceRef = (0, import_react.useRef)(null);
|
|
49
|
-
const debounceMs = params.debounceMs ?? 250;
|
|
50
|
-
const cacheKey = (0, import_react.useMemo)(() => {
|
|
51
|
-
return JSON.stringify({
|
|
52
|
-
q: params.q?.trim().toLowerCase() ?? "",
|
|
53
|
-
networkId: params.networkId ?? "all",
|
|
54
|
-
page: params.page ?? 1,
|
|
55
|
-
limit: params.limit ?? 50
|
|
56
|
-
});
|
|
57
|
-
}, [params.q, params.networkId, params.page, params.limit]);
|
|
58
|
-
async function fetchTokens(signal) {
|
|
59
|
-
if (tokenCache.has(cacheKey)) {
|
|
60
|
-
setData(tokenCache.get(cacheKey));
|
|
61
|
-
setLoading(false);
|
|
62
|
-
setError(null);
|
|
63
|
-
return;
|
|
64
|
-
}
|
|
65
|
-
try {
|
|
66
|
-
setLoading(true);
|
|
67
|
-
const result = await getTokenList({ ...params, signal });
|
|
68
|
-
tokenCache.set(cacheKey, result);
|
|
69
|
-
setData(result);
|
|
70
|
-
setError(null);
|
|
71
|
-
} catch (err) {
|
|
72
|
-
if (err.name !== "AbortError") {
|
|
73
|
-
const e = err instanceof Error ? err : new Error("Unknown error while fetching tokens");
|
|
74
|
-
setError(e);
|
|
75
|
-
}
|
|
76
|
-
} finally {
|
|
77
|
-
setLoading(false);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
(0, import_react.useEffect)(() => {
|
|
81
|
-
if (!params.q && !params.networkId) return;
|
|
82
|
-
if (debounceRef.current) clearTimeout(debounceRef.current);
|
|
83
|
-
if (controllerRef.current) controllerRef.current.abort();
|
|
84
|
-
const controller = new AbortController();
|
|
85
|
-
controllerRef.current = controller;
|
|
86
|
-
debounceRef.current = setTimeout(() => {
|
|
87
|
-
fetchTokens(controller.signal);
|
|
88
|
-
}, debounceMs);
|
|
89
|
-
return () => {
|
|
90
|
-
controller.abort();
|
|
91
|
-
if (debounceRef.current) clearTimeout(debounceRef.current);
|
|
92
|
-
};
|
|
93
|
-
}, [cacheKey, debounceMs]);
|
|
94
|
-
return (0, import_react.useMemo)(
|
|
95
|
-
() => ({
|
|
96
|
-
/** Current fetched data (cached when possible) */
|
|
97
|
-
data,
|
|
98
|
-
/** Whether a request is in progress */
|
|
99
|
-
loading,
|
|
100
|
-
/** Error object if a request failed */
|
|
101
|
-
error,
|
|
102
|
-
/** Manually refetch the token list */
|
|
103
|
-
refetch: () => fetchTokens(),
|
|
104
|
-
/** Clear all cached token results (shared across hook instances) */
|
|
105
|
-
clearCache: () => tokenCache.clear()
|
|
106
|
-
}),
|
|
107
|
-
[data, loading, error]
|
|
108
|
-
);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
// src/react/useExecuteOrder.ts
|
|
112
|
-
var import_react2 = require("react");
|
|
55
|
+
// src/core/getQuote.ts
|
|
56
|
+
var import_intents_sdk3 = require("@shogun-sdk/intents-sdk");
|
|
57
|
+
var import_viem2 = require("viem");
|
|
113
58
|
|
|
114
|
-
// src/core/
|
|
115
|
-
var
|
|
116
|
-
var import_viem3 = require("viem");
|
|
59
|
+
// src/core/execute/normalizeNative.ts
|
|
60
|
+
var import_intents_sdk2 = require("@shogun-sdk/intents-sdk");
|
|
117
61
|
|
|
118
62
|
// src/utils/address.ts
|
|
63
|
+
var import_viem = require("viem");
|
|
119
64
|
var NATIVE_TOKEN = {
|
|
120
65
|
ETH: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
|
|
121
66
|
SOL: "So11111111111111111111111111111111111111111",
|
|
@@ -126,13 +71,32 @@ var isNativeAddress = (tokenAddress) => {
|
|
|
126
71
|
const normalizedTokenAddress = tokenAddress.toLowerCase();
|
|
127
72
|
return !!tokenAddress && NATIVE_ADDRESSES.includes(normalizedTokenAddress);
|
|
128
73
|
};
|
|
74
|
+
function normalizeEvmTokenAddress(address) {
|
|
75
|
+
const lower = address.toLowerCase();
|
|
76
|
+
return lower === NATIVE_TOKEN.ETH.toLowerCase() ? import_viem.zeroAddress : address;
|
|
77
|
+
}
|
|
129
78
|
|
|
130
79
|
// src/utils/chain.ts
|
|
131
|
-
var
|
|
132
|
-
var SOLANA_CHAIN_ID =
|
|
133
|
-
var
|
|
80
|
+
var import_intents_sdk = require("@shogun-sdk/intents-sdk");
|
|
81
|
+
var SOLANA_CHAIN_ID = import_intents_sdk.ChainID.Solana;
|
|
82
|
+
var CURRENT_SUPPORTED = [
|
|
83
|
+
import_intents_sdk.ChainID.Solana,
|
|
84
|
+
import_intents_sdk.ChainID.BSC,
|
|
85
|
+
import_intents_sdk.ChainID.Base,
|
|
86
|
+
import_intents_sdk.ChainID.MONAD
|
|
87
|
+
];
|
|
88
|
+
var ChainId = Object.entries(import_intents_sdk.ChainID).reduce(
|
|
89
|
+
(acc, [key, value]) => {
|
|
90
|
+
if (typeof value === "number" && CURRENT_SUPPORTED.includes(value)) {
|
|
91
|
+
acc[key] = value;
|
|
92
|
+
}
|
|
93
|
+
return acc;
|
|
94
|
+
},
|
|
95
|
+
{}
|
|
96
|
+
);
|
|
97
|
+
var SupportedChainsInternal = [
|
|
134
98
|
{
|
|
135
|
-
id:
|
|
99
|
+
id: import_intents_sdk.ChainID.Arbitrum,
|
|
136
100
|
name: "Arbitrum",
|
|
137
101
|
isEVM: true,
|
|
138
102
|
wrapped: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
|
|
@@ -141,7 +105,7 @@ var SupportedChains = [
|
|
|
141
105
|
tokenAddress: NATIVE_TOKEN.ETH
|
|
142
106
|
},
|
|
143
107
|
{
|
|
144
|
-
id:
|
|
108
|
+
id: import_intents_sdk.ChainID.Optimism,
|
|
145
109
|
name: "Optimism",
|
|
146
110
|
isEVM: true,
|
|
147
111
|
wrapped: "0x4200000000000000000000000000000000000006",
|
|
@@ -150,7 +114,7 @@ var SupportedChains = [
|
|
|
150
114
|
tokenAddress: NATIVE_TOKEN.ETH
|
|
151
115
|
},
|
|
152
116
|
{
|
|
153
|
-
id:
|
|
117
|
+
id: import_intents_sdk.ChainID.Base,
|
|
154
118
|
name: "Base",
|
|
155
119
|
isEVM: true,
|
|
156
120
|
wrapped: "0x4200000000000000000000000000000000000006",
|
|
@@ -159,7 +123,7 @@ var SupportedChains = [
|
|
|
159
123
|
tokenAddress: NATIVE_TOKEN.ETH
|
|
160
124
|
},
|
|
161
125
|
{
|
|
162
|
-
id:
|
|
126
|
+
id: import_intents_sdk.ChainID.Hyperliquid,
|
|
163
127
|
name: "Hyperliquid",
|
|
164
128
|
isEVM: true,
|
|
165
129
|
wrapped: "0x5555555555555555555555555555555555555555",
|
|
@@ -168,7 +132,7 @@ var SupportedChains = [
|
|
|
168
132
|
tokenAddress: NATIVE_TOKEN.ETH
|
|
169
133
|
},
|
|
170
134
|
{
|
|
171
|
-
id:
|
|
135
|
+
id: import_intents_sdk.ChainID.BSC,
|
|
172
136
|
name: "BSC",
|
|
173
137
|
isEVM: true,
|
|
174
138
|
wrapped: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",
|
|
@@ -184,8 +148,21 @@ var SupportedChains = [
|
|
|
184
148
|
symbol: "SOL",
|
|
185
149
|
decimals: 9,
|
|
186
150
|
tokenAddress: NATIVE_TOKEN.SOL
|
|
151
|
+
},
|
|
152
|
+
{
|
|
153
|
+
id: import_intents_sdk.ChainID.MONAD,
|
|
154
|
+
name: "Monad",
|
|
155
|
+
isEVM: true,
|
|
156
|
+
wrapped: "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
|
|
157
|
+
symbol: "MON",
|
|
158
|
+
decimals: 18,
|
|
159
|
+
tokenAddress: NATIVE_TOKEN.ETH
|
|
187
160
|
}
|
|
188
161
|
];
|
|
162
|
+
var SupportedChains = SupportedChainsInternal.filter(
|
|
163
|
+
(c) => CURRENT_SUPPORTED.includes(c.id)
|
|
164
|
+
);
|
|
165
|
+
var isEvmChain = import_intents_sdk.isEvmChain;
|
|
189
166
|
|
|
190
167
|
// src/utils/viem.ts
|
|
191
168
|
function isViemWalletClient(wallet) {
|
|
@@ -213,10 +190,198 @@ function serializeBigIntsToStrings(obj) {
|
|
|
213
190
|
return obj;
|
|
214
191
|
}
|
|
215
192
|
|
|
193
|
+
// src/core/execute/normalizeNative.ts
|
|
194
|
+
function normalizeNative(chainId, address) {
|
|
195
|
+
if ((0, import_intents_sdk2.isEvmChain)(chainId) && isNativeAddress(address)) {
|
|
196
|
+
const chain = SupportedChains.find((c) => c.id === chainId);
|
|
197
|
+
if (!chain?.wrapped)
|
|
198
|
+
throw new Error(`Wrapped token not found for chainId ${chainId}`);
|
|
199
|
+
return chain.wrapped;
|
|
200
|
+
}
|
|
201
|
+
return address;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// src/core/getQuote.ts
|
|
205
|
+
async function getQuote(params) {
|
|
206
|
+
const amount = BigInt(params.amount);
|
|
207
|
+
if (!params.tokenIn?.address || !params.tokenOut?.address) {
|
|
208
|
+
throw new Error("Both tokenIn and tokenOut must include an address.");
|
|
209
|
+
}
|
|
210
|
+
if (!params.sourceChainId || !params.destChainId) {
|
|
211
|
+
throw new Error("Both sourceChainId and destChainId are required.");
|
|
212
|
+
}
|
|
213
|
+
if (amount <= 0n) {
|
|
214
|
+
throw new Error("Amount must be greater than 0.");
|
|
215
|
+
}
|
|
216
|
+
const normalizedTokenIn = normalizeNative(params.sourceChainId, params.tokenIn.address);
|
|
217
|
+
const data = await import_intents_sdk3.QuoteProvider.getQuote({
|
|
218
|
+
sourceChainId: params.sourceChainId,
|
|
219
|
+
destChainId: params.destChainId,
|
|
220
|
+
tokenIn: normalizedTokenIn,
|
|
221
|
+
tokenOut: params.tokenOut.address,
|
|
222
|
+
amount
|
|
223
|
+
});
|
|
224
|
+
const slippagePercent = Math.min(Math.max(params.slippage ?? 0.5, 0), 50);
|
|
225
|
+
let warning;
|
|
226
|
+
if (slippagePercent > 10) {
|
|
227
|
+
warning = `\u26A0\uFE0F High slippage tolerance (${slippagePercent.toFixed(2)}%) \u2014 price may vary significantly.`;
|
|
228
|
+
}
|
|
229
|
+
const estimatedAmountOut = BigInt(data.estimatedAmountOut);
|
|
230
|
+
const slippageBps = BigInt(Math.round(slippagePercent * 100));
|
|
231
|
+
const estimatedAmountOutAfterSlippage = estimatedAmountOut * (10000n - slippageBps) / 10000n;
|
|
232
|
+
const pricePerTokenOutInUsd = data.estimatedAmountOutUsd / Number(data.estimatedAmountOut);
|
|
233
|
+
const amountOutUsdAfterSlippage = Number(estimatedAmountOutAfterSlippage) * pricePerTokenOutInUsd;
|
|
234
|
+
const minStablecoinsAmountValue = BigInt(data.estimatedAmountInAsMinStablecoinAmount);
|
|
235
|
+
const minStablecoinsAmountAfterSlippage = minStablecoinsAmountValue * (10000n - slippageBps) / 10000n;
|
|
236
|
+
const pricePerInputToken = estimatedAmountOut * 10n ** BigInt(params.tokenIn.decimals ?? 18) / BigInt(params.amount);
|
|
237
|
+
return {
|
|
238
|
+
amountOut: estimatedAmountOutAfterSlippage,
|
|
239
|
+
amountOutUsd: amountOutUsdAfterSlippage,
|
|
240
|
+
amountInUsd: data.amountInUsd,
|
|
241
|
+
// Input USD stays the same
|
|
242
|
+
minStablecoinsAmount: minStablecoinsAmountAfterSlippage,
|
|
243
|
+
tokenIn: {
|
|
244
|
+
address: params.tokenIn.address,
|
|
245
|
+
decimals: params.tokenIn.decimals ?? 18,
|
|
246
|
+
chainId: params.sourceChainId
|
|
247
|
+
},
|
|
248
|
+
tokenOut: {
|
|
249
|
+
address: params.tokenOut.address,
|
|
250
|
+
decimals: params.tokenOut.decimals ?? 18,
|
|
251
|
+
chainId: params.destChainId
|
|
252
|
+
},
|
|
253
|
+
amountIn: BigInt(params.amount),
|
|
254
|
+
pricePerInputToken,
|
|
255
|
+
slippage: slippagePercent,
|
|
256
|
+
internal: {
|
|
257
|
+
...data,
|
|
258
|
+
estimatedAmountOutReduced: estimatedAmountOutAfterSlippage,
|
|
259
|
+
estimatedAmountOutUsdReduced: amountOutUsdAfterSlippage
|
|
260
|
+
},
|
|
261
|
+
warning
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
function buildQuoteParams({
|
|
265
|
+
tokenIn,
|
|
266
|
+
tokenOut,
|
|
267
|
+
sourceChainId,
|
|
268
|
+
destChainId,
|
|
269
|
+
amount,
|
|
270
|
+
slippage
|
|
271
|
+
}) {
|
|
272
|
+
return {
|
|
273
|
+
tokenIn,
|
|
274
|
+
tokenOut,
|
|
275
|
+
sourceChainId,
|
|
276
|
+
destChainId,
|
|
277
|
+
amount: (0, import_viem2.parseUnits)(amount.toString(), tokenIn.decimals ?? 18).toString(),
|
|
278
|
+
slippage
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// src/core/getBalances.ts
|
|
283
|
+
var import_intents_sdk4 = require("@shogun-sdk/intents-sdk");
|
|
284
|
+
async function getBalances(params, options) {
|
|
285
|
+
const { addresses, cursorEvm, cursorSvm } = params;
|
|
286
|
+
const { signal } = options ?? {};
|
|
287
|
+
if (!addresses?.evm && !addresses?.svm) {
|
|
288
|
+
throw new Error("At least one address (EVM or SVM) must be provided.");
|
|
289
|
+
}
|
|
290
|
+
const payload = JSON.stringify({
|
|
291
|
+
addresses,
|
|
292
|
+
cursorEvm,
|
|
293
|
+
cursorSvm
|
|
294
|
+
});
|
|
295
|
+
const start = performance.now();
|
|
296
|
+
const response = await fetch(`${import_intents_sdk4.TOKEN_SEARCH_API_BASE_URL}/tokens/balances`, {
|
|
297
|
+
method: "POST",
|
|
298
|
+
headers: {
|
|
299
|
+
accept: "application/json",
|
|
300
|
+
"Content-Type": "application/json"
|
|
301
|
+
},
|
|
302
|
+
body: payload,
|
|
303
|
+
signal
|
|
304
|
+
}).catch((err) => {
|
|
305
|
+
if (err.name === "AbortError") {
|
|
306
|
+
throw new Error("Balance request was cancelled.");
|
|
307
|
+
}
|
|
308
|
+
throw err;
|
|
309
|
+
});
|
|
310
|
+
if (!response.ok) {
|
|
311
|
+
const text = await response.text().catch(() => "");
|
|
312
|
+
throw new Error(`Failed to fetch balances: ${response.status} ${text}`);
|
|
313
|
+
}
|
|
314
|
+
const data = await response.json().catch(() => {
|
|
315
|
+
throw new Error("Invalid JSON response from balances API.");
|
|
316
|
+
});
|
|
317
|
+
const duration = (performance.now() - start).toFixed(1);
|
|
318
|
+
if (process.env.NODE_ENV !== "production") {
|
|
319
|
+
console.debug(`[Shogun SDK] Fetched balances in ${duration}ms`);
|
|
320
|
+
}
|
|
321
|
+
const evmItems = data.evm?.items ?? [];
|
|
322
|
+
const svmItems = data.svm?.items ?? [];
|
|
323
|
+
const combined = [...evmItems, ...svmItems];
|
|
324
|
+
const filtered = combined.filter(
|
|
325
|
+
(b) => CURRENT_SUPPORTED.includes(b.chainId)
|
|
326
|
+
);
|
|
327
|
+
return {
|
|
328
|
+
results: filtered,
|
|
329
|
+
nextCursorEvm: data.evm?.cursor ?? null,
|
|
330
|
+
nextCursorSvm: data.svm?.cursor ?? null
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// src/core/token-list.ts
|
|
335
|
+
var import_intents_sdk5 = require("@shogun-sdk/intents-sdk");
|
|
336
|
+
async function getTokenList(params) {
|
|
337
|
+
const url = new URL(`${import_intents_sdk5.TOKEN_SEARCH_API_BASE_URL}/tokens/search`);
|
|
338
|
+
if (params.q) url.searchParams.append("q", params.q);
|
|
339
|
+
if (params.networkId) url.searchParams.append("networkId", String(params.networkId));
|
|
340
|
+
if (params.page) url.searchParams.append("page", String(params.page));
|
|
341
|
+
if (params.limit) url.searchParams.append("limit", String(params.limit));
|
|
342
|
+
const res = await fetch(url.toString(), {
|
|
343
|
+
signal: params.signal
|
|
344
|
+
});
|
|
345
|
+
if (!res.ok) {
|
|
346
|
+
throw new Error(`Failed to fetch tokens: ${res.status} ${res.statusText}`);
|
|
347
|
+
}
|
|
348
|
+
const data = await res.json();
|
|
349
|
+
const filteredResults = data.results.filter(
|
|
350
|
+
(token) => CURRENT_SUPPORTED.includes(token.chainId)
|
|
351
|
+
);
|
|
352
|
+
return {
|
|
353
|
+
...data,
|
|
354
|
+
results: filteredResults,
|
|
355
|
+
count: filteredResults.length
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// src/core/token.ts
|
|
360
|
+
var import_intents_sdk6 = require("@shogun-sdk/intents-sdk");
|
|
361
|
+
async function getTokensData(addresses) {
|
|
362
|
+
if (!addresses?.length) return [];
|
|
363
|
+
const response = await fetch(`${import_intents_sdk6.TOKEN_SEARCH_API_BASE_URL}/tokens/tokens`, {
|
|
364
|
+
method: "POST",
|
|
365
|
+
headers: {
|
|
366
|
+
"Content-Type": "application/json",
|
|
367
|
+
accept: "*/*"
|
|
368
|
+
},
|
|
369
|
+
body: JSON.stringify({ addresses })
|
|
370
|
+
});
|
|
371
|
+
if (!response.ok) {
|
|
372
|
+
throw new Error(`Failed to fetch token data: ${response.statusText}`);
|
|
373
|
+
}
|
|
374
|
+
const data = await response.json();
|
|
375
|
+
const filtered = data.filter((t) => CURRENT_SUPPORTED.includes(Number(t.chainId)));
|
|
376
|
+
return filtered;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// src/core/execute/execute.ts
|
|
380
|
+
var import_intents_sdk12 = require("@shogun-sdk/intents-sdk");
|
|
381
|
+
var import_viem7 = require("viem");
|
|
382
|
+
|
|
216
383
|
// src/wallet-adapter/evm-wallet-adapter/adapter.ts
|
|
217
|
-
var
|
|
218
|
-
var import_utils = require("ethers/lib/utils.js");
|
|
219
|
-
var import_viem = require("viem");
|
|
384
|
+
var import_viem3 = require("viem");
|
|
220
385
|
function isEVMTransaction(tx) {
|
|
221
386
|
return typeof tx.from === "string";
|
|
222
387
|
}
|
|
@@ -234,15 +399,26 @@ var adaptViemWallet = (wallet) => {
|
|
|
234
399
|
if (!isEVMTransaction(transaction)) {
|
|
235
400
|
throw new Error("Expected EVMTransaction but got SolanaTransaction");
|
|
236
401
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
402
|
+
if (wallet.transport.type === "http") {
|
|
403
|
+
const request = await wallet.prepareTransactionRequest({
|
|
404
|
+
to: transaction.to,
|
|
405
|
+
data: transaction.data,
|
|
406
|
+
value: transaction.value,
|
|
407
|
+
chain: wallet.chain
|
|
408
|
+
});
|
|
409
|
+
const serializedTransaction = await wallet.signTransaction(request);
|
|
410
|
+
const tx = await wallet.sendRawTransaction({ serializedTransaction });
|
|
411
|
+
return tx;
|
|
412
|
+
} else {
|
|
413
|
+
const hash = await wallet.sendTransaction({
|
|
414
|
+
to: transaction.to,
|
|
415
|
+
data: transaction.data,
|
|
416
|
+
value: transaction.value,
|
|
417
|
+
chain: wallet.chain,
|
|
418
|
+
account: wallet.account
|
|
419
|
+
});
|
|
420
|
+
return hash;
|
|
421
|
+
}
|
|
246
422
|
};
|
|
247
423
|
const switchChain = async (chainId) => {
|
|
248
424
|
try {
|
|
@@ -265,67 +441,96 @@ var adaptViemWallet = (wallet) => {
|
|
|
265
441
|
if (!addr) throw new Error("No address found");
|
|
266
442
|
return addr;
|
|
267
443
|
};
|
|
444
|
+
const readContract = async ({
|
|
445
|
+
address: address2,
|
|
446
|
+
abi,
|
|
447
|
+
functionName,
|
|
448
|
+
args = []
|
|
449
|
+
}) => {
|
|
450
|
+
const publicClient = wallet.extend(import_viem3.publicActions);
|
|
451
|
+
return await publicClient.readContract({
|
|
452
|
+
address: address2,
|
|
453
|
+
abi,
|
|
454
|
+
functionName,
|
|
455
|
+
args
|
|
456
|
+
});
|
|
457
|
+
};
|
|
268
458
|
return {
|
|
269
459
|
vmType: "EVM" /* EVM */,
|
|
270
|
-
transport: (0,
|
|
460
|
+
transport: (0, import_viem3.custom)(wallet.transport),
|
|
271
461
|
getChainId: async () => wallet.getChainId(),
|
|
272
462
|
address,
|
|
273
463
|
sendTransaction,
|
|
274
464
|
signTypedData,
|
|
275
|
-
switchChain
|
|
465
|
+
switchChain,
|
|
466
|
+
readContract
|
|
276
467
|
};
|
|
277
468
|
};
|
|
278
469
|
|
|
279
|
-
// src/core/
|
|
280
|
-
var
|
|
281
|
-
var
|
|
282
|
-
|
|
283
|
-
// src/core/executeOrder/normalizeNative.ts
|
|
284
|
-
var import_intents_sdk3 = require("@shogun-sdk/intents-sdk");
|
|
285
|
-
function normalizeNative(chainId, address) {
|
|
286
|
-
if ((0, import_intents_sdk3.isEvmChain)(chainId) && isNativeAddress(address)) {
|
|
287
|
-
const chain = SupportedChains.find((c) => c.id === chainId);
|
|
288
|
-
if (!chain?.wrapped)
|
|
289
|
-
throw new Error(`Wrapped token not found for chainId ${chainId}`);
|
|
290
|
-
return chain.wrapped;
|
|
291
|
-
}
|
|
292
|
-
return address;
|
|
293
|
-
}
|
|
470
|
+
// src/core/execute/handleEvmExecution.ts
|
|
471
|
+
var import_intents_sdk10 = require("@shogun-sdk/intents-sdk");
|
|
472
|
+
var import_viem6 = require("viem");
|
|
294
473
|
|
|
295
|
-
// src/core/
|
|
474
|
+
// src/core/execute/stageMessages.ts
|
|
296
475
|
var DEFAULT_STAGE_MESSAGES = {
|
|
297
476
|
processing: "Preparing transaction for execution",
|
|
298
477
|
approving: "Approving token allowance",
|
|
299
478
|
approved: "Token approved successfully",
|
|
300
|
-
signing: "Signing
|
|
301
|
-
submitting: "Submitting
|
|
302
|
-
|
|
303
|
-
|
|
479
|
+
signing: "Signing transaction for submission",
|
|
480
|
+
submitting: "Submitting transaction",
|
|
481
|
+
initiated: "Transaction initiated.",
|
|
482
|
+
success: "Transaction Executed successfully",
|
|
483
|
+
success_limit: "Limit order has been submitted successfully.",
|
|
484
|
+
shogun_processing: "Shogun is processing your transaction",
|
|
485
|
+
error: "Transaction failed during submission"
|
|
304
486
|
};
|
|
305
487
|
|
|
306
|
-
// src/core/
|
|
307
|
-
var
|
|
488
|
+
// src/core/execute/buildOrder.ts
|
|
489
|
+
var import_intents_sdk7 = require("@shogun-sdk/intents-sdk");
|
|
490
|
+
var import_viem4 = require("viem");
|
|
491
|
+
|
|
492
|
+
// src/utils/order.ts
|
|
493
|
+
var OrderExecutionType = /* @__PURE__ */ ((OrderExecutionType2) => {
|
|
494
|
+
OrderExecutionType2["LIMIT"] = "limit";
|
|
495
|
+
OrderExecutionType2["MARKET"] = "market";
|
|
496
|
+
return OrderExecutionType2;
|
|
497
|
+
})(OrderExecutionType || {});
|
|
498
|
+
|
|
499
|
+
// src/core/execute/buildOrder.ts
|
|
308
500
|
async function buildOrder({
|
|
309
501
|
quote,
|
|
310
502
|
accountAddress,
|
|
311
503
|
destination,
|
|
312
504
|
deadline,
|
|
313
|
-
isSingleChain
|
|
505
|
+
isSingleChain,
|
|
506
|
+
orderType,
|
|
507
|
+
options
|
|
314
508
|
}) {
|
|
315
509
|
const { tokenIn, tokenOut } = quote;
|
|
510
|
+
let amountOutMin = BigInt(quote.internal.estimatedAmountOutReduced);
|
|
511
|
+
if (orderType === "limit" /* LIMIT */ && options && "executionPrice" in options) {
|
|
512
|
+
const executionPrice = Number(options.executionPrice);
|
|
513
|
+
if (Number.isFinite(executionPrice) && executionPrice > 0) {
|
|
514
|
+
const decimalsIn = tokenIn.decimals ?? 18;
|
|
515
|
+
const decimalsOut = tokenOut.decimals ?? 18;
|
|
516
|
+
const formattedAmountIn = Number((0, import_viem4.formatUnits)(BigInt(quote.amountIn.toString()), decimalsIn));
|
|
517
|
+
const rawAmountOut = formattedAmountIn * executionPrice;
|
|
518
|
+
amountOutMin = (0, import_viem4.parseUnits)(rawAmountOut.toString(), decimalsOut);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
316
521
|
if (isSingleChain) {
|
|
317
|
-
return await
|
|
522
|
+
return await import_intents_sdk7.SingleChainOrder.create({
|
|
318
523
|
user: accountAddress,
|
|
319
524
|
chainId: tokenIn.chainId,
|
|
320
525
|
tokenIn: tokenIn.address,
|
|
321
526
|
tokenOut: tokenOut.address,
|
|
322
527
|
amountIn: quote.amountIn,
|
|
323
|
-
amountOutMin
|
|
528
|
+
amountOutMin,
|
|
324
529
|
deadline,
|
|
325
530
|
destinationAddress: destination
|
|
326
531
|
});
|
|
327
532
|
}
|
|
328
|
-
return await
|
|
533
|
+
return await import_intents_sdk7.CrossChainOrder.create({
|
|
329
534
|
user: accountAddress,
|
|
330
535
|
sourceChainId: tokenIn.chainId,
|
|
331
536
|
sourceTokenAddress: tokenIn.address,
|
|
@@ -334,12 +539,166 @@ async function buildOrder({
|
|
|
334
539
|
destinationTokenAddress: tokenOut.address,
|
|
335
540
|
destinationAddress: destination,
|
|
336
541
|
deadline,
|
|
337
|
-
destinationTokenMinAmount:
|
|
542
|
+
destinationTokenMinAmount: amountOutMin,
|
|
338
543
|
minStablecoinAmount: quote.minStablecoinsAmount
|
|
339
544
|
});
|
|
340
545
|
}
|
|
341
546
|
|
|
342
|
-
// src/
|
|
547
|
+
// src/utils/pollOrderStatus.ts
|
|
548
|
+
var import_intents_sdk8 = require("@shogun-sdk/intents-sdk");
|
|
549
|
+
async function pollOrderStatus(address, orderId, options = {}) {
|
|
550
|
+
const { intervalMs = 2e3, timeoutMs = 3e5, authToken } = options;
|
|
551
|
+
const startTime = Date.now();
|
|
552
|
+
const isDebug = process.env.NODE_ENV !== "production";
|
|
553
|
+
const isEvmAddress = /^0x[a-fA-F0-9]{40}$/.test(address);
|
|
554
|
+
const isSuiAddress = /^0x[a-fA-F0-9]{64}$/.test(address);
|
|
555
|
+
const isSolanaAddress = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);
|
|
556
|
+
let queryParam;
|
|
557
|
+
if (isEvmAddress) queryParam = `evmWallets=${address}`;
|
|
558
|
+
else if (isSuiAddress) queryParam = `suiWallets=${address}`;
|
|
559
|
+
else if (isSolanaAddress) queryParam = `solanaWallets=${address}`;
|
|
560
|
+
else throw new Error(`Unrecognized wallet address format: ${address}`);
|
|
561
|
+
const queryUrl = `${import_intents_sdk8.AUCTIONEER_URL}/user_intent?${queryParam}`;
|
|
562
|
+
return new Promise((resolve, reject) => {
|
|
563
|
+
const pollInterval = setInterval(async () => {
|
|
564
|
+
try {
|
|
565
|
+
if (Date.now() - startTime > timeoutMs) {
|
|
566
|
+
clearInterval(pollInterval);
|
|
567
|
+
return resolve("Timeout");
|
|
568
|
+
}
|
|
569
|
+
const res = await fetch(queryUrl, {
|
|
570
|
+
method: "GET",
|
|
571
|
+
headers: {
|
|
572
|
+
"Content-Type": "application/json",
|
|
573
|
+
// The /user_intent status endpoint requires the SIWE JWT; without it
|
|
574
|
+
// the request 401s after the order has already been submitted.
|
|
575
|
+
...authToken ? { Authorization: `Bearer ${authToken}` } : {}
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
if (!res.ok) {
|
|
579
|
+
clearInterval(pollInterval);
|
|
580
|
+
return reject(
|
|
581
|
+
new Error(`Failed to fetch orders: ${res.status} ${res.statusText}`)
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
const json = await res.json();
|
|
585
|
+
const data = json?.data ?? {};
|
|
586
|
+
const allOrders = [
|
|
587
|
+
...data.crossChainDcaOrders ?? [],
|
|
588
|
+
...data.crossChainLimitOrders ?? [],
|
|
589
|
+
...data.singleChainDcaOrders ?? [],
|
|
590
|
+
...data.singleChainLimitOrders ?? []
|
|
591
|
+
];
|
|
592
|
+
const targetOrder = allOrders.find((o) => o.orderId === orderId);
|
|
593
|
+
if (!targetOrder) {
|
|
594
|
+
if (isDebug)
|
|
595
|
+
console.debug(`[pollOrderStatus] [${orderId}] Not found yet`);
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
const { orderStatus } = targetOrder;
|
|
599
|
+
if (isDebug) {
|
|
600
|
+
const elapsed = ((Date.now() - startTime) / 1e3).toFixed(1);
|
|
601
|
+
console.debug(`targetOrder`, targetOrder);
|
|
602
|
+
console.debug(
|
|
603
|
+
`[pollOrderStatus] [${orderId}] status=${orderStatus} (elapsed ${elapsed}s)`
|
|
604
|
+
);
|
|
605
|
+
}
|
|
606
|
+
if (["Fulfilled", "Cancelled", "Outdated"].includes(orderStatus)) {
|
|
607
|
+
clearInterval(pollInterval);
|
|
608
|
+
return resolve(orderStatus);
|
|
609
|
+
}
|
|
610
|
+
} catch (error) {
|
|
611
|
+
clearInterval(pollInterval);
|
|
612
|
+
return reject(error);
|
|
613
|
+
}
|
|
614
|
+
}, intervalMs);
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// src/core/execute/handleOrderPollingResult.ts
|
|
619
|
+
async function handleOrderPollingResult({
|
|
620
|
+
status,
|
|
621
|
+
orderId,
|
|
622
|
+
chainId,
|
|
623
|
+
update,
|
|
624
|
+
messageFor
|
|
625
|
+
}) {
|
|
626
|
+
switch (status) {
|
|
627
|
+
case "Fulfilled":
|
|
628
|
+
update("success", messageFor("success"));
|
|
629
|
+
return {
|
|
630
|
+
status: true,
|
|
631
|
+
orderId,
|
|
632
|
+
chainId,
|
|
633
|
+
finalStatus: status,
|
|
634
|
+
stage: "success"
|
|
635
|
+
};
|
|
636
|
+
case "Cancelled":
|
|
637
|
+
update("error", "Order was cancelled before fulfillment");
|
|
638
|
+
break;
|
|
639
|
+
case "Timeout":
|
|
640
|
+
update("error", "Order polling timed out");
|
|
641
|
+
break;
|
|
642
|
+
case "NotFound":
|
|
643
|
+
default:
|
|
644
|
+
update("error", "Order not found");
|
|
645
|
+
break;
|
|
646
|
+
}
|
|
647
|
+
return {
|
|
648
|
+
status: false,
|
|
649
|
+
orderId,
|
|
650
|
+
chainId,
|
|
651
|
+
finalStatus: status,
|
|
652
|
+
stage: "error"
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
// src/core/execute/ensurePermit2Allowance.ts
|
|
657
|
+
var import_viem5 = require("viem");
|
|
658
|
+
var import_intents_sdk9 = require("@shogun-sdk/intents-sdk");
|
|
659
|
+
async function ensurePermit2Allowance({
|
|
660
|
+
chainId,
|
|
661
|
+
tokenIn,
|
|
662
|
+
wallet,
|
|
663
|
+
accountAddress,
|
|
664
|
+
requiredAmount,
|
|
665
|
+
increaseByDelta = false
|
|
666
|
+
}) {
|
|
667
|
+
const spender = import_intents_sdk9.PERMIT2_ADDRESS[chainId];
|
|
668
|
+
let currentAllowance = 0n;
|
|
669
|
+
try {
|
|
670
|
+
if (!wallet.readContract) {
|
|
671
|
+
throw new Error("Wallet does not implement readContract()");
|
|
672
|
+
}
|
|
673
|
+
currentAllowance = await wallet.readContract({
|
|
674
|
+
address: tokenIn,
|
|
675
|
+
abi: import_viem5.erc20Abi,
|
|
676
|
+
functionName: "allowance",
|
|
677
|
+
args: [accountAddress, spender]
|
|
678
|
+
});
|
|
679
|
+
} catch (error) {
|
|
680
|
+
console.warn(`[Permit2] Failed to read allowance for ${tokenIn}`, error);
|
|
681
|
+
}
|
|
682
|
+
const approvalAmount = increaseByDelta ? currentAllowance + requiredAmount : import_viem5.maxUint256;
|
|
683
|
+
console.debug(
|
|
684
|
+
`[Permit2] Approving ${approvalAmount} for ${tokenIn} (current: ${currentAllowance}, required: ${requiredAmount})`
|
|
685
|
+
);
|
|
686
|
+
await wallet.sendTransaction({
|
|
687
|
+
to: tokenIn,
|
|
688
|
+
from: accountAddress,
|
|
689
|
+
data: (0, import_viem5.encodeFunctionData)({
|
|
690
|
+
abi: import_viem5.erc20Abi,
|
|
691
|
+
functionName: "approve",
|
|
692
|
+
args: [spender, approvalAmount]
|
|
693
|
+
}),
|
|
694
|
+
value: 0n
|
|
695
|
+
});
|
|
696
|
+
console.info(
|
|
697
|
+
`[Permit2] Approval transaction sent for ${tokenIn} on chain ${chainId}`
|
|
698
|
+
);
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// src/core/execute/handleEvmExecution.ts
|
|
343
702
|
async function handleEvmExecution({
|
|
344
703
|
recipientAddress,
|
|
345
704
|
quote,
|
|
@@ -347,18 +706,22 @@ async function handleEvmExecution({
|
|
|
347
706
|
accountAddress,
|
|
348
707
|
wallet,
|
|
349
708
|
isSingleChain,
|
|
350
|
-
|
|
351
|
-
|
|
709
|
+
update,
|
|
710
|
+
orderType,
|
|
711
|
+
options
|
|
352
712
|
}) {
|
|
353
|
-
const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
|
|
713
|
+
const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage] ?? "";
|
|
714
|
+
const deadline = options?.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
|
|
354
715
|
await wallet.switchChain(chainId);
|
|
355
716
|
const tokenIn = normalizeNative(chainId, quote.tokenIn.address);
|
|
717
|
+
quote.tokenOut.address = normalizeEvmTokenAddress(quote.tokenOut.address);
|
|
356
718
|
const shouldWrapNative = isNativeAddress(quote.tokenIn.address);
|
|
357
719
|
update("processing", shouldWrapNative ? `${messageFor("processing")} (wrapping native token)` : messageFor("processing"));
|
|
358
720
|
if (shouldWrapNative) {
|
|
721
|
+
quote.tokenIn.address === tokenIn;
|
|
359
722
|
await wallet.sendTransaction({
|
|
360
723
|
to: tokenIn,
|
|
361
|
-
data: (0,
|
|
724
|
+
data: (0, import_viem6.encodeFunctionData)({
|
|
362
725
|
abi: [{ type: "function", name: "deposit", stateMutability: "payable", inputs: [], outputs: [] }],
|
|
363
726
|
functionName: "deposit",
|
|
364
727
|
args: []
|
|
@@ -367,43 +730,70 @@ async function handleEvmExecution({
|
|
|
367
730
|
from: accountAddress
|
|
368
731
|
});
|
|
369
732
|
}
|
|
370
|
-
update("
|
|
371
|
-
await
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
}),
|
|
378
|
-
value: 0n,
|
|
379
|
-
from: accountAddress
|
|
733
|
+
update("processing", messageFor("approving"));
|
|
734
|
+
await ensurePermit2Allowance({
|
|
735
|
+
chainId,
|
|
736
|
+
tokenIn,
|
|
737
|
+
wallet,
|
|
738
|
+
accountAddress,
|
|
739
|
+
requiredAmount: BigInt(quote.amountIn)
|
|
380
740
|
});
|
|
381
|
-
update("
|
|
741
|
+
update("processing", messageFor("approved"));
|
|
382
742
|
const destination = recipientAddress ?? accountAddress;
|
|
383
743
|
const order = await buildOrder({
|
|
384
744
|
quote,
|
|
385
745
|
accountAddress,
|
|
386
746
|
destination,
|
|
387
747
|
deadline,
|
|
388
|
-
isSingleChain
|
|
748
|
+
isSingleChain,
|
|
749
|
+
orderType,
|
|
750
|
+
options
|
|
389
751
|
});
|
|
390
|
-
|
|
391
|
-
|
|
752
|
+
console.debug(`order`, order);
|
|
753
|
+
update("processing", messageFor("signing"));
|
|
754
|
+
const { orderTypedData, nonce } = isSingleChain ? await (0, import_intents_sdk10.getEVMSingleChainOrderTypedData)(order) : await (0, import_intents_sdk10.getEVMCrossChainOrderTypedData)(order);
|
|
755
|
+
const typedData = serializeBigIntsToStrings(orderTypedData);
|
|
392
756
|
if (!wallet.signTypedData) {
|
|
393
757
|
throw new Error("Wallet does not support EIP-712 signing");
|
|
394
758
|
}
|
|
395
|
-
const signature = await wallet.signTypedData(
|
|
396
|
-
|
|
759
|
+
const signature = await wallet.signTypedData({
|
|
760
|
+
domain: typedData.domain,
|
|
761
|
+
types: typedData.types,
|
|
762
|
+
primaryType: typedData.primaryType,
|
|
763
|
+
value: typedData.message,
|
|
764
|
+
message: typedData.message
|
|
765
|
+
});
|
|
766
|
+
update("processing", messageFor("submitting"));
|
|
397
767
|
const res = await order.sendToAuctioneer({ signature, nonce: nonce.toString() });
|
|
398
768
|
if (!res.success) {
|
|
399
769
|
throw new Error("Auctioneer submission failed");
|
|
400
770
|
}
|
|
401
|
-
update("
|
|
402
|
-
|
|
771
|
+
update("initiated", messageFor("initiated"));
|
|
772
|
+
const { intentId: orderId } = res.data;
|
|
773
|
+
update("initiated", messageFor("shogun_processing"));
|
|
774
|
+
if (orderType === "limit" /* LIMIT */) {
|
|
775
|
+
update("success", messageFor("success_limit"));
|
|
776
|
+
return {
|
|
777
|
+
status: true,
|
|
778
|
+
orderId,
|
|
779
|
+
chainId,
|
|
780
|
+
finalStatus: "OrderPlaced",
|
|
781
|
+
stage: "success"
|
|
782
|
+
};
|
|
783
|
+
} else {
|
|
784
|
+
const status = await pollOrderStatus(accountAddress, orderId, { authToken: options?.authToken });
|
|
785
|
+
return await handleOrderPollingResult({
|
|
786
|
+
status,
|
|
787
|
+
orderId,
|
|
788
|
+
chainId,
|
|
789
|
+
update,
|
|
790
|
+
messageFor
|
|
791
|
+
});
|
|
792
|
+
}
|
|
403
793
|
}
|
|
404
794
|
|
|
405
|
-
// src/core/
|
|
406
|
-
var
|
|
795
|
+
// src/core/execute/handleSolanaExecution.ts
|
|
796
|
+
var import_intents_sdk11 = require("@shogun-sdk/intents-sdk");
|
|
407
797
|
var import_web3 = require("@solana/web3.js");
|
|
408
798
|
async function handleSolanaExecution({
|
|
409
799
|
recipientAddress,
|
|
@@ -412,12 +802,14 @@ async function handleSolanaExecution({
|
|
|
412
802
|
isSingleChain,
|
|
413
803
|
update,
|
|
414
804
|
accountAddress,
|
|
415
|
-
|
|
805
|
+
orderType,
|
|
806
|
+
options
|
|
416
807
|
}) {
|
|
417
808
|
if (!wallet.rpcUrl) {
|
|
418
809
|
throw new Error("Solana wallet is missing rpcUrl");
|
|
419
810
|
}
|
|
420
|
-
const
|
|
811
|
+
const deadline = options?.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
|
|
812
|
+
const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage] ?? "";
|
|
421
813
|
update("processing", messageFor("processing"));
|
|
422
814
|
const destination = recipientAddress ?? accountAddress;
|
|
423
815
|
const order = await buildOrder({
|
|
@@ -425,7 +817,9 @@ async function handleSolanaExecution({
|
|
|
425
817
|
accountAddress,
|
|
426
818
|
destination,
|
|
427
819
|
deadline,
|
|
428
|
-
isSingleChain
|
|
820
|
+
isSingleChain,
|
|
821
|
+
orderType,
|
|
822
|
+
options
|
|
429
823
|
});
|
|
430
824
|
const txData = await getSolanaOrderInstructions({
|
|
431
825
|
order,
|
|
@@ -433,10 +827,9 @@ async function handleSolanaExecution({
|
|
|
433
827
|
rpcUrl: wallet.rpcUrl
|
|
434
828
|
});
|
|
435
829
|
const transaction = import_web3.VersionedTransaction.deserialize(Uint8Array.from(txData.txBytes));
|
|
436
|
-
update("
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
update("submitting", messageFor("submitting"));
|
|
830
|
+
update("processing", messageFor("signing"));
|
|
831
|
+
await wallet.sendTransaction(transaction);
|
|
832
|
+
update("processing", messageFor("submitting"));
|
|
440
833
|
const response = await submitToAuctioneer({
|
|
441
834
|
order,
|
|
442
835
|
isSingleChain,
|
|
@@ -445,13 +838,28 @@ async function handleSolanaExecution({
|
|
|
445
838
|
if (!response.success) {
|
|
446
839
|
throw new Error("Auctioneer submission failed");
|
|
447
840
|
}
|
|
448
|
-
update("
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
841
|
+
update("initiated", messageFor("initiated"));
|
|
842
|
+
const { intentId: orderId } = response.data;
|
|
843
|
+
update("initiated", messageFor("shogun_processing"));
|
|
844
|
+
if (orderType === "limit" /* LIMIT */) {
|
|
845
|
+
update("success", messageFor("success_limit"));
|
|
846
|
+
return {
|
|
847
|
+
status: true,
|
|
848
|
+
orderId,
|
|
849
|
+
chainId: SOLANA_CHAIN_ID,
|
|
850
|
+
finalStatus: "OrderPlaced",
|
|
851
|
+
stage: "success"
|
|
852
|
+
};
|
|
853
|
+
} else {
|
|
854
|
+
const status = await pollOrderStatus(accountAddress, orderId, { authToken: options?.authToken });
|
|
855
|
+
return await handleOrderPollingResult({
|
|
856
|
+
status,
|
|
857
|
+
orderId,
|
|
858
|
+
chainId: SOLANA_CHAIN_ID,
|
|
859
|
+
update,
|
|
860
|
+
messageFor
|
|
861
|
+
});
|
|
862
|
+
}
|
|
455
863
|
}
|
|
456
864
|
async function getSolanaOrderInstructions({
|
|
457
865
|
order,
|
|
@@ -459,11 +867,11 @@ async function getSolanaOrderInstructions({
|
|
|
459
867
|
rpcUrl
|
|
460
868
|
}) {
|
|
461
869
|
if (isSingleChain) {
|
|
462
|
-
return await (0,
|
|
870
|
+
return await (0, import_intents_sdk11.getSolanaSingleChainOrderInstructions)(order, {
|
|
463
871
|
rpcUrl
|
|
464
872
|
});
|
|
465
873
|
}
|
|
466
|
-
return await (0,
|
|
874
|
+
return await (0, import_intents_sdk11.getSolanaCrossChainOrderInstructions)(order, {
|
|
467
875
|
rpcUrl
|
|
468
876
|
});
|
|
469
877
|
}
|
|
@@ -484,52 +892,93 @@ async function submitToAuctioneer({
|
|
|
484
892
|
});
|
|
485
893
|
}
|
|
486
894
|
|
|
487
|
-
// src/core/
|
|
895
|
+
// src/core/execute/execute.ts
|
|
488
896
|
async function executeOrder({
|
|
489
897
|
quote,
|
|
490
898
|
accountAddress,
|
|
491
899
|
recipientAddress,
|
|
492
900
|
wallet,
|
|
493
901
|
onStatus,
|
|
902
|
+
orderType = "market" /* MARKET */,
|
|
494
903
|
options = {}
|
|
495
904
|
}) {
|
|
496
|
-
const
|
|
905
|
+
const isDev = process.env.NODE_ENV !== "production";
|
|
906
|
+
const log = (...args) => {
|
|
907
|
+
if (isDev) console.debug("[OneShot::executeOrder]", ...args);
|
|
908
|
+
};
|
|
497
909
|
const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
|
|
498
|
-
const update = (stage, message) =>
|
|
910
|
+
const update = (stage, message) => {
|
|
911
|
+
log("Stage:", stage, "| Message:", message ?? messageFor(stage));
|
|
912
|
+
onStatus?.(stage, message ?? messageFor(stage));
|
|
913
|
+
};
|
|
499
914
|
try {
|
|
915
|
+
log("Starting execution:", {
|
|
916
|
+
accountAddress,
|
|
917
|
+
recipientAddress,
|
|
918
|
+
tokenIn: quote?.tokenIn,
|
|
919
|
+
tokenOut: quote?.tokenOut
|
|
920
|
+
});
|
|
500
921
|
const adapter = normalizeWallet(wallet);
|
|
501
922
|
if (!adapter) throw new Error("No wallet provided");
|
|
502
923
|
const { tokenIn, tokenOut } = quote;
|
|
924
|
+
const srcChain = Number(tokenIn.chainId);
|
|
925
|
+
const destChain = Number(tokenOut.chainId);
|
|
926
|
+
if (!CURRENT_SUPPORTED.includes(srcChain) || !CURRENT_SUPPORTED.includes(destChain)) {
|
|
927
|
+
const unsupportedChains = [
|
|
928
|
+
!CURRENT_SUPPORTED.includes(srcChain) ? srcChain : null,
|
|
929
|
+
!CURRENT_SUPPORTED.includes(destChain) ? destChain : null
|
|
930
|
+
].filter(Boolean).join(", ");
|
|
931
|
+
const errorMsg = `Unsupported chain(s): ${unsupportedChains}`;
|
|
932
|
+
update("error", errorMsg);
|
|
933
|
+
log("Error:", errorMsg);
|
|
934
|
+
throw new Error(errorMsg);
|
|
935
|
+
}
|
|
503
936
|
const isSingleChain = tokenIn.chainId === tokenOut.chainId;
|
|
504
937
|
const chainId = Number(tokenIn.chainId);
|
|
505
|
-
update("processing"
|
|
506
|
-
if ((0,
|
|
507
|
-
|
|
938
|
+
update("processing");
|
|
939
|
+
if ((0, import_intents_sdk12.isEvmChain)(chainId)) {
|
|
940
|
+
log("Detected EVM chain:", chainId);
|
|
941
|
+
const result = await handleEvmExecution({
|
|
508
942
|
recipientAddress,
|
|
509
943
|
quote,
|
|
510
944
|
chainId,
|
|
511
945
|
accountAddress,
|
|
512
946
|
wallet: adapter,
|
|
513
947
|
isSingleChain,
|
|
514
|
-
|
|
515
|
-
|
|
948
|
+
update,
|
|
949
|
+
orderType,
|
|
950
|
+
options
|
|
516
951
|
});
|
|
952
|
+
log("EVM execution result:", result);
|
|
953
|
+
return result;
|
|
517
954
|
}
|
|
518
|
-
if (chainId ===
|
|
519
|
-
|
|
955
|
+
if (chainId === import_intents_sdk12.ChainID.Solana) {
|
|
956
|
+
log("Detected Solana chain");
|
|
957
|
+
const result = await handleSolanaExecution({
|
|
520
958
|
recipientAddress,
|
|
521
959
|
quote,
|
|
522
960
|
accountAddress,
|
|
523
961
|
wallet: adapter,
|
|
524
962
|
isSingleChain,
|
|
525
|
-
|
|
526
|
-
|
|
963
|
+
update,
|
|
964
|
+
orderType,
|
|
965
|
+
options
|
|
527
966
|
});
|
|
967
|
+
log("Solana execution result:", result);
|
|
968
|
+
return result;
|
|
528
969
|
}
|
|
529
|
-
|
|
530
|
-
|
|
970
|
+
const unsupported = `Unsupported chain: ${chainId}`;
|
|
971
|
+
update("error", unsupported);
|
|
972
|
+
log("Error:", unsupported);
|
|
973
|
+
return { status: false, message: unsupported, stage: "error" };
|
|
531
974
|
} catch (error) {
|
|
532
|
-
|
|
975
|
+
let message = "An unknown error occurred";
|
|
976
|
+
if (error && typeof error === "object") {
|
|
977
|
+
const err = error;
|
|
978
|
+
message = err.details ?? err.message ?? message;
|
|
979
|
+
} else if (typeof error === "string") {
|
|
980
|
+
message = error;
|
|
981
|
+
}
|
|
533
982
|
update("error", message);
|
|
534
983
|
return { status: false, message, stage: "error" };
|
|
535
984
|
}
|
|
@@ -540,349 +989,972 @@ function normalizeWallet(wallet) {
|
|
|
540
989
|
return wallet;
|
|
541
990
|
}
|
|
542
991
|
|
|
543
|
-
// src/
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
const
|
|
550
|
-
|
|
992
|
+
// src/core/orders/getOrders.ts
|
|
993
|
+
var import_intents_sdk13 = require("@shogun-sdk/intents-sdk");
|
|
994
|
+
async function getOrders({
|
|
995
|
+
evmAddress,
|
|
996
|
+
solAddress
|
|
997
|
+
}) {
|
|
998
|
+
const wallets = [evmAddress, solAddress].filter(
|
|
999
|
+
(wallet) => Boolean(wallet)
|
|
1000
|
+
);
|
|
1001
|
+
if (wallets.length === 0) {
|
|
1002
|
+
throw new Error("At least one wallet address (EVM, Solana) must be provided.");
|
|
1003
|
+
}
|
|
1004
|
+
const results = await Promise.all(
|
|
1005
|
+
wallets.map((wallet) => (0, import_intents_sdk13.fetchUserOrders)({ wallet }))
|
|
1006
|
+
);
|
|
1007
|
+
return results.reduce(
|
|
1008
|
+
(merged, orders) => {
|
|
1009
|
+
merged.singleChainLimitOrders.push(...orders.singleChainLimitOrders);
|
|
1010
|
+
merged.crossChainLimitOrders.push(...orders.crossChainLimitOrders);
|
|
1011
|
+
return merged;
|
|
1012
|
+
},
|
|
1013
|
+
{ singleChainLimitOrders: [], crossChainLimitOrders: [] }
|
|
1014
|
+
);
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
// src/core/orders/cancelOrder.ts
|
|
1018
|
+
var import_intents_sdk14 = require("@shogun-sdk/intents-sdk");
|
|
1019
|
+
var import_web32 = require("@solana/web3.js");
|
|
1020
|
+
var import_viem8 = require("viem");
|
|
1021
|
+
var inFlightCancels = /* @__PURE__ */ new Map();
|
|
1022
|
+
function cancelIntentsOrder(args) {
|
|
1023
|
+
const srcChain = "srcChainId" in args.order ? args.order.srcChainId : args.order.chainId;
|
|
1024
|
+
const key = `${srcChain}:${args.order.orderId}`;
|
|
1025
|
+
const existing = inFlightCancels.get(key);
|
|
1026
|
+
if (existing) return existing;
|
|
1027
|
+
const pending = performCancel(args).finally(() => {
|
|
1028
|
+
inFlightCancels.delete(key);
|
|
1029
|
+
});
|
|
1030
|
+
inFlightCancels.set(key, pending);
|
|
1031
|
+
return pending;
|
|
1032
|
+
}
|
|
1033
|
+
async function performCancel({
|
|
1034
|
+
order,
|
|
1035
|
+
wallet,
|
|
1036
|
+
sol_rpc
|
|
1037
|
+
}) {
|
|
1038
|
+
const isCrossChain = "srcChainId" in order && "destChainId" in order && order.srcChainId !== order.destChainId;
|
|
1039
|
+
const srcChain = "srcChainId" in order ? order.srcChainId : order.chainId;
|
|
1040
|
+
const isSolanaOrder = srcChain === import_intents_sdk14.ChainID.Solana;
|
|
1041
|
+
if (isSolanaOrder) {
|
|
1042
|
+
if (!isCrossChain) {
|
|
1043
|
+
const { versionedMessageBytes: versionedMessageBytes2 } = await (0, import_intents_sdk14.cancelSingleChainOrderInstructionsAsBytes)(
|
|
1044
|
+
order.orderId,
|
|
1045
|
+
order.user,
|
|
1046
|
+
{ rpcUrl: sol_rpc }
|
|
1047
|
+
);
|
|
1048
|
+
const message2 = import_web32.VersionedMessage.deserialize(
|
|
1049
|
+
versionedMessageBytes2
|
|
1050
|
+
);
|
|
1051
|
+
const tx2 = new import_web32.VersionedTransaction(message2);
|
|
1052
|
+
return await wallet.sendTransaction(tx2);
|
|
1053
|
+
}
|
|
1054
|
+
const { versionedMessageBytes } = await (0, import_intents_sdk14.cancelCrossChainOrderInstructionsAsBytes)(
|
|
1055
|
+
order.orderId,
|
|
1056
|
+
order.user,
|
|
1057
|
+
{ rpcUrl: sol_rpc }
|
|
1058
|
+
);
|
|
1059
|
+
const message = import_web32.VersionedMessage.deserialize(
|
|
1060
|
+
versionedMessageBytes
|
|
1061
|
+
);
|
|
1062
|
+
const tx = new import_web32.VersionedTransaction(message);
|
|
1063
|
+
return await wallet.sendTransaction(tx);
|
|
1064
|
+
}
|
|
1065
|
+
const chainId = srcChain;
|
|
1066
|
+
const { readContract } = wallet;
|
|
1067
|
+
if (!readContract) {
|
|
1068
|
+
throw new Error("Wallet does not support readContract");
|
|
1069
|
+
}
|
|
1070
|
+
const nonce = BigInt(order.nonce ?? "0");
|
|
1071
|
+
const nonceWordPos = nonce >> 8n;
|
|
1072
|
+
const nonceBitPos = nonce - nonceWordPos * 256n;
|
|
1073
|
+
if (isCrossChain) {
|
|
1074
|
+
const [orderData = [false, false], currentNonceBitmap = 0n] = await Promise.all([
|
|
1075
|
+
readContract({
|
|
1076
|
+
address: import_intents_sdk14.CROSS_CHAIN_GUARD_ADDRESSES[chainId],
|
|
1077
|
+
abi: [
|
|
1078
|
+
{
|
|
1079
|
+
inputs: [{ name: "orderId", type: "bytes32" }],
|
|
1080
|
+
name: "orderData",
|
|
1081
|
+
outputs: [
|
|
1082
|
+
{ name: "initialized", type: "bool" },
|
|
1083
|
+
{ name: "deactivated", type: "bool" }
|
|
1084
|
+
],
|
|
1085
|
+
stateMutability: "view",
|
|
1086
|
+
type: "function"
|
|
1087
|
+
}
|
|
1088
|
+
],
|
|
1089
|
+
functionName: "orderData",
|
|
1090
|
+
args: [order.orderId]
|
|
1091
|
+
}),
|
|
1092
|
+
readContract({
|
|
1093
|
+
address: import_intents_sdk14.PERMIT2_ADDRESS[chainId],
|
|
1094
|
+
abi: [
|
|
1095
|
+
{
|
|
1096
|
+
inputs: [
|
|
1097
|
+
{ name: "owner", type: "address" },
|
|
1098
|
+
{ name: "wordPos", type: "uint256" }
|
|
1099
|
+
],
|
|
1100
|
+
name: "nonceBitmap",
|
|
1101
|
+
outputs: [{ name: "", type: "uint256" }],
|
|
1102
|
+
stateMutability: "view",
|
|
1103
|
+
type: "function"
|
|
1104
|
+
}
|
|
1105
|
+
],
|
|
1106
|
+
functionName: "nonceBitmap",
|
|
1107
|
+
args: [order.user, nonceWordPos]
|
|
1108
|
+
})
|
|
1109
|
+
]);
|
|
1110
|
+
const [initialized, deactivated] = orderData;
|
|
1111
|
+
if (initialized) {
|
|
1112
|
+
if (deactivated) {
|
|
1113
|
+
throw new Error("Order is already deactivated");
|
|
1114
|
+
}
|
|
1115
|
+
return await wallet.sendTransaction({
|
|
1116
|
+
to: import_intents_sdk14.CROSS_CHAIN_GUARD_ADDRESSES[order.srcChainId],
|
|
1117
|
+
data: (0, import_viem8.encodeFunctionData)({
|
|
1118
|
+
abi: [
|
|
1119
|
+
{
|
|
1120
|
+
inputs: [
|
|
1121
|
+
{
|
|
1122
|
+
components: [
|
|
1123
|
+
{ name: "user", type: "address" },
|
|
1124
|
+
{ name: "tokenIn", type: "address" },
|
|
1125
|
+
{ name: "srcChainId", type: "uint256" },
|
|
1126
|
+
{ name: "deadline", type: "uint256" },
|
|
1127
|
+
{ name: "amountIn", type: "uint256" },
|
|
1128
|
+
{ name: "minStablecoinsAmount", type: "uint256" },
|
|
1129
|
+
{ name: "executionDetailsHash", type: "bytes32" },
|
|
1130
|
+
{ name: "nonce", type: "uint256" }
|
|
1131
|
+
],
|
|
1132
|
+
name: "orderInfo",
|
|
1133
|
+
type: "tuple"
|
|
1134
|
+
}
|
|
1135
|
+
],
|
|
1136
|
+
name: "cancelOrder",
|
|
1137
|
+
outputs: [],
|
|
1138
|
+
stateMutability: "nonpayable",
|
|
1139
|
+
type: "function"
|
|
1140
|
+
}
|
|
1141
|
+
],
|
|
1142
|
+
functionName: "cancelOrder",
|
|
1143
|
+
args: [
|
|
1144
|
+
{
|
|
1145
|
+
user: order.user,
|
|
1146
|
+
tokenIn: order.tokenIn,
|
|
1147
|
+
srcChainId: BigInt(order.srcChainId),
|
|
1148
|
+
deadline: BigInt(order.deadline),
|
|
1149
|
+
amountIn: BigInt(order.amountIn),
|
|
1150
|
+
minStablecoinsAmount: BigInt(order.minStablecoinsAmount),
|
|
1151
|
+
executionDetailsHash: order.executionDetailsHash,
|
|
1152
|
+
nonce
|
|
1153
|
+
}
|
|
1154
|
+
]
|
|
1155
|
+
}),
|
|
1156
|
+
value: BigInt(0),
|
|
1157
|
+
from: order.user
|
|
1158
|
+
});
|
|
1159
|
+
} else {
|
|
1160
|
+
if ((currentNonceBitmap & 1n << nonceBitPos) !== 0n) {
|
|
1161
|
+
throw new Error("Nonce is already invalidated");
|
|
1162
|
+
}
|
|
1163
|
+
const mask2 = 1n << nonceBitPos;
|
|
1164
|
+
return await wallet.sendTransaction({
|
|
1165
|
+
to: import_intents_sdk14.PERMIT2_ADDRESS[order.srcChainId],
|
|
1166
|
+
data: (0, import_viem8.encodeFunctionData)({
|
|
1167
|
+
abi: [
|
|
1168
|
+
{
|
|
1169
|
+
inputs: [
|
|
1170
|
+
{ name: "wordPos", type: "uint256" },
|
|
1171
|
+
{ name: "mask", type: "uint256" }
|
|
1172
|
+
],
|
|
1173
|
+
name: "invalidateUnorderedNonces",
|
|
1174
|
+
outputs: [],
|
|
1175
|
+
stateMutability: "nonpayable",
|
|
1176
|
+
type: "function"
|
|
1177
|
+
}
|
|
1178
|
+
],
|
|
1179
|
+
functionName: "invalidateUnorderedNonces",
|
|
1180
|
+
args: [nonceWordPos, mask2]
|
|
1181
|
+
}),
|
|
1182
|
+
value: BigInt(0),
|
|
1183
|
+
from: order.user
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
const [wasManuallyInitialized, currentBitmap = 0n] = await Promise.all([
|
|
1188
|
+
readContract({
|
|
1189
|
+
address: import_intents_sdk14.SINGLE_CHAIN_GUARD_ADDRESSES[chainId],
|
|
1190
|
+
abi: [
|
|
1191
|
+
{
|
|
1192
|
+
inputs: [{ name: "orderHash", type: "bytes32" }],
|
|
1193
|
+
name: "orderManuallyInitialized",
|
|
1194
|
+
outputs: [{ name: "", type: "bool" }],
|
|
1195
|
+
stateMutability: "view",
|
|
1196
|
+
type: "function"
|
|
1197
|
+
}
|
|
1198
|
+
],
|
|
1199
|
+
functionName: "orderManuallyInitialized",
|
|
1200
|
+
args: [order.orderId]
|
|
1201
|
+
}),
|
|
1202
|
+
readContract({
|
|
1203
|
+
address: import_intents_sdk14.PERMIT2_ADDRESS[chainId],
|
|
1204
|
+
abi: [
|
|
1205
|
+
{
|
|
1206
|
+
inputs: [
|
|
1207
|
+
{ name: "owner", type: "address" },
|
|
1208
|
+
{ name: "wordPos", type: "uint256" }
|
|
1209
|
+
],
|
|
1210
|
+
name: "nonceBitmap",
|
|
1211
|
+
outputs: [{ name: "", type: "uint256" }],
|
|
1212
|
+
stateMutability: "view",
|
|
1213
|
+
type: "function"
|
|
1214
|
+
}
|
|
1215
|
+
],
|
|
1216
|
+
functionName: "nonceBitmap",
|
|
1217
|
+
args: [order.user, nonceWordPos]
|
|
1218
|
+
})
|
|
1219
|
+
]);
|
|
1220
|
+
if (wasManuallyInitialized) {
|
|
1221
|
+
return await wallet.sendTransaction({
|
|
1222
|
+
to: import_intents_sdk14.SINGLE_CHAIN_GUARD_ADDRESSES[chainId],
|
|
1223
|
+
data: (0, import_viem8.encodeFunctionData)({
|
|
1224
|
+
abi: [
|
|
1225
|
+
{
|
|
1226
|
+
inputs: [
|
|
1227
|
+
{
|
|
1228
|
+
name: "order",
|
|
1229
|
+
type: "tuple",
|
|
1230
|
+
components: [
|
|
1231
|
+
{ name: "amountIn", type: "uint256" },
|
|
1232
|
+
{ name: "tokenIn", type: "address" },
|
|
1233
|
+
{ name: "deadline", type: "uint256" },
|
|
1234
|
+
{ name: "nonce", type: "uint256" },
|
|
1235
|
+
{ name: "encodedExternalCallData", type: "bytes" },
|
|
1236
|
+
{
|
|
1237
|
+
name: "extraTransfers",
|
|
1238
|
+
type: "tuple[]",
|
|
1239
|
+
components: [
|
|
1240
|
+
{ name: "amount", type: "uint256" },
|
|
1241
|
+
{ name: "receiver", type: "address" },
|
|
1242
|
+
{ name: "token", type: "address" }
|
|
1243
|
+
]
|
|
1244
|
+
},
|
|
1245
|
+
{
|
|
1246
|
+
name: "requestedOutput",
|
|
1247
|
+
type: "tuple",
|
|
1248
|
+
components: [
|
|
1249
|
+
{ name: "amount", type: "uint256" },
|
|
1250
|
+
{ name: "receiver", type: "address" },
|
|
1251
|
+
{ name: "token", type: "address" }
|
|
1252
|
+
]
|
|
1253
|
+
},
|
|
1254
|
+
{ name: "user", type: "address" }
|
|
1255
|
+
]
|
|
1256
|
+
}
|
|
1257
|
+
],
|
|
1258
|
+
name: "cancelManuallyCreatedOrder",
|
|
1259
|
+
outputs: [],
|
|
1260
|
+
stateMutability: "nonpayable",
|
|
1261
|
+
type: "function"
|
|
1262
|
+
}
|
|
1263
|
+
],
|
|
1264
|
+
functionName: "cancelManuallyCreatedOrder",
|
|
1265
|
+
args: [
|
|
1266
|
+
{
|
|
1267
|
+
amountIn: BigInt(order.amountIn),
|
|
1268
|
+
tokenIn: order.tokenIn,
|
|
1269
|
+
deadline: BigInt(order.deadline),
|
|
1270
|
+
nonce,
|
|
1271
|
+
encodedExternalCallData: "0x",
|
|
1272
|
+
extraTransfers: (order.extraTransfers || []).map((t) => ({
|
|
1273
|
+
amount: BigInt(t.amount),
|
|
1274
|
+
receiver: t.receiver,
|
|
1275
|
+
token: t.token
|
|
1276
|
+
})),
|
|
1277
|
+
requestedOutput: {
|
|
1278
|
+
amount: BigInt(order.amountOutMin),
|
|
1279
|
+
receiver: order.destinationAddress,
|
|
1280
|
+
token: order.tokenOut
|
|
1281
|
+
},
|
|
1282
|
+
user: order.user
|
|
1283
|
+
}
|
|
1284
|
+
]
|
|
1285
|
+
}),
|
|
1286
|
+
value: 0n,
|
|
1287
|
+
from: order.user
|
|
1288
|
+
});
|
|
1289
|
+
}
|
|
1290
|
+
const mask = 1n << nonceBitPos;
|
|
1291
|
+
if ((currentBitmap & mask) !== 0n) {
|
|
1292
|
+
throw new Error("Nonce is already invalidated");
|
|
1293
|
+
}
|
|
1294
|
+
return await wallet.sendTransaction({
|
|
1295
|
+
to: import_intents_sdk14.PERMIT2_ADDRESS[chainId],
|
|
1296
|
+
data: (0, import_viem8.encodeFunctionData)({
|
|
1297
|
+
abi: [
|
|
1298
|
+
{
|
|
1299
|
+
inputs: [
|
|
1300
|
+
{ name: "wordPos", type: "uint256" },
|
|
1301
|
+
{ name: "mask", type: "uint256" }
|
|
1302
|
+
],
|
|
1303
|
+
name: "invalidateUnorderedNonces",
|
|
1304
|
+
outputs: [],
|
|
1305
|
+
stateMutability: "nonpayable",
|
|
1306
|
+
type: "function"
|
|
1307
|
+
}
|
|
1308
|
+
],
|
|
1309
|
+
functionName: "invalidateUnorderedNonces",
|
|
1310
|
+
args: [nonceWordPos, mask]
|
|
1311
|
+
}),
|
|
1312
|
+
value: 0n,
|
|
1313
|
+
from: order.user
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
// src/core/client.ts
|
|
1318
|
+
var SwapSDK = class {
|
|
1319
|
+
constructor(config) {
|
|
1320
|
+
__publicField(this, "apiKey");
|
|
1321
|
+
/**
|
|
1322
|
+
* Fetches metadata for one or more tokens from the Shogun Token Search API.
|
|
1323
|
+
*
|
|
1324
|
+
* ---
|
|
1325
|
+
* ### Overview
|
|
1326
|
+
* `getTokensData` retrieves normalized token information — such as symbol, name,
|
|
1327
|
+
* decimals, logo URI, and verified status — for a given list of token addresses.
|
|
1328
|
+
*
|
|
1329
|
+
* It supports both **EVM** and **SVM (Solana)** tokens, returning metadata from
|
|
1330
|
+
* Shogun’s unified token registry.
|
|
1331
|
+
*
|
|
1332
|
+
* ---
|
|
1333
|
+
* @example
|
|
1334
|
+
* ```ts
|
|
1335
|
+
* const tokens = await getTokensData([
|
|
1336
|
+
* "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC
|
|
1337
|
+
* "So11111111111111111111111111111111111111112", // SOL
|
|
1338
|
+
* ]);
|
|
1339
|
+
*
|
|
1340
|
+
* console.log(tokens);
|
|
1341
|
+
* [
|
|
1342
|
+
* { symbol: "USDC", name: "USD Coin", chainId: 1, decimals: 6, ... },
|
|
1343
|
+
* { symbol: "SOL", name: "Solana", chainId: 101, decimals: 9, ... }
|
|
1344
|
+
* ]
|
|
1345
|
+
* ```
|
|
1346
|
+
*
|
|
1347
|
+
* @param addresses - An array of token addresses (EVM or SVM) to fetch metadata for.
|
|
1348
|
+
* @returns A promise resolving to an array of {@link TokenInfo} objects.
|
|
1349
|
+
*
|
|
1350
|
+
* @throws Will throw an error if the network request fails or the API responds with a non-OK status.
|
|
1351
|
+
*/
|
|
1352
|
+
__publicField(this, "getTokensData", getTokensData.bind(this));
|
|
1353
|
+
if (!config.apiKey) {
|
|
1354
|
+
throw new Error("SwapSDK: Missing API key");
|
|
1355
|
+
}
|
|
1356
|
+
this.apiKey = config.apiKey;
|
|
1357
|
+
if (this.apiKey) void this.apiKey;
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* Retrieves a swap quote for the given input and output tokens.
|
|
1361
|
+
*
|
|
1362
|
+
* @param params - Quote parameters including source/destination tokens and amount.
|
|
1363
|
+
* @returns A normalized `SwapQuoteResponse` containing output amount, route, and metadata.
|
|
1364
|
+
*/
|
|
1365
|
+
async getQuote(params) {
|
|
1366
|
+
return getQuote(params);
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Fetches token balances for the specified user wallet(s).
|
|
1370
|
+
*
|
|
1371
|
+
* Supports both EVM and SVM (Solana) wallet addresses.
|
|
1372
|
+
*
|
|
1373
|
+
* @param params - Wallet address and optional chain filters.
|
|
1374
|
+
* @param options - Optional abort signal for cancellation.
|
|
1375
|
+
* @returns A unified balance response with per-chain token details.
|
|
1376
|
+
*/
|
|
1377
|
+
async getBalances(params, options) {
|
|
1378
|
+
return getBalances(params, options);
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* Retrieves a list of verified tokens based on search query or chain filter.
|
|
1382
|
+
*
|
|
1383
|
+
* @param params - Search parameters (query, chain ID, pagination options).
|
|
1384
|
+
* @returns Paginated `TokenSearchResponse` containing token metadata.
|
|
1385
|
+
*/
|
|
1386
|
+
async getTokenList(params) {
|
|
1387
|
+
return getTokenList(params);
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Executes a prepared swap quote using the provided wallet and configuration.
|
|
1391
|
+
*
|
|
1392
|
+
* Handles:
|
|
1393
|
+
* - Token approval (if required)
|
|
1394
|
+
* - Transaction signing and broadcasting
|
|
1395
|
+
* - Confirmation polling and stage-based status updates
|
|
1396
|
+
*
|
|
1397
|
+
* Supports both:
|
|
1398
|
+
* - Market orders (with optional deadline)
|
|
1399
|
+
* - Limit orders (requires executionPrice and deadline)
|
|
1400
|
+
*
|
|
1401
|
+
* @param quote - The swap quote to execute, containing route and metadata.
|
|
1402
|
+
* @param accountAddress - The user's wallet address executing the swap.
|
|
1403
|
+
* @param recipientAddress - Optional recipient address for the output tokens (defaults to sender).
|
|
1404
|
+
* @param wallet - Adapted wallet instance (EVM/Solana) or a standard Viem `WalletClient`.
|
|
1405
|
+
* @param onStatus - Optional callback for receiving execution stage updates and messages.
|
|
1406
|
+
* @param orderType - Defines whether this is a market or limit order.
|
|
1407
|
+
* @param options - Execution parameters (different per order type).
|
|
1408
|
+
*
|
|
1409
|
+
* @returns A finalized execution result containing transaction hash, status, and any returned data.
|
|
1410
|
+
*
|
|
1411
|
+
* @example
|
|
1412
|
+
* ```ts
|
|
1413
|
+
* * Market order
|
|
1414
|
+
* const result = await sdk.executeTransaction({
|
|
1415
|
+
* quote,
|
|
1416
|
+
* accountAddress: "0x123...",
|
|
1417
|
+
* wallet,
|
|
1418
|
+
* orderType: OrderExecutionType.MARKET,
|
|
1419
|
+
* options: { deadline: 1800 },
|
|
1420
|
+
* onStatus: (stage, msg) => console.log(stage, msg),
|
|
1421
|
+
* });
|
|
1422
|
+
*
|
|
1423
|
+
* * Limit order
|
|
1424
|
+
* const result = await sdk.executeTransaction({
|
|
1425
|
+
* quote,
|
|
1426
|
+
* accountAddress: "0x123...",
|
|
1427
|
+
* wallet,
|
|
1428
|
+
* orderType: OrderExecutionType.LIMIT,
|
|
1429
|
+
* options: { executionPrice: "0.0021", deadline: 3600 },
|
|
1430
|
+
* });
|
|
1431
|
+
* ```
|
|
1432
|
+
*/
|
|
1433
|
+
async executeTransaction({
|
|
1434
|
+
quote,
|
|
1435
|
+
accountAddress,
|
|
1436
|
+
recipientAddress,
|
|
1437
|
+
wallet,
|
|
1438
|
+
onStatus,
|
|
1439
|
+
orderType,
|
|
1440
|
+
options
|
|
1441
|
+
}) {
|
|
1442
|
+
return executeOrder({
|
|
1443
|
+
quote,
|
|
1444
|
+
wallet,
|
|
1445
|
+
accountAddress,
|
|
1446
|
+
recipientAddress,
|
|
1447
|
+
onStatus,
|
|
1448
|
+
orderType,
|
|
1449
|
+
options
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Fetches all user orders (Market, Limit, Cross-chain) for connected wallets.
|
|
1454
|
+
*
|
|
1455
|
+
* ---
|
|
1456
|
+
* ### Overview
|
|
1457
|
+
* Retrieves both **single-chain** and **cross-chain** orders from the Shogun Intents API.
|
|
1458
|
+
* Works across EVM, Solana
|
|
1459
|
+
*
|
|
1460
|
+
* ---
|
|
1461
|
+
* @example
|
|
1462
|
+
* ```ts
|
|
1463
|
+
* const orders = await sdk.getOrders({
|
|
1464
|
+
* evmAddress: "0x123...",
|
|
1465
|
+
* solAddress: "9d12hF...abc",
|
|
1466
|
+
* });
|
|
1467
|
+
*
|
|
1468
|
+
* console.log(orders.singleChainLimitOrders);
|
|
1469
|
+
* ```
|
|
1470
|
+
*
|
|
1471
|
+
* @param params - Wallet addresses to fetch orders for (EVM, Solana).
|
|
1472
|
+
* @returns A structured {@link ApiUserOrders} object containing all user orders.
|
|
1473
|
+
*/
|
|
1474
|
+
async getOrders(params) {
|
|
1475
|
+
return getOrders(params);
|
|
1476
|
+
}
|
|
1477
|
+
/**
|
|
1478
|
+
* Cancels an order (single-chain or cross-chain) on EVM or Solana.
|
|
1479
|
+
*
|
|
1480
|
+
* Internally routes to the correct guard contract or Solana program to
|
|
1481
|
+
* deactivate the order or invalidate its nonce.
|
|
1482
|
+
*
|
|
1483
|
+
* @param params.order - Order payload returned from the Intents API.
|
|
1484
|
+
* @param params.wallet - Adapted wallet used to submit the cancellation transaction.
|
|
1485
|
+
* @param params.solRpc - Solana RPC URL used for SVM cancellations.
|
|
1486
|
+
*
|
|
1487
|
+
* @returns A transaction signature or hash from the underlying wallet.
|
|
1488
|
+
*/
|
|
1489
|
+
async cancelOrder(params) {
|
|
1490
|
+
return cancelIntentsOrder({
|
|
1491
|
+
order: params.order,
|
|
1492
|
+
wallet: params.wallet,
|
|
1493
|
+
sol_rpc: params.solRpc
|
|
1494
|
+
});
|
|
1495
|
+
}
|
|
1496
|
+
};
|
|
1497
|
+
|
|
1498
|
+
// src/react/SwapProvider.tsx
|
|
1499
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
1500
|
+
var SwapContext = (0, import_react.createContext)(null);
|
|
1501
|
+
var SwapProvider = ({ config, children }) => {
|
|
1502
|
+
const sdk = (0, import_react.useMemo)(() => new SwapSDK(config), [config.apiKey]);
|
|
1503
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SwapContext.Provider, { value: sdk, children });
|
|
1504
|
+
};
|
|
1505
|
+
var useSwap = () => {
|
|
1506
|
+
const ctx = (0, import_react.useContext)(SwapContext);
|
|
1507
|
+
if (!ctx) {
|
|
1508
|
+
throw new Error("useSwap must be used within <SwapProvider>");
|
|
1509
|
+
}
|
|
1510
|
+
return ctx;
|
|
1511
|
+
};
|
|
1512
|
+
|
|
1513
|
+
// src/react/useQuote.ts
|
|
1514
|
+
var import_react2 = require("react");
|
|
1515
|
+
var import_swr = __toESM(require("swr"), 1);
|
|
1516
|
+
var QUOTE_KEY = "quote-global";
|
|
1517
|
+
function isValidQuoteParams(p) {
|
|
1518
|
+
if (!p) return false;
|
|
1519
|
+
const { tokenIn, tokenOut, amount } = p;
|
|
1520
|
+
if (!tokenIn || !tokenOut || !amount) return false;
|
|
1521
|
+
const n = Number(amount);
|
|
1522
|
+
return Number.isFinite(n) && n > 0;
|
|
1523
|
+
}
|
|
1524
|
+
function useQuote(initialParams) {
|
|
1525
|
+
const sdk = useSwap();
|
|
1526
|
+
const abortRef = (0, import_react2.useRef)(null);
|
|
1527
|
+
const paramsRef = globalThis.__QUOTE_PARAMS_REF__ ?? (globalThis.__QUOTE_PARAMS_REF__ = { current: initialParams ?? null });
|
|
551
1528
|
(0, import_react2.useEffect)(() => {
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
1529
|
+
if (initialParams && JSON.stringify(paramsRef.current) !== JSON.stringify(initialParams)) {
|
|
1530
|
+
paramsRef.current = initialParams;
|
|
1531
|
+
void (0, import_swr.mutate)(QUOTE_KEY);
|
|
1532
|
+
}
|
|
1533
|
+
}, [initialParams]);
|
|
1534
|
+
const fetcher = (0, import_react2.useCallback)(async () => {
|
|
1535
|
+
const activeParams = paramsRef.current;
|
|
1536
|
+
if (!isValidQuoteParams(activeParams)) return null;
|
|
1537
|
+
if (abortRef.current) abortRef.current.abort();
|
|
1538
|
+
const controller = new AbortController();
|
|
1539
|
+
abortRef.current = controller;
|
|
1540
|
+
try {
|
|
1541
|
+
return await sdk.getQuote(activeParams);
|
|
1542
|
+
} catch (err) {
|
|
1543
|
+
if (err instanceof DOMException && err.name === "AbortError") return null;
|
|
1544
|
+
if (err instanceof Error) throw err;
|
|
1545
|
+
throw new Error(String(err));
|
|
1546
|
+
}
|
|
1547
|
+
}, [sdk]);
|
|
1548
|
+
const {
|
|
1549
|
+
data,
|
|
1550
|
+
error,
|
|
1551
|
+
isValidating: loading,
|
|
1552
|
+
mutate: mutateQuote
|
|
1553
|
+
} = (0, import_swr.default)(QUOTE_KEY, fetcher, {
|
|
1554
|
+
revalidateOnFocus: false,
|
|
1555
|
+
shouldRetryOnError: false,
|
|
1556
|
+
keepPreviousData: true
|
|
1557
|
+
});
|
|
1558
|
+
const refetch = (0, import_react2.useCallback)(async () => {
|
|
1559
|
+
await mutateQuote();
|
|
1560
|
+
}, [mutateQuote]);
|
|
1561
|
+
const setParams = (0, import_react2.useCallback)(
|
|
1562
|
+
(next) => {
|
|
1563
|
+
paramsRef.current = next;
|
|
1564
|
+
void (0, import_swr.mutate)(QUOTE_KEY);
|
|
1565
|
+
},
|
|
1566
|
+
[]
|
|
1567
|
+
);
|
|
1568
|
+
return (0, import_react2.useMemo)(
|
|
1569
|
+
() => ({
|
|
1570
|
+
data,
|
|
1571
|
+
loading,
|
|
1572
|
+
error: error instanceof Error ? error.message : null,
|
|
1573
|
+
refetch,
|
|
1574
|
+
setParams,
|
|
1575
|
+
get activeParams() {
|
|
1576
|
+
return paramsRef.current;
|
|
1577
|
+
}
|
|
1578
|
+
}),
|
|
1579
|
+
[data, loading, error, refetch, setParams]
|
|
1580
|
+
);
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
// src/react/useExecuteTransaction.ts
|
|
1584
|
+
var import_react4 = require("react");
|
|
1585
|
+
|
|
1586
|
+
// src/react/useBalances.ts
|
|
1587
|
+
var import_react3 = require("react");
|
|
1588
|
+
var import_swr2 = __toESM(require("swr"), 1);
|
|
1589
|
+
var BALANCE_KEY = "balances-global";
|
|
1590
|
+
function useBalances(initialParams, options) {
|
|
1591
|
+
const sdk = useSwap();
|
|
1592
|
+
const abortRef = (0, import_react3.useRef)(null);
|
|
1593
|
+
const lastDataRef = (0, import_react3.useRef)(null);
|
|
1594
|
+
const paramsRef = globalThis.__BALANCES_PARAMS_REF__ ?? (globalThis.__BALANCES_PARAMS_REF__ = { current: initialParams ?? null });
|
|
1595
|
+
const fetcher = (0, import_react3.useCallback)(async () => {
|
|
1596
|
+
const activeParams = paramsRef.current;
|
|
1597
|
+
if (!activeParams) return null;
|
|
1598
|
+
if (abortRef.current) abortRef.current.abort();
|
|
1599
|
+
const controller = new AbortController();
|
|
1600
|
+
abortRef.current = controller;
|
|
1601
|
+
try {
|
|
1602
|
+
const balances = await sdk.getBalances(activeParams, { signal: controller.signal });
|
|
1603
|
+
lastDataRef.current = balances;
|
|
1604
|
+
return balances;
|
|
1605
|
+
} catch (err) {
|
|
1606
|
+
if (err instanceof DOMException && err.name === "AbortError") return lastDataRef.current;
|
|
1607
|
+
if (err instanceof Error) throw err;
|
|
1608
|
+
throw new Error(String(err));
|
|
1609
|
+
}
|
|
1610
|
+
}, [sdk, paramsRef]);
|
|
1611
|
+
const {
|
|
1612
|
+
data,
|
|
1613
|
+
error,
|
|
1614
|
+
// `isLoading` is only true on the initial fetch (no data yet), so background
|
|
1615
|
+
// refreshes on `refreshInterval` don't toggle it and flicker the UI.
|
|
1616
|
+
isLoading: loading,
|
|
1617
|
+
isValidating,
|
|
1618
|
+
mutate: mutateBalances
|
|
1619
|
+
} = (0, import_swr2.default)(BALANCE_KEY, fetcher, {
|
|
1620
|
+
revalidateOnFocus: false,
|
|
1621
|
+
shouldRetryOnError: false,
|
|
1622
|
+
keepPreviousData: true,
|
|
1623
|
+
// 0 (default) disables polling; a positive value re-fetches on that interval.
|
|
1624
|
+
refreshInterval: options?.refreshInterval ?? 0
|
|
1625
|
+
});
|
|
1626
|
+
const refetch = (0, import_react3.useCallback)(async () => {
|
|
1627
|
+
await mutateBalances();
|
|
1628
|
+
}, [mutateBalances]);
|
|
1629
|
+
const setParams = (0, import_react3.useCallback)((next) => {
|
|
1630
|
+
paramsRef.current = next;
|
|
1631
|
+
void (0, import_swr2.mutate)(BALANCE_KEY);
|
|
1632
|
+
}, [paramsRef]);
|
|
1633
|
+
(0, import_react3.useEffect)(() => {
|
|
1634
|
+
if (initialParams) {
|
|
1635
|
+
const prevParams = paramsRef.current;
|
|
1636
|
+
const paramsChanged = !prevParams || prevParams.addresses.svm !== initialParams.addresses.svm || prevParams.addresses.evm !== initialParams.addresses.evm;
|
|
1637
|
+
if (paramsChanged) {
|
|
1638
|
+
paramsRef.current = initialParams;
|
|
1639
|
+
void (0, import_swr2.mutate)(BALANCE_KEY);
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
}, [initialParams, paramsRef]);
|
|
1643
|
+
return (0, import_react3.useMemo)(
|
|
1644
|
+
() => ({
|
|
1645
|
+
data,
|
|
1646
|
+
loading,
|
|
1647
|
+
// True during background revalidation (e.g. `refreshInterval` polls) while
|
|
1648
|
+
// previous `data` stays visible — use for a subtle refresh indicator.
|
|
1649
|
+
isValidating,
|
|
1650
|
+
error: error instanceof Error ? error : null,
|
|
1651
|
+
refetch,
|
|
1652
|
+
setParams,
|
|
1653
|
+
get activeParams() {
|
|
1654
|
+
return paramsRef.current;
|
|
1655
|
+
}
|
|
1656
|
+
}),
|
|
1657
|
+
[data, loading, isValidating, error, refetch, setParams, paramsRef]
|
|
1658
|
+
);
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
// src/react/useExecuteTransaction.ts
|
|
1662
|
+
function useExecuteTransaction() {
|
|
1663
|
+
const sdk = useSwap();
|
|
1664
|
+
const [isLoading, setLoading] = (0, import_react4.useState)(false);
|
|
1665
|
+
const [stage, setStage] = (0, import_react4.useState)(null);
|
|
1666
|
+
const [message, setMessage] = (0, import_react4.useState)(null);
|
|
1667
|
+
const [error, setError] = (0, import_react4.useState)(null);
|
|
1668
|
+
const [result, setResult] = (0, import_react4.useState)(null);
|
|
1669
|
+
const { refetch: refetchQuote } = useQuote();
|
|
1670
|
+
const { refetch: refetchBalances } = useBalances();
|
|
1671
|
+
const execute = (0, import_react4.useCallback)(
|
|
557
1672
|
async ({
|
|
558
1673
|
quote,
|
|
559
1674
|
accountAddress,
|
|
560
1675
|
recipientAddress,
|
|
561
1676
|
wallet,
|
|
562
|
-
|
|
1677
|
+
orderType,
|
|
1678
|
+
options
|
|
563
1679
|
}) => {
|
|
564
|
-
if (!quote || !wallet) {
|
|
565
|
-
throw new Error("Quote and wallet are required for order execution.");
|
|
566
|
-
}
|
|
567
1680
|
setLoading(true);
|
|
568
1681
|
setError(null);
|
|
569
|
-
|
|
570
|
-
|
|
1682
|
+
setResult(null);
|
|
1683
|
+
const onStatus = (s, msg) => {
|
|
1684
|
+
setStage(s);
|
|
1685
|
+
setMessage(msg ?? "");
|
|
1686
|
+
};
|
|
571
1687
|
try {
|
|
572
|
-
const
|
|
573
|
-
const onStatus = (stage, msg) => {
|
|
574
|
-
if (!isMounted.current) return;
|
|
575
|
-
setStatus(stage);
|
|
576
|
-
if (msg) setMessage(msg);
|
|
577
|
-
};
|
|
578
|
-
const result = await executeOrder({
|
|
1688
|
+
const res = await sdk.executeTransaction({
|
|
579
1689
|
quote,
|
|
1690
|
+
wallet,
|
|
580
1691
|
accountAddress,
|
|
581
1692
|
recipientAddress,
|
|
582
|
-
wallet,
|
|
583
1693
|
onStatus,
|
|
584
|
-
|
|
1694
|
+
orderType,
|
|
1695
|
+
options
|
|
585
1696
|
});
|
|
586
|
-
if (
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
return result;
|
|
591
|
-
} catch (err) {
|
|
592
|
-
const errorObj = err instanceof Error ? err : new Error(String(err));
|
|
593
|
-
if (isMounted.current) {
|
|
594
|
-
setError(errorObj);
|
|
595
|
-
setStatus("error");
|
|
596
|
-
setMessage(errorObj.message);
|
|
597
|
-
setData({
|
|
598
|
-
status: false,
|
|
599
|
-
stage: "error",
|
|
600
|
-
message: errorObj.message
|
|
1697
|
+
if (res && typeof res === "object" && "status" in res && "stage" in res && typeof res.stage === "string") {
|
|
1698
|
+
setResult({
|
|
1699
|
+
...res,
|
|
1700
|
+
stage: res.stage
|
|
601
1701
|
});
|
|
1702
|
+
} else {
|
|
1703
|
+
setResult(res);
|
|
602
1704
|
}
|
|
603
|
-
return
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
1705
|
+
return res;
|
|
1706
|
+
} catch (err) {
|
|
1707
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1708
|
+
setError(msg);
|
|
1709
|
+
throw err;
|
|
608
1710
|
} finally {
|
|
609
|
-
|
|
1711
|
+
await Promise.allSettled([refetchQuote(), refetchBalances()]);
|
|
1712
|
+
setLoading(false);
|
|
610
1713
|
}
|
|
611
1714
|
},
|
|
612
|
-
[]
|
|
1715
|
+
[sdk, refetchQuote, refetchBalances]
|
|
613
1716
|
);
|
|
614
1717
|
return {
|
|
615
|
-
/** Executes the swap order. */
|
|
616
1718
|
execute,
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
/** Human-readable status message. */
|
|
1719
|
+
isLoading,
|
|
1720
|
+
stage,
|
|
620
1721
|
message,
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
/** Raw SDK response data. */
|
|
624
|
-
data,
|
|
625
|
-
/** Captured error (if execution failed). */
|
|
626
|
-
error
|
|
1722
|
+
error,
|
|
1723
|
+
result
|
|
627
1724
|
};
|
|
628
1725
|
}
|
|
629
1726
|
|
|
630
|
-
// src/react/
|
|
631
|
-
var
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
const
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
tokenIn: normalizedTokenIn,
|
|
651
|
-
tokenOut: params.tokenOut.address,
|
|
652
|
-
amount: params.amount
|
|
653
|
-
});
|
|
654
|
-
const inputSlippage = params.slippage ?? 5;
|
|
655
|
-
const slippageDecimal = inputSlippage / 100;
|
|
656
|
-
const slippage = Math.min(Math.max(slippageDecimal, 0), 0.5);
|
|
657
|
-
let warning;
|
|
658
|
-
if (slippage > 0.1) {
|
|
659
|
-
warning = `\u26A0\uFE0F High slippage tolerance (${(slippage * 100).toFixed(2)}%) \u2014 price may vary significantly.`;
|
|
660
|
-
}
|
|
661
|
-
const estimatedAmountOut = BigInt(data.estimatedAmountOutReduced);
|
|
662
|
-
const slippageBps = BigInt(Math.round(slippage * 1e4));
|
|
663
|
-
const estimatedAmountOutAfterSlippage = estimatedAmountOut * (10000n - slippageBps) / 10000n;
|
|
664
|
-
const pricePerInputToken = estimatedAmountOut * 10n ** BigInt(params.tokenIn.decimals ?? 18) / BigInt(params.amount);
|
|
665
|
-
return {
|
|
666
|
-
amountOut: estimatedAmountOut,
|
|
667
|
-
amountOutUsd: data.estimatedAmountOutUsd,
|
|
668
|
-
amountInUsd: data.amountInUsd,
|
|
669
|
-
minStablecoinsAmount: data.estimatedAmountInAsMinStablecoinAmount,
|
|
670
|
-
tokenIn: {
|
|
671
|
-
address: params.tokenIn.address,
|
|
672
|
-
decimals: params.tokenIn.decimals ?? 18,
|
|
673
|
-
chainId: params.sourceChainId
|
|
674
|
-
},
|
|
675
|
-
tokenOut: {
|
|
676
|
-
address: params.tokenOut.address,
|
|
677
|
-
decimals: params.tokenOut.decimals ?? 18,
|
|
678
|
-
chainId: params.destChainId
|
|
679
|
-
},
|
|
680
|
-
amountIn: params.amount,
|
|
681
|
-
pricePerInputToken,
|
|
682
|
-
slippage,
|
|
683
|
-
internal: {
|
|
684
|
-
...data,
|
|
685
|
-
estimatedAmountOutReduced: estimatedAmountOutAfterSlippage
|
|
686
|
-
},
|
|
687
|
-
warning
|
|
688
|
-
};
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
// src/react/useQuote.ts
|
|
692
|
-
function useQuote(params, options) {
|
|
693
|
-
const [data, setData] = (0, import_react3.useState)(null);
|
|
694
|
-
const [loading, setLoading] = (0, import_react3.useState)(false);
|
|
695
|
-
const [error, setError] = (0, import_react3.useState)(null);
|
|
696
|
-
const [warning, setWarning] = (0, import_react3.useState)(null);
|
|
697
|
-
const debounceMs = options?.debounceMs ?? 250;
|
|
698
|
-
const autoRefreshMs = options?.autoRefreshMs;
|
|
699
|
-
const abortRef = (0, import_react3.useRef)(null);
|
|
700
|
-
const debounceRef = (0, import_react3.useRef)(null);
|
|
701
|
-
const mounted = (0, import_react3.useRef)(false);
|
|
702
|
-
(0, import_react3.useEffect)(() => {
|
|
703
|
-
mounted.current = true;
|
|
704
|
-
return () => {
|
|
705
|
-
mounted.current = false;
|
|
706
|
-
abortRef.current?.abort();
|
|
707
|
-
if (debounceRef.current) clearTimeout(debounceRef.current);
|
|
708
|
-
};
|
|
709
|
-
}, []);
|
|
710
|
-
const fetchQuote = (0, import_react3.useCallback)(
|
|
711
|
-
async () => {
|
|
712
|
-
if (!params) return;
|
|
1727
|
+
// src/react/useTokenList.ts
|
|
1728
|
+
var import_react5 = require("react");
|
|
1729
|
+
function useTokenList() {
|
|
1730
|
+
const [tokens, setTokens] = (0, import_react5.useState)([]);
|
|
1731
|
+
const [loading, setLoading] = (0, import_react5.useState)(false);
|
|
1732
|
+
const [error, setError] = (0, import_react5.useState)(null);
|
|
1733
|
+
const [hasMore, setHasMore] = (0, import_react5.useState)(true);
|
|
1734
|
+
const [page, setPage] = (0, import_react5.useState)(1);
|
|
1735
|
+
const sdk = useSwap();
|
|
1736
|
+
const pageRef = (0, import_react5.useRef)(1);
|
|
1737
|
+
const hasMoreRef = (0, import_react5.useRef)(true);
|
|
1738
|
+
const lastQuery = (0, import_react5.useRef)({});
|
|
1739
|
+
const cache = (0, import_react5.useRef)(/* @__PURE__ */ new Map());
|
|
1740
|
+
const isLoadingRef = (0, import_react5.useRef)(false);
|
|
1741
|
+
pageRef.current = page;
|
|
1742
|
+
hasMoreRef.current = hasMore;
|
|
1743
|
+
const loadTokens = (0, import_react5.useCallback)(
|
|
1744
|
+
async (params) => {
|
|
1745
|
+
const { q, networkId, reset } = params;
|
|
1746
|
+
if (isLoadingRef.current && !reset) return;
|
|
713
1747
|
try {
|
|
1748
|
+
let currentPage = pageRef.current;
|
|
1749
|
+
if (reset) {
|
|
1750
|
+
currentPage = 1;
|
|
1751
|
+
setTokens([]);
|
|
1752
|
+
setPage(1);
|
|
1753
|
+
setHasMore(true);
|
|
1754
|
+
pageRef.current = 1;
|
|
1755
|
+
hasMoreRef.current = true;
|
|
1756
|
+
}
|
|
1757
|
+
if (!reset && !hasMoreRef.current) return;
|
|
1758
|
+
isLoadingRef.current = true;
|
|
714
1759
|
setLoading(true);
|
|
715
|
-
setWarning(null);
|
|
716
|
-
const result = await getQuote(params);
|
|
717
|
-
const serializeResult = serializeBigIntsToStrings(result);
|
|
718
|
-
if (!mounted.current) return;
|
|
719
|
-
setData((prev) => {
|
|
720
|
-
if (JSON.stringify(prev) === JSON.stringify(serializeResult)) return prev;
|
|
721
|
-
return serializeResult;
|
|
722
|
-
});
|
|
723
|
-
setWarning(result.warning ?? null);
|
|
724
1760
|
setError(null);
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
1761
|
+
const cacheKey = JSON.stringify({
|
|
1762
|
+
q: q?.toLowerCase() ?? "",
|
|
1763
|
+
networkId: networkId ?? void 0,
|
|
1764
|
+
page: currentPage
|
|
1765
|
+
});
|
|
1766
|
+
if (cache.current.has(cacheKey)) {
|
|
1767
|
+
const cached = cache.current.get(cacheKey);
|
|
1768
|
+
setTokens((prev) => reset ? cached.results : [...prev, ...cached.results]);
|
|
1769
|
+
if (!reset && cached.results.length > 0) {
|
|
1770
|
+
const nextPage = currentPage + 1;
|
|
1771
|
+
setPage(nextPage);
|
|
1772
|
+
pageRef.current = nextPage;
|
|
1773
|
+
}
|
|
1774
|
+
isLoadingRef.current = false;
|
|
1775
|
+
setLoading(false);
|
|
1776
|
+
return;
|
|
1777
|
+
}
|
|
1778
|
+
const apiParams = {
|
|
1779
|
+
q,
|
|
1780
|
+
page: currentPage,
|
|
1781
|
+
limit: 20,
|
|
1782
|
+
...networkId !== void 0 ? { networkId } : {}
|
|
1783
|
+
};
|
|
1784
|
+
const res = await sdk.getTokenList(apiParams);
|
|
1785
|
+
cache.current.set(cacheKey, res);
|
|
1786
|
+
setTokens((prev) => reset ? res.results : [...prev, ...res.results]);
|
|
1787
|
+
const isLastPage = res.results.length === 0 || res.results.length < 20 || res.count && currentPage * 20 >= res.count;
|
|
1788
|
+
setHasMore(!isLastPage);
|
|
1789
|
+
hasMoreRef.current = !isLastPage;
|
|
1790
|
+
if (!reset && !isLastPage) {
|
|
1791
|
+
const nextPage = currentPage + 1;
|
|
1792
|
+
setPage(nextPage);
|
|
1793
|
+
pageRef.current = nextPage;
|
|
1794
|
+
}
|
|
1795
|
+
lastQuery.current = { q, networkId };
|
|
1796
|
+
} catch (e) {
|
|
1797
|
+
console.error("useTokenList error:", e);
|
|
1798
|
+
setError("Failed to load tokens");
|
|
729
1799
|
} finally {
|
|
730
|
-
|
|
1800
|
+
setLoading(false);
|
|
1801
|
+
isLoadingRef.current = false;
|
|
731
1802
|
}
|
|
732
1803
|
},
|
|
733
|
-
[
|
|
734
|
-
);
|
|
735
|
-
(0, import_react3.useEffect)(() => {
|
|
736
|
-
if (!params) return;
|
|
737
|
-
if (debounceRef.current) clearTimeout(debounceRef.current);
|
|
738
|
-
debounceRef.current = setTimeout(() => {
|
|
739
|
-
fetchQuote();
|
|
740
|
-
}, debounceMs);
|
|
741
|
-
return () => {
|
|
742
|
-
if (debounceRef.current) clearTimeout(debounceRef.current);
|
|
743
|
-
abortRef.current?.abort();
|
|
744
|
-
};
|
|
745
|
-
}, [params, debounceMs, fetchQuote]);
|
|
746
|
-
(0, import_react3.useEffect)(() => {
|
|
747
|
-
if (!autoRefreshMs || !params) return;
|
|
748
|
-
const interval = setInterval(() => fetchQuote(), autoRefreshMs);
|
|
749
|
-
return () => clearInterval(interval);
|
|
750
|
-
}, [autoRefreshMs, params, fetchQuote]);
|
|
751
|
-
return (0, import_react3.useMemo)(
|
|
752
|
-
() => ({
|
|
753
|
-
data,
|
|
754
|
-
loading,
|
|
755
|
-
error,
|
|
756
|
-
warning,
|
|
757
|
-
refetch: () => fetchQuote()
|
|
758
|
-
}),
|
|
759
|
-
[data, loading, error, warning, fetchQuote]
|
|
1804
|
+
[sdk]
|
|
760
1805
|
);
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
const { signal } = options ?? {};
|
|
771
|
-
if (!addresses?.evm && !addresses?.svm) {
|
|
772
|
-
throw new Error("At least one address (EVM or SVM) must be provided.");
|
|
773
|
-
}
|
|
774
|
-
const payload = JSON.stringify({
|
|
775
|
-
addresses,
|
|
776
|
-
cursorEvm,
|
|
777
|
-
cursorSvm
|
|
778
|
-
});
|
|
779
|
-
const start = performance.now();
|
|
780
|
-
const response = await fetch(`${import_intents_sdk9.TOKEN_SEARCH_API_BASE_URL}/tokens/balances`, {
|
|
781
|
-
method: "POST",
|
|
782
|
-
headers: {
|
|
783
|
-
accept: "application/json",
|
|
784
|
-
"Content-Type": "application/json"
|
|
785
|
-
},
|
|
786
|
-
body: payload,
|
|
787
|
-
signal
|
|
788
|
-
}).catch((err) => {
|
|
789
|
-
if (err.name === "AbortError") {
|
|
790
|
-
throw new Error("Balance request was cancelled.");
|
|
791
|
-
}
|
|
792
|
-
throw err;
|
|
793
|
-
});
|
|
794
|
-
if (!response.ok) {
|
|
795
|
-
const text = await response.text().catch(() => "");
|
|
796
|
-
throw new Error(`Failed to fetch balances: ${response.status} ${text}`);
|
|
797
|
-
}
|
|
798
|
-
const data = await response.json().catch(() => {
|
|
799
|
-
throw new Error("Invalid JSON response from balances API.");
|
|
800
|
-
});
|
|
801
|
-
const duration = (performance.now() - start).toFixed(1);
|
|
802
|
-
if (process.env.NODE_ENV !== "production") {
|
|
803
|
-
console.debug(`[Shogun SDK] Fetched balances in ${duration}ms`);
|
|
804
|
-
}
|
|
805
|
-
const evmItems = data.evm?.items ?? [];
|
|
806
|
-
const svmItems = data.svm?.items ?? [];
|
|
807
|
-
const combined = [...evmItems, ...svmItems];
|
|
1806
|
+
const resetTokens = (0, import_react5.useCallback)(() => {
|
|
1807
|
+
setTokens([]);
|
|
1808
|
+
setPage(1);
|
|
1809
|
+
setHasMore(true);
|
|
1810
|
+
pageRef.current = 1;
|
|
1811
|
+
hasMoreRef.current = true;
|
|
1812
|
+
cache.current.clear();
|
|
1813
|
+
lastQuery.current = {};
|
|
1814
|
+
}, []);
|
|
808
1815
|
return {
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
1816
|
+
tokens,
|
|
1817
|
+
loading,
|
|
1818
|
+
error,
|
|
1819
|
+
hasMore,
|
|
1820
|
+
page,
|
|
1821
|
+
lastQuery: lastQuery.current,
|
|
1822
|
+
loadTokens,
|
|
1823
|
+
resetTokens
|
|
812
1824
|
};
|
|
813
1825
|
}
|
|
814
1826
|
|
|
815
|
-
// src/react/
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
const
|
|
819
|
-
const [
|
|
820
|
-
const
|
|
821
|
-
const
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
1827
|
+
// src/react/useTokensData.ts
|
|
1828
|
+
var import_react6 = require("react");
|
|
1829
|
+
function useTokensData(addresses) {
|
|
1830
|
+
const sdk = useSwap();
|
|
1831
|
+
const [data, setData] = (0, import_react6.useState)([]);
|
|
1832
|
+
const [loading, setLoading] = (0, import_react6.useState)(false);
|
|
1833
|
+
const [error, setError] = (0, import_react6.useState)(null);
|
|
1834
|
+
(0, import_react6.useEffect)(() => {
|
|
1835
|
+
if (!addresses?.length) return;
|
|
1836
|
+
let isMounted = true;
|
|
1837
|
+
setLoading(true);
|
|
1838
|
+
setError(null);
|
|
1839
|
+
sdk.getTokensData(addresses).then((res) => {
|
|
1840
|
+
if (isMounted) setData(res);
|
|
1841
|
+
}).catch((e) => {
|
|
1842
|
+
if (isMounted) setError(e instanceof Error ? e : new Error(String(e)));
|
|
1843
|
+
}).finally(() => {
|
|
1844
|
+
if (isMounted) setLoading(false);
|
|
1845
|
+
});
|
|
1846
|
+
return () => {
|
|
1847
|
+
isMounted = false;
|
|
831
1848
|
};
|
|
832
|
-
}, [
|
|
833
|
-
|
|
834
|
-
|
|
1849
|
+
}, [sdk, JSON.stringify(addresses)]);
|
|
1850
|
+
return { data, loading, error };
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
// src/react/useOrders.ts
|
|
1854
|
+
var import_react7 = require("react");
|
|
1855
|
+
var import_swr3 = __toESM(require("swr"), 1);
|
|
1856
|
+
var ORDERS_KEY = "orders-global";
|
|
1857
|
+
function hasValidAddress(addrs) {
|
|
1858
|
+
if (!addrs) return false;
|
|
1859
|
+
return Boolean(addrs.evmAddress || addrs.solAddress || addrs.suiAddress);
|
|
1860
|
+
}
|
|
1861
|
+
function useOrders(initialAddresses) {
|
|
1862
|
+
const sdk = useSwap();
|
|
1863
|
+
const abortRef = (0, import_react7.useRef)(null);
|
|
1864
|
+
const addrRef = globalThis.__ORDERS_ADDR_REF__ ?? (globalThis.__ORDERS_ADDR_REF__ = { current: initialAddresses ?? null });
|
|
1865
|
+
(0, import_react7.useEffect)(() => {
|
|
1866
|
+
if (initialAddresses && JSON.stringify(addrRef.current) !== JSON.stringify(initialAddresses)) {
|
|
1867
|
+
addrRef.current = initialAddresses;
|
|
1868
|
+
void (0, import_swr3.mutate)(ORDERS_KEY);
|
|
1869
|
+
}
|
|
1870
|
+
}, [initialAddresses]);
|
|
1871
|
+
const fetcher = (0, import_react7.useCallback)(async () => {
|
|
1872
|
+
const active = addrRef.current;
|
|
1873
|
+
if (!hasValidAddress(active)) return null;
|
|
835
1874
|
if (abortRef.current) abortRef.current.abort();
|
|
836
1875
|
const controller = new AbortController();
|
|
837
1876
|
abortRef.current = controller;
|
|
838
|
-
setLoading(true);
|
|
839
|
-
setError(null);
|
|
840
1877
|
try {
|
|
841
|
-
|
|
842
|
-
setData((prev) => {
|
|
843
|
-
if (JSON.stringify(prev) === JSON.stringify(result)) return prev;
|
|
844
|
-
return result;
|
|
845
|
-
});
|
|
846
|
-
return result;
|
|
1878
|
+
return await sdk.getOrders(active ?? {});
|
|
847
1879
|
} catch (err) {
|
|
848
|
-
if (err.name === "AbortError") return;
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
throw e;
|
|
852
|
-
} finally {
|
|
853
|
-
setLoading(false);
|
|
1880
|
+
if (err instanceof DOMException && err.name === "AbortError") return null;
|
|
1881
|
+
if (err instanceof Error) throw err;
|
|
1882
|
+
throw new Error(String(err));
|
|
854
1883
|
}
|
|
855
|
-
}, [
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
1884
|
+
}, [sdk]);
|
|
1885
|
+
const {
|
|
1886
|
+
data,
|
|
1887
|
+
error,
|
|
1888
|
+
isValidating: loading,
|
|
1889
|
+
mutate: mutateOrders
|
|
1890
|
+
} = (0, import_swr3.default)(ORDERS_KEY, fetcher, {
|
|
1891
|
+
revalidateOnFocus: false,
|
|
1892
|
+
revalidateOnReconnect: false,
|
|
1893
|
+
shouldRetryOnError: false,
|
|
1894
|
+
keepPreviousData: true
|
|
1895
|
+
});
|
|
1896
|
+
const refetch = (0, import_react7.useCallback)(async () => {
|
|
1897
|
+
await mutateOrders();
|
|
1898
|
+
}, [mutateOrders]);
|
|
1899
|
+
const setAddresses = (0, import_react7.useCallback)(
|
|
1900
|
+
(next) => {
|
|
1901
|
+
if (!next) return;
|
|
1902
|
+
addrRef.current = next;
|
|
1903
|
+
void (0, import_swr3.mutate)(ORDERS_KEY);
|
|
1904
|
+
},
|
|
1905
|
+
[]
|
|
1906
|
+
);
|
|
1907
|
+
return (0, import_react7.useMemo)(
|
|
864
1908
|
() => ({
|
|
865
|
-
/** Latest fetched balance data */
|
|
866
1909
|
data,
|
|
867
|
-
/** Whether the hook is currently fetching */
|
|
868
1910
|
loading,
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
1911
|
+
error: error instanceof Error ? error.message : null,
|
|
1912
|
+
refetch,
|
|
1913
|
+
setAddresses,
|
|
1914
|
+
get activeAddresses() {
|
|
1915
|
+
return addrRef.current;
|
|
1916
|
+
}
|
|
873
1917
|
}),
|
|
874
|
-
[data, loading, error,
|
|
1918
|
+
[data, loading, error, refetch, setAddresses]
|
|
875
1919
|
);
|
|
876
1920
|
}
|
|
877
1921
|
|
|
878
|
-
// src/react/
|
|
879
|
-
var
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
1922
|
+
// src/react/useCancelOrder.ts
|
|
1923
|
+
var import_react8 = require("react");
|
|
1924
|
+
var import_swr4 = require("swr");
|
|
1925
|
+
function useCancelOrder() {
|
|
1926
|
+
const sdk = useSwap();
|
|
1927
|
+
const [isLoading, setLoading] = (0, import_react8.useState)(false);
|
|
1928
|
+
const [error, setError] = (0, import_react8.useState)(null);
|
|
1929
|
+
const [result, setResult] = (0, import_react8.useState)(null);
|
|
1930
|
+
const cancel = (0, import_react8.useCallback)(
|
|
1931
|
+
async (params) => {
|
|
1932
|
+
setLoading(true);
|
|
1933
|
+
setError(null);
|
|
1934
|
+
setResult(null);
|
|
1935
|
+
try {
|
|
1936
|
+
const tx = await sdk.cancelOrder({
|
|
1937
|
+
order: params.order,
|
|
1938
|
+
wallet: params.wallet,
|
|
1939
|
+
solRpc: params.solRpc
|
|
1940
|
+
});
|
|
1941
|
+
setResult(tx);
|
|
1942
|
+
void (0, import_swr4.mutate)("orders-global");
|
|
1943
|
+
return tx;
|
|
1944
|
+
} catch (err) {
|
|
1945
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1946
|
+
setError(msg);
|
|
1947
|
+
throw err;
|
|
1948
|
+
} finally {
|
|
1949
|
+
setLoading(false);
|
|
1950
|
+
}
|
|
1951
|
+
},
|
|
1952
|
+
[sdk]
|
|
1953
|
+
);
|
|
1954
|
+
return {
|
|
1955
|
+
cancel,
|
|
1956
|
+
isLoading,
|
|
1957
|
+
error,
|
|
1958
|
+
result
|
|
1959
|
+
};
|
|
1960
|
+
}
|