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