@one_deploy/sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/.turbo/turbo-build.log +0 -0
  2. package/.turbo/turbo-type-check.log +0 -0
  3. package/dist/config/index.d.mts +74 -0
  4. package/dist/config/index.d.ts +74 -0
  5. package/dist/config/index.js +242 -0
  6. package/dist/config/index.js.map +1 -0
  7. package/dist/config/index.mjs +224 -0
  8. package/dist/config/index.mjs.map +1 -0
  9. package/dist/engine-5ndtBaCr.d.ts +1039 -0
  10. package/dist/engine-CrlhH0nw.d.mts +1039 -0
  11. package/dist/hooks/index.d.mts +56 -0
  12. package/dist/hooks/index.d.ts +56 -0
  13. package/dist/hooks/index.js +1360 -0
  14. package/dist/hooks/index.js.map +1 -0
  15. package/dist/hooks/index.mjs +1356 -0
  16. package/dist/hooks/index.mjs.map +1 -0
  17. package/dist/index.d.mts +356 -0
  18. package/dist/index.d.ts +356 -0
  19. package/dist/index.js +5068 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/index.mjs +4949 -0
  22. package/dist/index.mjs.map +1 -0
  23. package/dist/price-CgqXPnT3.d.ts +13 -0
  24. package/dist/price-ClbLHHjv.d.mts +13 -0
  25. package/dist/providers/index.d.mts +121 -0
  26. package/dist/providers/index.d.ts +121 -0
  27. package/dist/providers/index.js +1642 -0
  28. package/dist/providers/index.js.map +1 -0
  29. package/dist/providers/index.mjs +1600 -0
  30. package/dist/providers/index.mjs.map +1 -0
  31. package/dist/react-native.d.mts +120 -0
  32. package/dist/react-native.d.ts +120 -0
  33. package/dist/react-native.js +1792 -0
  34. package/dist/react-native.js.map +1 -0
  35. package/dist/react-native.mjs +1755 -0
  36. package/dist/react-native.mjs.map +1 -0
  37. package/dist/services/index.d.mts +85 -0
  38. package/dist/services/index.d.ts +85 -0
  39. package/dist/services/index.js +1466 -0
  40. package/dist/services/index.js.map +1 -0
  41. package/dist/services/index.mjs +1458 -0
  42. package/dist/services/index.mjs.map +1 -0
  43. package/dist/types/index.d.mts +759 -0
  44. package/dist/types/index.d.ts +759 -0
  45. package/dist/types/index.js +4 -0
  46. package/dist/types/index.js.map +1 -0
  47. package/dist/types/index.mjs +3 -0
  48. package/dist/types/index.mjs.map +1 -0
  49. package/dist/utils/index.d.mts +36 -0
  50. package/dist/utils/index.d.ts +36 -0
  51. package/dist/utils/index.js +164 -0
  52. package/dist/utils/index.js.map +1 -0
  53. package/dist/utils/index.mjs +142 -0
  54. package/dist/utils/index.mjs.map +1 -0
  55. package/package.json +101 -0
  56. package/src/components/OneConnectButton.tsx +143 -0
  57. package/src/components/OneNFTGallery.tsx +324 -0
  58. package/src/components/OneOfframpWidget.tsx +660 -0
  59. package/src/components/OneOnrampWidget.tsx +596 -0
  60. package/src/components/OnePayWidget.tsx +160 -0
  61. package/src/components/OneReceiveWidget.tsx +272 -0
  62. package/src/components/OneSendWidget.tsx +248 -0
  63. package/src/components/OneSwapWidget.tsx +715 -0
  64. package/src/components/OneTransactionButton.tsx +150 -0
  65. package/src/components/OneWalletBalance.tsx +354 -0
  66. package/src/components/index.ts +24 -0
  67. package/src/config/index.ts +299 -0
  68. package/src/hooks/index.ts +2 -0
  69. package/src/hooks/useTokenPrice.ts +162 -0
  70. package/src/hooks/useWalletBalance.ts +98 -0
  71. package/src/index.ts +193 -0
  72. package/src/providers/OneProvider.tsx +452 -0
  73. package/src/providers/ThirdwebProvider.tsx +203 -0
  74. package/src/providers/index.ts +26 -0
  75. package/src/react-native.ts +378 -0
  76. package/src/services/engine.ts +1854 -0
  77. package/src/services/index.ts +30 -0
  78. package/src/services/price.ts +164 -0
  79. package/src/services/supabase.ts +180 -0
  80. package/src/types/index.ts +887 -0
  81. package/src/utils/index.ts +200 -0
  82. package/tsconfig.json +22 -0
  83. package/tsup.config.ts +25 -0
