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