@@ -0,0 +1,1356 @@
1
+ import { useState, useRef, useCallback, useEffect } from 'react';
2
+
3
+ function getConfig() {
4
+ {
5
+ throw new Error("ONE SDK not initialized. Call initOneSDK() first.");
6
+ }
7
+ }
8
+
9
+ // src/services/engine.ts
10
+ var OneEngineClient = class {
11
+ constructor(options) {
12
+ const config2 = getConfig();
13
+ this.baseUrl = options?.baseUrl || config2.oneEngineUrl;
14
+ this.clientId = options?.clientId || config2.oneClientId || "";
15
+ this.secretKey = options?.secretKey || config2.oneSecretKey;
16
+ }
17
+ /**
18
+ * Set access token for authenticated requests
19
+ */
20
+ setAccessToken(token) {
21
+ this.accessToken = token;
22
+ }
23
+ /**
24
+ * Clear access token
25
+ */
26
+ clearAccessToken() {
27
+ this.accessToken = void 0;
28
+ }
29
+ getHeaders(includeSecret = false) {
30
+ const headers = {
31
+ "Content-Type": "application/json",
32
+ "x-client-id": this.clientId
33
+ };
34
+ if (this.accessToken) {
35
+ headers["Authorization"] = `Bearer ${this.accessToken}`;
36
+ }
37
+ if (includeSecret && this.secretKey) {
38
+ headers["x-secret-key"] = this.secretKey;
39
+ }
40
+ return headers;
41
+ }
42
+ async request(endpoint, options = {}, includeSecret = false) {
43
+ try {
44
+ const response = await fetch(`${this.baseUrl}${endpoint}`, {
45
+ ...options,
46
+ headers: {
47
+ ...this.getHeaders(includeSecret),
48
+ ...options.headers
49
+ }
50
+ });
51
+ const data = await response.json();
52
+ if (!response.ok) {
53
+ return {
54
+ success: false,
55
+ error: {
56
+ code: data.error?.code || `HTTP_${response.status}`,
57
+ message: data.error?.message || "Request failed"
58
+ }
59
+ };
60
+ }
61
+ return {
62
+ success: true,
63
+ data: data.data || data
64
+ };
65
+ } catch (error) {
66
+ return {
67
+ success: false,
68
+ error: {
69
+ code: "NETWORK_ERROR",
70
+ message: error instanceof Error ? error.message : "Network request failed"
71
+ }
72
+ };
73
+ }
74
+ }
75
+ // ===============================
76
+ // AUTH ENDPOINTS
77
+ // ===============================
78
+ /**
79
+ * Send OTP to email for authentication
80
+ */
81
+ async sendEmailOtp(email) {
82
+ return this.request("/api/v1/auth/otp", {
83
+ method: "POST",
84
+ body: JSON.stringify({ email })
85
+ });
86
+ }
87
+ /**
88
+ * Verify OTP and get access token
89
+ */
90
+ async verifyEmailOtp(email, otp) {
91
+ return this.request("/api/v1/auth/otp/verify", {
92
+ method: "POST",
93
+ body: JSON.stringify({ email, otp })
94
+ });
95
+ }
96
+ /**
97
+ * Authenticate with wallet signature
98
+ */
99
+ async authWithWallet(walletAddress, signature, message) {
100
+ return this.request("/api/v1/auth/wallet", {
101
+ method: "POST",
102
+ body: JSON.stringify({ walletAddress, signature, message })
103
+ });
104
+ }
105
+ /**
106
+ * Refresh access token
107
+ */
108
+ async refreshToken(refreshToken) {
109
+ return this.request("/api/v1/auth/refresh", {
110
+ method: "POST",
111
+ body: JSON.stringify({ refreshToken })
112
+ });
113
+ }
114
+ /**
115
+ * Get current user
116
+ */
117
+ async getCurrentUser() {
118
+ return this.request("/api/v1/auth/me", { method: "GET" });
119
+ }
120
+ /**
121
+ * Sign out
122
+ */
123
+ async signOut() {
124
+ return this.request("/api/v1/auth/logout", { method: "POST" });
125
+ }
126
+ // ===============================
127
+ // WALLET/ASSETS ENDPOINTS
128
+ // ===============================
129
+ /**
130
+ * Get wallet balance across all chains
131
+ */
132
+ async getWalletBalance(walletAddress, chains) {
133
+ const params = new URLSearchParams({ address: walletAddress });
134
+ if (chains?.length && chains.length > 0) {
135
+ params.set("chainId", chains[0].toString());
136
+ }
137
+ return this.request(`/api/v1/assets?${params}`, { method: "GET" });
138
+ }
139
+ /**
140
+ * Get portfolio summary
141
+ */
142
+ async getPortfolioSummary(walletAddress) {
143
+ const params = new URLSearchParams({ address: walletAddress });
144
+ return this.request(`/api/v1/assets/portfolio?${params}`, { method: "GET" });
145
+ }
146
+ /**
147
+ * Get user's wallets
148
+ */
149
+ async getUserWallets(chainId) {
150
+ const params = chainId ? `?chainId=${chainId}` : "";
151
+ return this.request(`/api/v1/wallet${params}`, { method: "GET" });
152
+ }
153
+ /**
154
+ * Create a new wallet
155
+ */
156
+ async createWallet(chainId = 8453, type = "smart") {
157
+ return this.request("/api/v1/wallet", {
158
+ method: "POST",
159
+ body: JSON.stringify({ chainId, type })
160
+ });
161
+ }
162
+ /**
163
+ * Get wallet transactions (placeholder - needs endpoint)
164
+ */
165
+ async getWalletTransactions(walletAddress, options) {
166
+ const params = new URLSearchParams({ address: walletAddress });
167
+ if (options?.limit) params.set("limit", options.limit.toString());
168
+ if (options?.offset) params.set("offset", options.offset.toString());
169
+ if (options?.chainId) params.set("chainId", options.chainId.toString());
170
+ return this.request(`/api/v1/assets/transactions?${params}`, { method: "GET" });
171
+ }
172
+ /**
173
+ * Send native token or ERC20
174
+ */
175
+ async sendTransaction(request) {
176
+ return this.request("/api/v1/wallet/send", {
177
+ method: "POST",
178
+ body: JSON.stringify(request)
179
+ });
180
+ }
181
+ /**
182
+ * Get transaction status
183
+ */
184
+ async getTransactionStatus(txId) {
185
+ return this.request(`/api/v1/wallet/transaction/${txId}`, { method: "GET" });
186
+ }
187
+ // ===============================
188
+ // ONRAMP ENDPOINTS (Fiat-to-Crypto)
189
+ // ===============================
190
+ /**
191
+ * Get onramp quote
192
+ */
193
+ async getOnrampQuote(fiatCurrency, fiatAmount, cryptoCurrency, paymentMethod) {
194
+ const params = new URLSearchParams({
195
+ fiatCurrency,
196
+ fiatAmount: fiatAmount.toString(),
197
+ cryptoCurrency
198
+ });
199
+ if (paymentMethod) params.set("paymentMethod", paymentMethod);
200
+ return this.request(`/api/v1/fiat/onramp/quote?${params}`, { method: "GET" });
201
+ }
202
+ /**
203
+ * Create onramp session (returns widget URL)
204
+ */
205
+ async createOnrampSession(request) {
206
+ return this.request("/api/v1/fiat/onramp", {
207
+ method: "POST",
208
+ body: JSON.stringify({
209
+ fiatCurrency: request.fiatCurrency || "USD",
210
+ fiatAmount: request.fiatAmount || 100,
211
+ cryptoCurrency: request.cryptoCurrency || "ETH",
212
+ walletAddress: request.walletAddress,
213
+ chainId: 8453
214
+ // Default to Base
215
+ })
216
+ });
217
+ }
218
+ /**
219
+ * Get onramp session status
220
+ */
221
+ async getOnrampStatus(sessionId) {
222
+ return this.request(`/api/v1/fiat/onramp/${sessionId}`, { method: "GET" });
223
+ }
224
+ /**
225
+ * Get supported currencies (fiat + crypto)
226
+ */
227
+ async getSupportedCurrencies() {
228
+ return this.request("/api/v1/fiat/onramp", { method: "GET" });
229
+ }
230
+ /**
231
+ * Get supported fiat currencies
232
+ */
233
+ async getSupportedFiatCurrencies() {
234
+ const result = await this.getSupportedCurrencies();
235
+ if (result.success && result.data) {
236
+ return { success: true, data: result.data.fiatCurrencies };
237
+ }
238
+ return { success: false, error: result.error };
239
+ }
240
+ /**
241
+ * Get supported payment methods
242
+ */
243
+ async getSupportedPaymentMethods(country) {
244
+ return { success: true, data: ["card", "bank_transfer", "apple_pay", "google_pay"] };
245
+ }
246
+ // ===============================
247
+ // SWAP ENDPOINTS
248
+ // ===============================
249
+ /**
250
+ * Get swap quote
251
+ */
252
+ async getSwapQuote(request) {
253
+ return this.request("/api/v1/swap/quote", {
254
+ method: "POST",
255
+ body: JSON.stringify(request)
256
+ });
257
+ }
258
+ /**
259
+ * Execute swap
260
+ */
261
+ async executeSwap(request) {
262
+ return this.request("/api/v1/swap/execute", {
263
+ method: "POST",
264
+ body: JSON.stringify(request)
265
+ });
266
+ }
267
+ /**
268
+ * Get swap status
269
+ */
270
+ async getSwapStatus(swapId) {
271
+ return this.request(`/api/v1/swap/${swapId}`, { method: "GET" });
272
+ }
273
+ /**
274
+ * Get supported tokens for swap
275
+ */
276
+ async getSupportedSwapTokens(chainId) {
277
+ const params = chainId ? `?chainId=${chainId}` : "";
278
+ return this.request(`/api/v1/swap/tokens${params}`, { method: "GET" });
279
+ }
280
+ /**
281
+ * Get supported chains for swap
282
+ */
283
+ async getSupportedSwapChains() {
284
+ return this.request("/api/v1/swap/chains", { method: "GET" });
285
+ }
286
+ // ===============================
287
+ // AI TRADING/QUANT ENDPOINTS
288
+ // ===============================
289
+ /**
290
+ * Get available AI trading strategies
291
+ */
292
+ async getStrategies() {
293
+ return this.request("/api/v1/quant/strategies", { method: "GET" });
294
+ }
295
+ /**
296
+ * Get strategy details
297
+ */
298
+ async getStrategy(strategyId) {
299
+ return this.request(`/api/v1/quant/strategies/${strategyId}`, { method: "GET" });
300
+ }
301
+ /**
302
+ * Get user's positions
303
+ */
304
+ async getPositions() {
305
+ return this.request("/api/v1/quant/positions", { method: "GET" });
306
+ }
307
+ /**
308
+ * Create investment order
309
+ */
310
+ async createOrder(strategyId, amount, currency) {
311
+ return this.request("/api/v1/trading/orders", {
312
+ method: "POST",
313
+ body: JSON.stringify({ strategyId, amount, currency })
314
+ });
315
+ }
316
+ /**
317
+ * Get user's orders
318
+ */
319
+ async getUserOrders() {
320
+ return this.request("/api/v1/trading/orders", { method: "GET" });
321
+ }
322
+ /**
323
+ * Get user's portfolio stats from positions
324
+ */
325
+ async getPortfolioStats() {
326
+ const positionsResult = await this.getPositions();
327
+ if (positionsResult.success && positionsResult.data) {
328
+ const positions = positionsResult.data;
329
+ const totalInvested = positions.reduce((sum, p) => sum + (p.investedAmount || 0), 0);
330
+ const totalValue = positions.reduce((sum, p) => sum + (p.currentValue || 0), 0);
331
+ const totalPnl = totalValue - totalInvested;
332
+ const totalPnlPercent = totalInvested > 0 ? totalPnl / totalInvested * 100 : 0;
333
+ return {
334
+ success: true,
335
+ data: {
336
+ totalInvested,
337
+ totalValue,
338
+ totalPnl,
339
+ totalPnlPercent,
340
+ activePositions: positions.filter((p) => p.status === "active").length
341
+ }
342
+ };
343
+ }
344
+ return {
345
+ success: true,
346
+ data: { totalInvested: 0, totalValue: 0, totalPnl: 0, totalPnlPercent: 0, activePositions: 0 }
347
+ };
348
+ }
349
+ // ===============================
350
+ // MARKET/PRICE ENDPOINTS
351
+ // ===============================
352
+ /**
353
+ * Get token prices
354
+ */
355
+ async getTokenPrices(symbols) {
356
+ const bybitSymbols = symbols.map((s) => {
357
+ const upper = s.toUpperCase();
358
+ if (upper.endsWith("USDT")) return upper;
359
+ return `${upper}USDT`;
360
+ });
361
+ const result = await this.request(
362
+ `/api/v1/trading/market?symbols=${bybitSymbols.join(",")}`,
363
+ { method: "GET" }
364
+ );
365
+ if (result.success && result.data?.markets) {
366
+ const prices = {};
367
+ for (const market of result.data.markets) {
368
+ const symbol = market.symbol?.replace("USDT", "") || "";
369
+ prices[symbol] = {
370
+ price: parseFloat(market.lastPrice) || 0,
371
+ change24h: parseFloat(market.price24hPcnt) * 100 || 0,
372
+ marketCap: void 0
373
+ // Bybit doesn't provide this
374
+ };
375
+ }
376
+ return { success: true, data: prices };
377
+ }
378
+ return { success: false, error: result.error };
379
+ }
380
+ /**
381
+ * Get market data overview
382
+ */
383
+ async getMarketData() {
384
+ const result = await this.request("/api/v1/trading/market", { method: "GET" });
385
+ if (result.success && result.data?.markets) {
386
+ return {
387
+ success: true,
388
+ data: {
389
+ totalMarketCap: 0,
390
+ // Would need separate API
391
+ totalVolume24h: result.data.markets.reduce((sum, m) => sum + (parseFloat(m.volume24h) || 0), 0),
392
+ btcDominance: 0,
393
+ // Would need separate API
394
+ markets: result.data.markets
395
+ }
396
+ };
397
+ }
398
+ return { success: false, error: result.error };
399
+ }
400
+ // ===============================
401
+ // NFT ENDPOINTS
402
+ // ===============================
403
+ /**
404
+ * Get user's NFTs
405
+ */
406
+ async getUserNFTs(walletAddress, options) {
407
+ const params = new URLSearchParams({ address: walletAddress });
408
+ if (options?.chainId) params.set("chainId", options.chainId.toString());
409
+ if (options?.limit) params.set("limit", options.limit.toString());
410
+ if (options?.offset) params.set("offset", options.offset.toString());
411
+ return this.request(`/api/v1/assets/nfts?${params}`, { method: "GET" });
412
+ }
413
+ /**
414
+ * Get NFT details
415
+ */
416
+ async getNFTDetails(contractAddress, tokenId, chainId) {
417
+ return this.request(`/api/v1/assets/nfts/${contractAddress}/${tokenId}?chainId=${chainId}`, { method: "GET" });
418
+ }
419
+ /**
420
+ * Get NFT collection
421
+ */
422
+ async getNFTCollection(contractAddress, chainId) {
423
+ return this.request(`/api/v1/assets/nfts/collection/${contractAddress}?chainId=${chainId}`, { method: "GET" });
424
+ }
425
+ /**
426
+ * Transfer NFT
427
+ */
428
+ async transferNFT(params) {
429
+ return this.request("/api/v1/assets/nfts/transfer", {
430
+ method: "POST",
431
+ body: JSON.stringify(params)
432
+ });
433
+ }
434
+ // ===============================
435
+ // CONTRACT ENDPOINTS
436
+ // ===============================
437
+ /**
438
+ * Get user's contracts
439
+ */
440
+ async getUserContracts(options) {
441
+ const params = new URLSearchParams();
442
+ if (options?.chainId) params.set("chainId", options.chainId.toString());
443
+ if (options?.limit) params.set("limit", options.limit.toString());
444
+ if (options?.offset) params.set("offset", options.offset.toString());
445
+ return this.request(`/api/v1/contracts?${params}`, { method: "GET" });
446
+ }
447
+ /**
448
+ * Get contract details
449
+ */
450
+ async getContractDetails(address, chainId) {
451
+ return this.request(`/api/v1/contracts/${address}?chainId=${chainId}`, { method: "GET" });
452
+ }
453
+ /**
454
+ * Read contract (call view function)
455
+ */
456
+ async readContract(params) {
457
+ return this.request("/api/v1/contracts/read", {
458
+ method: "POST",
459
+ body: JSON.stringify(params)
460
+ });
461
+ }
462
+ /**
463
+ * Write to contract (execute transaction)
464
+ */
465
+ async writeContract(params) {
466
+ return this.request("/api/v1/contracts/write", {
467
+ method: "POST",
468
+ body: JSON.stringify(params)
469
+ });
470
+ }
471
+ /**
472
+ * Deploy contract
473
+ */
474
+ async deployContract(params) {
475
+ return this.request("/api/v1/contracts/deploy", {
476
+ method: "POST",
477
+ body: JSON.stringify(params)
478
+ });
479
+ }
480
+ // ===============================
481
+ // OFFRAMP ENDPOINTS (Crypto-to-Fiat)
482
+ // ===============================
483
+ /**
484
+ * Get offramp quote
485
+ */
486
+ async getOfframpQuote(cryptoCurrency, cryptoAmount, fiatCurrency, payoutMethod) {
487
+ const params = new URLSearchParams({
488
+ cryptoCurrency,
489
+ cryptoAmount: cryptoAmount.toString(),
490
+ fiatCurrency
491
+ });
492
+ if (payoutMethod) params.set("payoutMethod", payoutMethod);
493
+ return this.request(`/api/v1/fiat/offramp/quote?${params}`, { method: "GET" });
494
+ }
495
+ /**
496
+ * Create offramp transaction
497
+ */
498
+ async createOfframpTransaction(request) {
499
+ return this.request("/api/v1/fiat/offramp", {
500
+ method: "POST",
501
+ body: JSON.stringify(request)
502
+ });
503
+ }
504
+ /**
505
+ * Get offramp transaction status
506
+ */
507
+ async getOfframpStatus(transactionId) {
508
+ return this.request(`/api/v1/fiat/offramp/${transactionId}`, { method: "GET" });
509
+ }
510
+ /**
511
+ * Get supported payout methods
512
+ */
513
+ async getSupportedPayoutMethods(country) {
514
+ const params = country ? `?country=${country}` : "";
515
+ return this.request(`/api/v1/fiat/offramp/methods${params}`, { method: "GET" });
516
+ }
517
+ // ===============================
518
+ // BILL PAYMENT ENDPOINTS
519
+ // ===============================
520
+ /**
521
+ * Get bill providers
522
+ */
523
+ async getBillProviders(country, category) {
524
+ const params = new URLSearchParams();
525
+ if (country) params.set("country", country);
526
+ if (category) params.set("category", category);
527
+ return this.request(`/api/v1/bills/providers?${params}`, { method: "GET" });
528
+ }
529
+ /**
530
+ * Get bill details/validate account
531
+ */
532
+ async validateBillAccount(providerId, accountNumber) {
533
+ return this.request("/api/v1/bills/validate", {
534
+ method: "POST",
535
+ body: JSON.stringify({ providerId, accountNumber })
536
+ });
537
+ }
538
+ /**
539
+ * Pay bill
540
+ */
541
+ async payBill(params) {
542
+ return this.request("/api/v1/bills/pay", {
543
+ method: "POST",
544
+ body: JSON.stringify(params)
545
+ });
546
+ }
547
+ /**
548
+ * Get bill payment history
549
+ */
550
+ async getBillHistory(options) {
551
+ const params = new URLSearchParams();
552
+ if (options?.limit) params.set("limit", options.limit.toString());
553
+ if (options?.offset) params.set("offset", options.offset.toString());
554
+ return this.request(`/api/v1/bills/history?${params}`, { method: "GET" });
555
+ }
556
+ // ===============================
557
+ // STAKING ENDPOINTS
558
+ // ===============================
559
+ /**
560
+ * Get staking pools
561
+ */
562
+ async getStakingPools(chainId) {
563
+ const params = chainId ? `?chainId=${chainId}` : "";
564
+ return this.request(`/api/v1/staking/pools${params}`, { method: "GET" });
565
+ }
566
+ /**
567
+ * Get user's staking positions
568
+ */
569
+ async getStakingPositions() {
570
+ return this.request("/api/v1/staking/positions", { method: "GET" });
571
+ }
572
+ /**
573
+ * Stake tokens
574
+ */
575
+ async stake(params) {
576
+ return this.request("/api/v1/staking/stake", {
577
+ method: "POST",
578
+ body: JSON.stringify(params)
579
+ });
580
+ }
581
+ /**
582
+ * Unstake tokens
583
+ */
584
+ async unstake(params) {
585
+ return this.request("/api/v1/staking/unstake", {
586
+ method: "POST",
587
+ body: JSON.stringify(params)
588
+ });
589
+ }
590
+ /**
591
+ * Claim staking rewards
592
+ */
593
+ async claimStakingRewards(positionId) {
594
+ return this.request("/api/v1/staking/claim", {
595
+ method: "POST",
596
+ body: JSON.stringify({ positionId })
597
+ });
598
+ }
599
+ // ===============================
600
+ // USER PROFILE ENDPOINTS
601
+ // ===============================
602
+ /**
603
+ * Get user profile
604
+ */
605
+ async getUserProfile() {
606
+ return this.request("/api/v1/user/profile", { method: "GET" });
607
+ }
608
+ /**
609
+ * Update user profile
610
+ */
611
+ async updateUserProfile(updates) {
612
+ return this.request("/api/v1/user/profile", {
613
+ method: "PATCH",
614
+ body: JSON.stringify(updates)
615
+ });
616
+ }
617
+ /**
618
+ * Get user settings
619
+ */
620
+ async getUserSettings() {
621
+ return this.request("/api/v1/user/settings", { method: "GET" });
622
+ }
623
+ /**
624
+ * Update user settings
625
+ */
626
+ async updateUserSettings(updates) {
627
+ return this.request("/api/v1/user/settings", {
628
+ method: "PATCH",
629
+ body: JSON.stringify(updates)
630
+ });
631
+ }
632
+ // ===============================
633
+ // NOTIFICATION ENDPOINTS
634
+ // ===============================
635
+ /**
636
+ * Get notifications
637
+ */
638
+ async getNotifications(options) {
639
+ const params = new URLSearchParams();
640
+ if (options?.unreadOnly) params.set("unreadOnly", "true");
641
+ if (options?.limit) params.set("limit", options.limit.toString());
642
+ if (options?.offset) params.set("offset", options.offset.toString());
643
+ return this.request(`/api/v1/notifications?${params}`, { method: "GET" });
644
+ }
645
+ /**
646
+ * Mark notification as read
647
+ */
648
+ async markNotificationRead(notificationId) {
649
+ return this.request(`/api/v1/notifications/${notificationId}/read`, { method: "POST" });
650
+ }
651
+ /**
652
+ * Mark all notifications as read
653
+ */
654
+ async markAllNotificationsRead() {
655
+ return this.request("/api/v1/notifications/read-all", { method: "POST" });
656
+ }
657
+ // ===============================
658
+ // REFERRAL ENDPOINTS
659
+ // ===============================
660
+ /**
661
+ * Get referral info
662
+ */
663
+ async getReferralInfo() {
664
+ return this.request("/api/v1/referral", { method: "GET" });
665
+ }
666
+ /**
667
+ * Get referred users
668
+ */
669
+ async getReferrals() {
670
+ return this.request("/api/v1/referral/list", { method: "GET" });
671
+ }
672
+ /**
673
+ * Apply referral code
674
+ */
675
+ async applyReferralCode(code) {
676
+ return this.request("/api/v1/referral/apply", {
677
+ method: "POST",
678
+ body: JSON.stringify({ code })
679
+ });
680
+ }
681
+ /**
682
+ * Claim referral rewards
683
+ */
684
+ async claimReferralRewards() {
685
+ return this.request("/api/v1/referral/claim", { method: "POST" });
686
+ }
687
+ // ===============================
688
+ // KYC ENDPOINTS
689
+ // ===============================
690
+ /**
691
+ * Get KYC status
692
+ */
693
+ async getKycStatus() {
694
+ return this.request("/api/v1/kyc/status", { method: "GET" });
695
+ }
696
+ /**
697
+ * Start KYC verification
698
+ */
699
+ async startKycVerification(level) {
700
+ return this.request("/api/v1/kyc/start", {
701
+ method: "POST",
702
+ body: JSON.stringify({ level })
703
+ });
704
+ }
705
+ /**
706
+ * Submit KYC documents
707
+ */
708
+ async submitKycDocuments(params) {
709
+ return this.request("/api/v1/kyc/submit", {
710
+ method: "POST",
711
+ body: JSON.stringify(params)
712
+ });
713
+ }
714
+ // ===============================
715
+ // BRIDGE ENDPOINTS
716
+ // ===============================
717
+ /**
718
+ * Get bridge quote
719
+ */
720
+ async getBridgeQuote(params) {
721
+ return this.request("/api/v1/bridge/quote", {
722
+ method: "POST",
723
+ body: JSON.stringify(params)
724
+ });
725
+ }
726
+ /**
727
+ * Execute bridge transaction
728
+ */
729
+ async executeBridge(params) {
730
+ return this.request("/api/v1/bridge/execute", {
731
+ method: "POST",
732
+ body: JSON.stringify(params)
733
+ });
734
+ }
735
+ /**
736
+ * Get bridge transaction status
737
+ */
738
+ async getBridgeStatus(bridgeId) {
739
+ return this.request(`/api/v1/bridge/${bridgeId}`, { method: "GET" });
740
+ }
741
+ /**
742
+ * Get supported bridge routes
743
+ */
744
+ async getSupportedBridgeRoutes() {
745
+ return this.request("/api/v1/bridge/routes", { method: "GET" });
746
+ }
747
+ // ===============================
748
+ // GAS ENDPOINTS
749
+ // ===============================
750
+ /**
751
+ * Get gas estimate for transaction
752
+ */
753
+ async getGasEstimate(params) {
754
+ return this.request("/api/v1/gas/estimate", {
755
+ method: "POST",
756
+ body: JSON.stringify(params)
757
+ });
758
+ }
759
+ /**
760
+ * Get current gas prices for chain
761
+ */
762
+ async getGasPrice(chainId) {
763
+ return this.request(`/api/v1/gas/price?chainId=${chainId}`, { method: "GET" });
764
+ }
765
+ // ===============================
766
+ // WALLET IMPORT/EXPORT ENDPOINTS
767
+ // ===============================
768
+ /**
769
+ * Import wallet from private key or mnemonic
770
+ */
771
+ async importWallet(request) {
772
+ return this.request("/api/v1/wallet/import", {
773
+ method: "POST",
774
+ body: JSON.stringify(request)
775
+ }, true);
776
+ }
777
+ /**
778
+ * Export wallet (get encrypted private key)
779
+ * Requires additional authentication
780
+ */
781
+ async exportWallet(walletId, pin) {
782
+ return this.request("/api/v1/wallet/export", {
783
+ method: "POST",
784
+ body: JSON.stringify({ walletId, pin })
785
+ }, true);
786
+ }
787
+ /**
788
+ * Generate new mnemonic phrase
789
+ */
790
+ async generateMnemonic() {
791
+ return this.request("/api/v1/wallet/generate-mnemonic", { method: "POST" }, true);
792
+ }
793
+ /**
794
+ * Validate mnemonic phrase
795
+ */
796
+ async validateMnemonic(mnemonic) {
797
+ return this.request("/api/v1/wallet/validate-mnemonic", {
798
+ method: "POST",
799
+ body: JSON.stringify({ mnemonic })
800
+ });
801
+ }
802
+ // ===============================
803
+ // PORTFOLIO ANALYTICS ENDPOINTS
804
+ // ===============================
805
+ /**
806
+ * Get portfolio analytics with historical data
807
+ */
808
+ async getPortfolioAnalytics(walletAddress, period = "30d") {
809
+ const params = new URLSearchParams({ address: walletAddress, period });
810
+ return this.request(`/api/v1/analytics/portfolio?${params}`, { method: "GET" });
811
+ }
812
+ /**
813
+ * Get transaction analytics
814
+ */
815
+ async getTransactionAnalytics(walletAddress, period = "30d") {
816
+ const params = new URLSearchParams({ address: walletAddress, period });
817
+ return this.request(`/api/v1/analytics/transactions?${params}`, { method: "GET" });
818
+ }
819
+ // ===============================
820
+ // ADVANCED TRADING ENDPOINTS
821
+ // ===============================
822
+ /**
823
+ * Create limit order
824
+ */
825
+ async createLimitOrder(params) {
826
+ return this.request("/api/v1/trading/limit-orders", {
827
+ method: "POST",
828
+ body: JSON.stringify(params)
829
+ });
830
+ }
831
+ /**
832
+ * Get user's limit orders
833
+ */
834
+ async getLimitOrders(status) {
835
+ const params = status ? `?status=${status}` : "";
836
+ return this.request(`/api/v1/trading/limit-orders${params}`, { method: "GET" });
837
+ }
838
+ /**
839
+ * Cancel limit order
840
+ */
841
+ async cancelLimitOrder(orderId) {
842
+ return this.request(`/api/v1/trading/limit-orders/${orderId}`, { method: "DELETE" });
843
+ }
844
+ /**
845
+ * Set price alert
846
+ */
847
+ async setPriceAlert(params) {
848
+ return this.request("/api/v1/trading/alerts", {
849
+ method: "POST",
850
+ body: JSON.stringify(params)
851
+ });
852
+ }
853
+ /**
854
+ * Get price alerts
855
+ */
856
+ async getPriceAlerts() {
857
+ return this.request("/api/v1/trading/alerts", { method: "GET" });
858
+ }
859
+ /**
860
+ * Delete price alert
861
+ */
862
+ async deletePriceAlert(alertId) {
863
+ return this.request(`/api/v1/trading/alerts/${alertId}`, { method: "DELETE" });
864
+ }
865
+ // ===============================
866
+ // SESSION MANAGEMENT
867
+ // ===============================
868
+ /**
869
+ * Get active sessions
870
+ */
871
+ async getActiveSessions() {
872
+ return this.request("/api/v1/auth/sessions", { method: "GET" });
873
+ }
874
+ /**
875
+ * Revoke session
876
+ */
877
+ async revokeSession(sessionId) {
878
+ return this.request(`/api/v1/auth/sessions/${sessionId}`, { method: "DELETE" });
879
+ }
880
+ /**
881
+ * Revoke all other sessions
882
+ */
883
+ async revokeAllOtherSessions() {
884
+ return this.request("/api/v1/auth/sessions/revoke-all", { method: "POST" });
885
+ }
886
+ // ========== Webhooks ==========
887
+ /**
888
+ * List webhooks for the project
889
+ */
890
+ async listWebhooks(options) {
891
+ const params = new URLSearchParams();
892
+ if (options?.isActive !== void 0) params.set("isActive", String(options.isActive));
893
+ const query = params.toString();
894
+ return this.request(`/api/v1/webhooks${query ? `?${query}` : ""}`, { method: "GET" });
895
+ }
896
+ /**
897
+ * Get webhook by ID
898
+ */
899
+ async getWebhook(webhookId) {
900
+ return this.request(`/api/v1/webhooks/${webhookId}`, { method: "GET" });
901
+ }
902
+ /**
903
+ * Create a webhook
904
+ */
905
+ async createWebhook(input) {
906
+ return this.request("/api/v1/webhooks", {
907
+ method: "POST",
908
+ body: JSON.stringify(input)
909
+ });
910
+ }
911
+ /**
912
+ * Update a webhook
913
+ */
914
+ async updateWebhook(webhookId, input) {
915
+ return this.request(`/api/v1/webhooks/${webhookId}`, {
916
+ method: "PATCH",
917
+ body: JSON.stringify(input)
918
+ });
919
+ }
920
+ /**
921
+ * Delete a webhook
922
+ */
923
+ async deleteWebhook(webhookId) {
924
+ return this.request(`/api/v1/webhooks/${webhookId}`, { method: "DELETE" });
925
+ }
926
+ /**
927
+ * Get webhook deliveries
928
+ */
929
+ async getWebhookDeliveries(webhookId, options) {
930
+ const params = new URLSearchParams();
931
+ if (options?.status) params.set("status", options.status);
932
+ if (options?.limit) params.set("limit", String(options.limit));
933
+ if (options?.offset) params.set("offset", String(options.offset));
934
+ const query = params.toString();
935
+ return this.request(`/api/v1/webhooks/${webhookId}/deliveries${query ? `?${query}` : ""}`, { method: "GET" });
936
+ }
937
+ /**
938
+ * Test a webhook
939
+ */
940
+ async testWebhook(webhookId) {
941
+ return this.request(`/api/v1/webhooks/${webhookId}/test`, { method: "POST" });
942
+ }
943
+ // ========== Admin (requires admin role) ==========
944
+ /**
945
+ * List all users (admin only)
946
+ */
947
+ async adminListUsers(options) {
948
+ const params = new URLSearchParams();
949
+ if (options?.page) params.set("page", String(options.page));
950
+ if (options?.limit) params.set("limit", String(options.limit));
951
+ if (options?.search) params.set("search", options.search);
952
+ if (options?.sortBy) params.set("sortBy", options.sortBy);
953
+ if (options?.sortOrder) params.set("sortOrder", options.sortOrder);
954
+ if (options?.role) params.set("role", options.role);
955
+ if (options?.kycStatus) params.set("kycStatus", options.kycStatus);
956
+ if (options?.isActive !== void 0) params.set("isActive", String(options.isActive));
957
+ const query = params.toString();
958
+ return this.request(`/api/v1/admin/users${query ? `?${query}` : ""}`, { method: "GET" });
959
+ }
960
+ /**
961
+ * Get user by ID (admin only)
962
+ */
963
+ async adminGetUser(userId) {
964
+ return this.request(`/api/v1/admin/users/${userId}`, { method: "GET" });
965
+ }
966
+ /**
967
+ * Update user (admin only)
968
+ */
969
+ async adminUpdateUser(userId, data) {
970
+ return this.request(`/api/v1/admin/users/${userId}`, {
971
+ method: "PATCH",
972
+ body: JSON.stringify(data)
973
+ });
974
+ }
975
+ /**
976
+ * List all projects (admin only)
977
+ */
978
+ async adminListProjects(options) {
979
+ const params = new URLSearchParams();
980
+ if (options?.page) params.set("page", String(options.page));
981
+ if (options?.limit) params.set("limit", String(options.limit));
982
+ if (options?.search) params.set("search", options.search);
983
+ if (options?.sortBy) params.set("sortBy", options.sortBy);
984
+ if (options?.sortOrder) params.set("sortOrder", options.sortOrder);
985
+ if (options?.isActive !== void 0) params.set("isActive", String(options.isActive));
986
+ const query = params.toString();
987
+ return this.request(`/api/v1/admin/projects${query ? `?${query}` : ""}`, { method: "GET" });
988
+ }
989
+ /**
990
+ * Get project by ID (admin only)
991
+ */
992
+ async adminGetProject(projectId) {
993
+ return this.request(`/api/v1/admin/projects/${projectId}`, { method: "GET" });
994
+ }
995
+ /**
996
+ * Update project (admin only)
997
+ */
998
+ async adminUpdateProject(projectId, data) {
999
+ return this.request(`/api/v1/admin/projects/${projectId}`, {
1000
+ method: "PATCH",
1001
+ body: JSON.stringify(data)
1002
+ });
1003
+ }
1004
+ /**
1005
+ * Regenerate project API key (admin only)
1006
+ */
1007
+ async adminRegenerateApiKey(projectId) {
1008
+ return this.request(`/api/v1/admin/projects/${projectId}/regenerate-key`, { method: "POST" });
1009
+ }
1010
+ /**
1011
+ * Get system statistics (admin only)
1012
+ */
1013
+ async adminGetStats(days) {
1014
+ const query = days ? `?days=${days}` : "";
1015
+ return this.request(`/api/v1/admin/stats${query}`, { method: "GET" });
1016
+ }
1017
+ /**
1018
+ * Get system logs (admin only)
1019
+ */
1020
+ async adminGetLogs(options) {
1021
+ const params = new URLSearchParams();
1022
+ if (options?.level) params.set("level", options.level);
1023
+ if (options?.service) params.set("service", options.service);
1024
+ if (options?.limit) params.set("limit", String(options.limit));
1025
+ if (options?.offset) params.set("offset", String(options.offset));
1026
+ if (options?.startDate) params.set("startDate", options.startDate);
1027
+ if (options?.endDate) params.set("endDate", options.endDate);
1028
+ const query = params.toString();
1029
+ return this.request(`/api/v1/admin/logs${query ? `?${query}` : ""}`, { method: "GET" });
1030
+ }
1031
+ /**
1032
+ * Get rate limit status (admin only)
1033
+ */
1034
+ async adminGetRateLimits(options) {
1035
+ const params = new URLSearchParams();
1036
+ if (options?.identifier) params.set("identifier", options.identifier);
1037
+ if (options?.limit) params.set("limit", String(options.limit));
1038
+ const query = params.toString();
1039
+ return this.request(`/api/v1/admin/rate-limits${query ? `?${query}` : ""}`, { method: "GET" });
1040
+ }
1041
+ /**
1042
+ * Clear rate limits for an identifier (admin only)
1043
+ */
1044
+ async adminClearRateLimits(identifier) {
1045
+ return this.request(`/api/v1/admin/rate-limits/${identifier}`, { method: "DELETE" });
1046
+ }
1047
+ // ========== AI Quant Trading ==========
1048
+ /**
1049
+ * Get all AI trading strategies
1050
+ */
1051
+ async getAIStrategies(filters) {
1052
+ const params = new URLSearchParams();
1053
+ if (filters?.category) params.set("category", filters.category);
1054
+ if (filters?.riskLevel) params.set("risk_level", String(filters.riskLevel));
1055
+ if (filters?.minTvl) params.set("min_tvl", String(filters.minTvl));
1056
+ if (filters?.isActive !== void 0) params.set("is_active", String(filters.isActive));
1057
+ const query = params.toString();
1058
+ return this.request(`/api/v1/ai-quant/strategies${query ? `?${query}` : ""}`, { method: "GET" });
1059
+ }
1060
+ /**
1061
+ * Get AI strategy details
1062
+ */
1063
+ async getAIStrategy(strategyId, include) {
1064
+ const params = new URLSearchParams();
1065
+ if (include?.length) params.set("include", include.join(","));
1066
+ const query = params.toString();
1067
+ return this.request(`/api/v1/ai-quant/strategies/${strategyId}${query ? `?${query}` : ""}`, { method: "GET" });
1068
+ }
1069
+ /**
1070
+ * Get strategy performance history
1071
+ */
1072
+ async getAIStrategyPerformance(strategyId, days = 30) {
1073
+ return this.request(`/api/v1/ai-quant/strategies/${strategyId}?include=performance&days=${days}`, { method: "GET" });
1074
+ }
1075
+ /**
1076
+ * Get real-time market data for strategy pairs
1077
+ */
1078
+ async getAIStrategyMarketData(strategyId) {
1079
+ return this.request(`/api/v1/ai-quant/strategies/${strategyId}?include=market`, { method: "GET" });
1080
+ }
1081
+ /**
1082
+ * Create AI trading order
1083
+ */
1084
+ async createAIOrder(request) {
1085
+ return this.request("/api/v1/ai-quant/orders", {
1086
+ method: "POST",
1087
+ body: JSON.stringify(request)
1088
+ });
1089
+ }
1090
+ /**
1091
+ * Get user's AI orders
1092
+ */
1093
+ async getAIOrders(filters) {
1094
+ const params = new URLSearchParams();
1095
+ if (filters?.strategyId) params.set("strategy_id", filters.strategyId);
1096
+ if (filters?.status) params.set("status", filters.status);
1097
+ const query = params.toString();
1098
+ return this.request(`/api/v1/ai-quant/orders${query ? `?${query}` : ""}`, { method: "GET" });
1099
+ }
1100
+ /**
1101
+ * Get AI order details
1102
+ */
1103
+ async getAIOrder(orderId) {
1104
+ return this.request(`/api/v1/ai-quant/orders/${orderId}`, { method: "GET" });
1105
+ }
1106
+ /**
1107
+ * Pause AI order
1108
+ */
1109
+ async pauseAIOrder(orderId) {
1110
+ return this.request(`/api/v1/ai-quant/orders/${orderId}/pause`, { method: "POST" });
1111
+ }
1112
+ /**
1113
+ * Resume AI order
1114
+ */
1115
+ async resumeAIOrder(orderId) {
1116
+ return this.request(`/api/v1/ai-quant/orders/${orderId}/resume`, { method: "POST" });
1117
+ }
1118
+ /**
1119
+ * Request redemption for AI order
1120
+ */
1121
+ async redeemAIOrder(orderId) {
1122
+ return this.request(`/api/v1/ai-quant/orders/${orderId}/redeem`, { method: "POST" });
1123
+ }
1124
+ /**
1125
+ * Get AI portfolio summary
1126
+ */
1127
+ async getAIPortfolio(include) {
1128
+ const params = new URLSearchParams();
1129
+ if (include?.length) params.set("include", include.join(","));
1130
+ const query = params.toString();
1131
+ return this.request(`/api/v1/ai-quant/portfolio${query ? `?${query}` : ""}`, { method: "GET" });
1132
+ }
1133
+ /**
1134
+ * Get user's trade allocations
1135
+ */
1136
+ async getAITradeAllocations(limit = 50) {
1137
+ return this.request(`/api/v1/ai-quant/portfolio?include=allocations&limit=${limit}`, { method: "GET" });
1138
+ }
1139
+ /**
1140
+ * Get trade history for a strategy
1141
+ */
1142
+ async getAITradeHistory(strategyId, limit = 50) {
1143
+ return this.request(`/api/v1/ai-quant/strategies/${strategyId}?include=trades&limit=${limit}`, { method: "GET" });
1144
+ }
1145
+ /**
1146
+ * Execute AI signals for a strategy (admin only)
1147
+ */
1148
+ async executeAISignals(strategyId) {
1149
+ return this.request("/api/v1/ai-quant/execute", {
1150
+ method: "POST",
1151
+ body: JSON.stringify({ strategyId })
1152
+ });
1153
+ }
1154
+ // ========== Free Price APIs (No API Key Required) ==========
1155
+ /**
1156
+ * Get cryptocurrency prices (FREE - uses CoinGecko/Binance/CoinCap)
1157
+ */
1158
+ async getCryptoPrices(symbols) {
1159
+ return this.request(`/api/v1/prices?symbols=${symbols.join(",")}`, { method: "GET" });
1160
+ }
1161
+ /**
1162
+ * Get single cryptocurrency price (FREE)
1163
+ */
1164
+ async getCryptoPrice(symbol) {
1165
+ return this.request(`/api/v1/prices/${symbol}`, { method: "GET" });
1166
+ }
1167
+ /**
1168
+ * Get OHLCV candles for charting (FREE - from Binance)
1169
+ */
1170
+ async getCryptoCandles(symbol, interval = "1h", limit = 100) {
1171
+ return this.request(`/api/v1/prices/${symbol}?candles=true&interval=${interval}&limit=${limit}`, { method: "GET" });
1172
+ }
1173
+ /**
1174
+ * Get top cryptocurrencies by market cap (FREE)
1175
+ */
1176
+ async getTopCryptos(limit = 20) {
1177
+ return this.request(`/api/v1/prices?type=top&limit=${limit}`, { method: "GET" });
1178
+ }
1179
+ /**
1180
+ * Get crypto market overview (FREE)
1181
+ */
1182
+ async getCryptoMarketOverview() {
1183
+ return this.request("/api/v1/prices?type=overview", { method: "GET" });
1184
+ }
1185
+ };
1186
+ function createOneEngineClient(options) {
1187
+ return new OneEngineClient(options);
1188
+ }
1189
+
1190
+ // src/hooks/useWalletBalance.ts
1191
+ function useWalletBalance(walletAddress, options = {}) {
1192
+ const {
1193
+ chains,
1194
+ autoRefresh = false,
1195
+ refreshInterval = 6e4,
1196
+ // 1 minute
1197
+ engineUrl,
1198
+ clientId
1199
+ } = options;
1200
+ const [balance, setBalance] = useState(null);
1201
+ const [isLoading, setIsLoading] = useState(false);
1202
+ const [error, setError] = useState(null);
1203
+ const engineRef = useRef(createOneEngineClient({
1204
+ baseUrl: engineUrl,
1205
+ clientId
1206
+ }));
1207
+ const fetchBalance = useCallback(async () => {
1208
+ if (!walletAddress) {
1209
+ setBalance(null);
1210
+ return;
1211
+ }
1212
+ setIsLoading(true);
1213
+ setError(null);
1214
+ try {
1215
+ const result = await engineRef.current.getWalletBalance(walletAddress, chains);
1216
+ if (result.success && result.data) {
1217
+ setBalance(result.data);
1218
+ } else {
1219
+ setError(result.error?.message || "Failed to fetch balance");
1220
+ }
1221
+ } catch (err) {
1222
+ setError(err instanceof Error ? err.message : "Failed to fetch balance");
1223
+ } finally {
1224
+ setIsLoading(false);
1225
+ }
1226
+ }, [walletAddress, chains]);
1227
+ useEffect(() => {
1228
+ fetchBalance();
1229
+ }, [fetchBalance]);
1230
+ useEffect(() => {
1231
+ if (!autoRefresh || !walletAddress) return;
1232
+ const interval = setInterval(fetchBalance, refreshInterval);
1233
+ return () => clearInterval(interval);
1234
+ }, [autoRefresh, refreshInterval, fetchBalance, walletAddress]);
1235
+ return {
1236
+ balance,
1237
+ tokens: balance?.tokens || [],
1238
+ totalUsd: balance?.totalUsd || 0,
1239
+ change24h: balance?.change24h || 0,
1240
+ changePercent24h: balance?.changePercent24h || 0,
1241
+ isLoading,
1242
+ error,
1243
+ refetch: fetchBalance
1244
+ };
1245
+ }
1246
+ function useTokenPrice(symbol, options = {}) {
1247
+ const { autoRefresh = false, refreshInterval = 3e4, engineUrl, clientId } = options;
1248
+ const [price, setPrice] = useState(null);
1249
+ const [isLoading, setIsLoading] = useState(false);
1250
+ const [error, setError] = useState(null);
1251
+ const engineRef = useRef(createOneEngineClient({
1252
+ baseUrl: engineUrl,
1253
+ clientId
1254
+ }));
1255
+ const fetchPrice = useCallback(async () => {
1256
+ if (!symbol) return;
1257
+ setIsLoading(true);
1258
+ setError(null);
1259
+ try {
1260
+ const result = await engineRef.current.getTokenPrices([symbol]);
1261
+ if (result.success && result.data && result.data[symbol]) {
1262
+ const priceData = result.data[symbol];
1263
+ setPrice({
1264
+ symbol,
1265
+ price: priceData.price,
1266
+ change24h: priceData.change24h,
1267
+ changePercent24h: priceData.change24h,
1268
+ // Same as change24h for percentage
1269
+ marketCap: priceData.marketCap,
1270
+ volume24h: 0,
1271
+ // Not provided by engine
1272
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1273
+ });
1274
+ } else {
1275
+ setError(result.error?.message || "Failed to fetch price");
1276
+ }
1277
+ } catch (err) {
1278
+ setError(err instanceof Error ? err.message : "Failed to fetch price");
1279
+ } finally {
1280
+ setIsLoading(false);
1281
+ }
1282
+ }, [symbol]);
1283
+ useEffect(() => {
1284
+ fetchPrice();
1285
+ }, [fetchPrice]);
1286
+ useEffect(() => {
1287
+ if (!autoRefresh) return;
1288
+ const interval = setInterval(fetchPrice, refreshInterval);
1289
+ return () => clearInterval(interval);
1290
+ }, [autoRefresh, refreshInterval, fetchPrice]);
1291
+ return {
1292
+ price,
1293
+ isLoading,
1294
+ error,
1295
+ refetch: fetchPrice
1296
+ };
1297
+ }
1298
+ function useTokenPrices(symbols, options = {}) {
1299
+ const { autoRefresh = false, refreshInterval = 3e4, engineUrl, clientId } = options;
1300
+ const [prices, setPrices] = useState({});
1301
+ const [isLoading, setIsLoading] = useState(false);
1302
+ const [error, setError] = useState(null);
1303
+ const engineRef = useRef(createOneEngineClient({
1304
+ baseUrl: engineUrl,
1305
+ clientId
1306
+ }));
1307
+ const fetchPrices = useCallback(async () => {
1308
+ if (symbols.length === 0) return;
1309
+ setIsLoading(true);
1310
+ setError(null);
1311
+ try {
1312
+ const result = await engineRef.current.getTokenPrices(symbols);
1313
+ if (result.success && result.data) {
1314
+ const priceMap = {};
1315
+ for (const sym of symbols) {
1316
+ if (result.data[sym]) {
1317
+ priceMap[sym] = {
1318
+ symbol: sym,
1319
+ price: result.data[sym].price,
1320
+ change24h: result.data[sym].change24h,
1321
+ changePercent24h: result.data[sym].change24h,
1322
+ marketCap: result.data[sym].marketCap,
1323
+ volume24h: 0,
1324
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1325
+ };
1326
+ }
1327
+ }
1328
+ setPrices(priceMap);
1329
+ } else {
1330
+ setError(result.error?.message || "Failed to fetch prices");
1331
+ }
1332
+ } catch (err) {
1333
+ setError(err instanceof Error ? err.message : "Failed to fetch prices");
1334
+ } finally {
1335
+ setIsLoading(false);
1336
+ }
1337
+ }, [symbols]);
1338
+ useEffect(() => {
1339
+ fetchPrices();
1340
+ }, [fetchPrices]);
1341
+ useEffect(() => {
1342
+ if (!autoRefresh) return;
1343
+ const interval = setInterval(fetchPrices, refreshInterval);
1344
+ return () => clearInterval(interval);
1345
+ }, [autoRefresh, refreshInterval, fetchPrices]);
1346
+ return {
1347
+ prices,
1348
+ isLoading,
1349
+ error,
1350
+ refetch: fetchPrices
1351
+ };
1352
+ }
1353
+
1354
+ export { useTokenPrice, useTokenPrices, useWalletBalance };
1355
+ //# sourceMappingURL=index.mjs.map
1356
+ //# sourceMappingURL=index.mjs.map