@one_deploy/sdk 1.0.2 → 1.0.4

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 (70) hide show
  1. package/package.json +1 -1
  2. package/src/components/OneSwapWidget.tsx +1 -1
  3. package/src/components/ai/OneChainSelector.tsx +183 -0
  4. package/src/components/ai/OneCycleSelector.tsx +187 -0
  5. package/src/components/ai/OnePairSelector.tsx +181 -0
  6. package/src/components/ai/OneTierSelector.tsx +187 -0
  7. package/src/components/ai/index.ts +17 -0
  8. package/src/components/index.ts +3 -0
  9. package/src/config/index.ts +1 -1
  10. package/src/hooks/index.ts +20 -0
  11. package/src/hooks/useAITrading.ts +444 -0
  12. package/src/index.ts +20 -0
  13. package/src/react-native.ts +23 -0
  14. package/src/services/engine.ts +184 -0
  15. package/src/services/index.ts +16 -0
  16. package/src/services/usage.ts +249 -0
  17. package/.turbo/turbo-build.log +0 -0
  18. package/.turbo/turbo-type-check.log +0 -0
  19. package/dist/config/index.d.mts +0 -74
  20. package/dist/config/index.d.ts +0 -74
  21. package/dist/config/index.js +0 -244
  22. package/dist/config/index.js.map +0 -1
  23. package/dist/config/index.mjs +0 -226
  24. package/dist/config/index.mjs.map +0 -1
  25. package/dist/engine-5ndtBaCr.d.ts +0 -1039
  26. package/dist/engine-CrlhH0nw.d.mts +0 -1039
  27. package/dist/hooks/index.d.mts +0 -56
  28. package/dist/hooks/index.d.ts +0 -56
  29. package/dist/hooks/index.js +0 -1360
  30. package/dist/hooks/index.js.map +0 -1
  31. package/dist/hooks/index.mjs +0 -1356
  32. package/dist/hooks/index.mjs.map +0 -1
  33. package/dist/index.d.mts +0 -356
  34. package/dist/index.d.ts +0 -356
  35. package/dist/index.js +0 -5069
  36. package/dist/index.js.map +0 -1
  37. package/dist/index.mjs +0 -4950
  38. package/dist/index.mjs.map +0 -1
  39. package/dist/price-CgqXPnT3.d.ts +0 -13
  40. package/dist/price-ClbLHHjv.d.mts +0 -13
  41. package/dist/providers/index.d.mts +0 -121
  42. package/dist/providers/index.d.ts +0 -121
  43. package/dist/providers/index.js +0 -1643
  44. package/dist/providers/index.js.map +0 -1
  45. package/dist/providers/index.mjs +0 -1601
  46. package/dist/providers/index.mjs.map +0 -1
  47. package/dist/react-native.d.mts +0 -120
  48. package/dist/react-native.d.ts +0 -120
  49. package/dist/react-native.js +0 -1794
  50. package/dist/react-native.js.map +0 -1
  51. package/dist/react-native.mjs +0 -1757
  52. package/dist/react-native.mjs.map +0 -1
  53. package/dist/services/index.d.mts +0 -85
  54. package/dist/services/index.d.ts +0 -85
  55. package/dist/services/index.js +0 -1466
  56. package/dist/services/index.js.map +0 -1
  57. package/dist/services/index.mjs +0 -1458
  58. package/dist/services/index.mjs.map +0 -1
  59. package/dist/types/index.d.mts +0 -759
  60. package/dist/types/index.d.ts +0 -759
  61. package/dist/types/index.js +0 -4
  62. package/dist/types/index.js.map +0 -1
  63. package/dist/types/index.mjs +0 -3
  64. package/dist/types/index.mjs.map +0 -1
  65. package/dist/utils/index.d.mts +0 -36
  66. package/dist/utils/index.d.ts +0 -36
  67. package/dist/utils/index.js +0 -164
  68. package/dist/utils/index.js.map +0 -1
  69. package/dist/utils/index.mjs +0 -142
  70. package/dist/utils/index.mjs.map +0 -1
@@ -1,1794 +0,0 @@
1
- 'use strict';
2
-
3
- // src/config/index.ts
4
- var DEFAULT_ENGINE_URL = "https://api.one23.io/api";
5
- var DEFAULT_CLIENT_ID = "one_pk_e8f647bfa643fdcfaa3a23f760488e49be09f929296eed4a6c399d437d907f60";
6
- var config = null;
7
- function initOneSDK(options) {
8
- const engineUrl = options.oneEngineUrl || DEFAULT_ENGINE_URL;
9
- const clientId = options.oneClientId || DEFAULT_CLIENT_ID;
10
- config = {
11
- ...options,
12
- oneEngineUrl: engineUrl,
13
- oneClientId: clientId
14
- };
15
- }
16
- function getConfig() {
17
- if (!config) {
18
- throw new Error("ONE SDK not initialized. Call initOneSDK() first.");
19
- }
20
- return config;
21
- }
22
- var TOKEN_NAMES = {
23
- ETH: "Ethereum",
24
- BTC: "Bitcoin",
25
- BNB: "BNB",
26
- MATIC: "Polygon",
27
- POL: "Polygon",
28
- AVAX: "Avalanche",
29
- USDT: "Tether",
30
- USDC: "USD Coin",
31
- DAI: "Dai",
32
- WBTC: "Wrapped Bitcoin",
33
- WETH: "Wrapped Ether",
34
- ARB: "Arbitrum",
35
- OP: "Optimism",
36
- LINK: "Chainlink",
37
- UNI: "Uniswap",
38
- AAVE: "Aave",
39
- CRV: "Curve",
40
- MKR: "Maker",
41
- SNX: "Synthetix",
42
- COMP: "Compound",
43
- SUSHI: "SushiSwap",
44
- YFI: "Yearn Finance",
45
- SOL: "Solana",
46
- DOT: "Polkadot",
47
- ATOM: "Cosmos",
48
- NEAR: "Near Protocol"
49
- };
50
- var COINGECKO_IDS = {
51
- ETH: "ethereum",
52
- BTC: "bitcoin",
53
- BNB: "binancecoin",
54
- MATIC: "matic-network",
55
- POL: "matic-network",
56
- AVAX: "avalanche-2",
57
- USDT: "tether",
58
- USDC: "usd-coin",
59
- DAI: "dai",
60
- WBTC: "wrapped-bitcoin",
61
- WETH: "weth",
62
- ARB: "arbitrum",
63
- OP: "optimism",
64
- LINK: "chainlink",
65
- UNI: "uniswap",
66
- AAVE: "aave",
67
- SOL: "solana"
68
- };
69
- var CHAIN_CONFIGS = {
70
- ethereum: {
71
- id: 1,
72
- name: "Ethereum",
73
- shortName: "ETH",
74
- icon: "\u229F",
75
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
76
- rpcUrls: ["https://ethereum.rpc.thirdweb.com"],
77
- blockExplorerUrls: ["https://etherscan.io"],
78
- testnet: false
79
- },
80
- polygon: {
81
- id: 137,
82
- name: "Polygon",
83
- shortName: "MATIC",
84
- icon: "\u{1F7E3}",
85
- nativeCurrency: { name: "POL", symbol: "POL", decimals: 18 },
86
- rpcUrls: ["https://polygon.rpc.thirdweb.com"],
87
- blockExplorerUrls: ["https://polygonscan.com"],
88
- testnet: false
89
- },
90
- base: {
91
- id: 8453,
92
- name: "Base",
93
- shortName: "BASE",
94
- icon: "\u{1F537}",
95
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
96
- rpcUrls: ["https://base.rpc.thirdweb.com"],
97
- blockExplorerUrls: ["https://basescan.org"],
98
- testnet: false
99
- },
100
- arbitrum: {
101
- id: 42161,
102
- name: "Arbitrum One",
103
- shortName: "ARB",
104
- icon: "\u{1F535}",
105
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
106
- rpcUrls: ["https://arbitrum.rpc.thirdweb.com"],
107
- blockExplorerUrls: ["https://arbiscan.io"],
108
- testnet: false
109
- },
110
- optimism: {
111
- id: 10,
112
- name: "Optimism",
113
- shortName: "OP",
114
- icon: "\u{1F534}",
115
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
116
- rpcUrls: ["https://optimism.rpc.thirdweb.com"],
117
- blockExplorerUrls: ["https://optimistic.etherscan.io"],
118
- testnet: false
119
- }
120
- };
121
-
122
- // src/services/engine.ts
123
- var OneEngineClient = class {
124
- constructor(options) {
125
- const config2 = getConfig();
126
- this.baseUrl = options?.baseUrl || config2.oneEngineUrl;
127
- this.clientId = options?.clientId || config2.oneClientId || "";
128
- this.secretKey = options?.secretKey || config2.oneSecretKey;
129
- }
130
- /**
131
- * Set access token for authenticated requests
132
- */
133
- setAccessToken(token) {
134
- this.accessToken = token;
135
- }
136
- /**
137
- * Clear access token
138
- */
139
- clearAccessToken() {
140
- this.accessToken = void 0;
141
- }
142
- getHeaders(includeSecret = false) {
143
- const headers = {
144
- "Content-Type": "application/json",
145
- "x-client-id": this.clientId
146
- };
147
- if (this.accessToken) {
148
- headers["Authorization"] = `Bearer ${this.accessToken}`;
149
- }
150
- if (includeSecret && this.secretKey) {
151
- headers["x-secret-key"] = this.secretKey;
152
- }
153
- return headers;
154
- }
155
- async request(endpoint, options = {}, includeSecret = false) {
156
- try {
157
- const response = await fetch(`${this.baseUrl}${endpoint}`, {
158
- ...options,
159
- headers: {
160
- ...this.getHeaders(includeSecret),
161
- ...options.headers
162
- }
163
- });
164
- const data = await response.json();
165
- if (!response.ok) {
166
- return {
167
- success: false,
168
- error: {
169
- code: data.error?.code || `HTTP_${response.status}`,
170
- message: data.error?.message || "Request failed"
171
- }
172
- };
173
- }
174
- return {
175
- success: true,
176
- data: data.data || data
177
- };
178
- } catch (error) {
179
- return {
180
- success: false,
181
- error: {
182
- code: "NETWORK_ERROR",
183
- message: error instanceof Error ? error.message : "Network request failed"
184
- }
185
- };
186
- }
187
- }
188
- // ===============================
189
- // AUTH ENDPOINTS
190
- // ===============================
191
- /**
192
- * Send OTP to email for authentication
193
- */
194
- async sendEmailOtp(email) {
195
- return this.request("/api/v1/auth/otp", {
196
- method: "POST",
197
- body: JSON.stringify({ email })
198
- });
199
- }
200
- /**
201
- * Verify OTP and get access token
202
- */
203
- async verifyEmailOtp(email, otp) {
204
- return this.request("/api/v1/auth/otp/verify", {
205
- method: "POST",
206
- body: JSON.stringify({ email, otp })
207
- });
208
- }
209
- /**
210
- * Authenticate with wallet signature
211
- */
212
- async authWithWallet(walletAddress, signature, message) {
213
- return this.request("/api/v1/auth/wallet", {
214
- method: "POST",
215
- body: JSON.stringify({ walletAddress, signature, message })
216
- });
217
- }
218
- /**
219
- * Refresh access token
220
- */
221
- async refreshToken(refreshToken) {
222
- return this.request("/api/v1/auth/refresh", {
223
- method: "POST",
224
- body: JSON.stringify({ refreshToken })
225
- });
226
- }
227
- /**
228
- * Get current user
229
- */
230
- async getCurrentUser() {
231
- return this.request("/api/v1/auth/me", { method: "GET" });
232
- }
233
- /**
234
- * Sign out
235
- */
236
- async signOut() {
237
- return this.request("/api/v1/auth/logout", { method: "POST" });
238
- }
239
- // ===============================
240
- // WALLET/ASSETS ENDPOINTS
241
- // ===============================
242
- /**
243
- * Get wallet balance across all chains
244
- */
245
- async getWalletBalance(walletAddress, chains) {
246
- const params = new URLSearchParams({ address: walletAddress });
247
- if (chains?.length && chains.length > 0) {
248
- params.set("chainId", chains[0].toString());
249
- }
250
- return this.request(`/api/v1/assets?${params}`, { method: "GET" });
251
- }
252
- /**
253
- * Get portfolio summary
254
- */
255
- async getPortfolioSummary(walletAddress) {
256
- const params = new URLSearchParams({ address: walletAddress });
257
- return this.request(`/api/v1/assets/portfolio?${params}`, { method: "GET" });
258
- }
259
- /**
260
- * Get user's wallets
261
- */
262
- async getUserWallets(chainId) {
263
- const params = chainId ? `?chainId=${chainId}` : "";
264
- return this.request(`/api/v1/wallet${params}`, { method: "GET" });
265
- }
266
- /**
267
- * Create a new wallet
268
- */
269
- async createWallet(chainId = 8453, type = "smart") {
270
- return this.request("/api/v1/wallet", {
271
- method: "POST",
272
- body: JSON.stringify({ chainId, type })
273
- });
274
- }
275
- /**
276
- * Get wallet transactions (placeholder - needs endpoint)
277
- */
278
- async getWalletTransactions(walletAddress, options) {
279
- const params = new URLSearchParams({ address: walletAddress });
280
- if (options?.limit) params.set("limit", options.limit.toString());
281
- if (options?.offset) params.set("offset", options.offset.toString());
282
- if (options?.chainId) params.set("chainId", options.chainId.toString());
283
- return this.request(`/api/v1/assets/transactions?${params}`, { method: "GET" });
284
- }
285
- /**
286
- * Send native token or ERC20
287
- */
288
- async sendTransaction(request) {
289
- return this.request("/api/v1/wallet/send", {
290
- method: "POST",
291
- body: JSON.stringify(request)
292
- });
293
- }
294
- /**
295
- * Get transaction status
296
- */
297
- async getTransactionStatus(txId) {
298
- return this.request(`/api/v1/wallet/transaction/${txId}`, { method: "GET" });
299
- }
300
- // ===============================
301
- // ONRAMP ENDPOINTS (Fiat-to-Crypto)
302
- // ===============================
303
- /**
304
- * Get onramp quote
305
- */
306
- async getOnrampQuote(fiatCurrency, fiatAmount, cryptoCurrency, paymentMethod) {
307
- const params = new URLSearchParams({
308
- fiatCurrency,
309
- fiatAmount: fiatAmount.toString(),
310
- cryptoCurrency
311
- });
312
- if (paymentMethod) params.set("paymentMethod", paymentMethod);
313
- return this.request(`/api/v1/fiat/onramp/quote?${params}`, { method: "GET" });
314
- }
315
- /**
316
- * Create onramp session (returns widget URL)
317
- */
318
- async createOnrampSession(request) {
319
- return this.request("/api/v1/fiat/onramp", {
320
- method: "POST",
321
- body: JSON.stringify({
322
- fiatCurrency: request.fiatCurrency || "USD",
323
- fiatAmount: request.fiatAmount || 100,
324
- cryptoCurrency: request.cryptoCurrency || "ETH",
325
- walletAddress: request.walletAddress,
326
- chainId: 8453
327
- // Default to Base
328
- })
329
- });
330
- }
331
- /**
332
- * Get onramp session status
333
- */
334
- async getOnrampStatus(sessionId) {
335
- return this.request(`/api/v1/fiat/onramp/${sessionId}`, { method: "GET" });
336
- }
337
- /**
338
- * Get supported currencies (fiat + crypto)
339
- */
340
- async getSupportedCurrencies() {
341
- return this.request("/api/v1/fiat/onramp", { method: "GET" });
342
- }
343
- /**
344
- * Get supported fiat currencies
345
- */
346
- async getSupportedFiatCurrencies() {
347
- const result = await this.getSupportedCurrencies();
348
- if (result.success && result.data) {
349
- return { success: true, data: result.data.fiatCurrencies };
350
- }
351
- return { success: false, error: result.error };
352
- }
353
- /**
354
- * Get supported payment methods
355
- */
356
- async getSupportedPaymentMethods(country) {
357
- return { success: true, data: ["card", "bank_transfer", "apple_pay", "google_pay"] };
358
- }
359
- // ===============================
360
- // SWAP ENDPOINTS
361
- // ===============================
362
- /**
363
- * Get swap quote
364
- */
365
- async getSwapQuote(request) {
366
- return this.request("/api/v1/swap/quote", {
367
- method: "POST",
368
- body: JSON.stringify(request)
369
- });
370
- }
371
- /**
372
- * Execute swap
373
- */
374
- async executeSwap(request) {
375
- return this.request("/api/v1/swap/execute", {
376
- method: "POST",
377
- body: JSON.stringify(request)
378
- });
379
- }
380
- /**
381
- * Get swap status
382
- */
383
- async getSwapStatus(swapId) {
384
- return this.request(`/api/v1/swap/${swapId}`, { method: "GET" });
385
- }
386
- /**
387
- * Get supported tokens for swap
388
- */
389
- async getSupportedSwapTokens(chainId) {
390
- const params = chainId ? `?chainId=${chainId}` : "";
391
- return this.request(`/api/v1/swap/tokens${params}`, { method: "GET" });
392
- }
393
- /**
394
- * Get supported chains for swap
395
- */
396
- async getSupportedSwapChains() {
397
- return this.request("/api/v1/swap/chains", { method: "GET" });
398
- }
399
- // ===============================
400
- // AI TRADING/QUANT ENDPOINTS
401
- // ===============================
402
- /**
403
- * Get available AI trading strategies
404
- */
405
- async getStrategies() {
406
- return this.request("/api/v1/quant/strategies", { method: "GET" });
407
- }
408
- /**
409
- * Get strategy details
410
- */
411
- async getStrategy(strategyId) {
412
- return this.request(`/api/v1/quant/strategies/${strategyId}`, { method: "GET" });
413
- }
414
- /**
415
- * Get user's positions
416
- */
417
- async getPositions() {
418
- return this.request("/api/v1/quant/positions", { method: "GET" });
419
- }
420
- /**
421
- * Create investment order
422
- */
423
- async createOrder(strategyId, amount, currency) {
424
- return this.request("/api/v1/trading/orders", {
425
- method: "POST",
426
- body: JSON.stringify({ strategyId, amount, currency })
427
- });
428
- }
429
- /**
430
- * Get user's orders
431
- */
432
- async getUserOrders() {
433
- return this.request("/api/v1/trading/orders", { method: "GET" });
434
- }
435
- /**
436
- * Get user's portfolio stats from positions
437
- */
438
- async getPortfolioStats() {
439
- const positionsResult = await this.getPositions();
440
- if (positionsResult.success && positionsResult.data) {
441
- const positions = positionsResult.data;
442
- const totalInvested = positions.reduce((sum, p) => sum + (p.investedAmount || 0), 0);
443
- const totalValue = positions.reduce((sum, p) => sum + (p.currentValue || 0), 0);
444
- const totalPnl = totalValue - totalInvested;
445
- const totalPnlPercent = totalInvested > 0 ? totalPnl / totalInvested * 100 : 0;
446
- return {
447
- success: true,
448
- data: {
449
- totalInvested,
450
- totalValue,
451
- totalPnl,
452
- totalPnlPercent,
453
- activePositions: positions.filter((p) => p.status === "active").length
454
- }
455
- };
456
- }
457
- return {
458
- success: true,
459
- data: { totalInvested: 0, totalValue: 0, totalPnl: 0, totalPnlPercent: 0, activePositions: 0 }
460
- };
461
- }
462
- // ===============================
463
- // MARKET/PRICE ENDPOINTS
464
- // ===============================
465
- /**
466
- * Get token prices
467
- */
468
- async getTokenPrices(symbols) {
469
- const bybitSymbols = symbols.map((s) => {
470
- const upper = s.toUpperCase();
471
- if (upper.endsWith("USDT")) return upper;
472
- return `${upper}USDT`;
473
- });
474
- const result = await this.request(
475
- `/api/v1/trading/market?symbols=${bybitSymbols.join(",")}`,
476
- { method: "GET" }
477
- );
478
- if (result.success && result.data?.markets) {
479
- const prices = {};
480
- for (const market of result.data.markets) {
481
- const symbol = market.symbol?.replace("USDT", "") || "";
482
- prices[symbol] = {
483
- price: parseFloat(market.lastPrice) || 0,
484
- change24h: parseFloat(market.price24hPcnt) * 100 || 0,
485
- marketCap: void 0
486
- // Bybit doesn't provide this
487
- };
488
- }
489
- return { success: true, data: prices };
490
- }
491
- return { success: false, error: result.error };
492
- }
493
- /**
494
- * Get market data overview
495
- */
496
- async getMarketData() {
497
- const result = await this.request("/api/v1/trading/market", { method: "GET" });
498
- if (result.success && result.data?.markets) {
499
- return {
500
- success: true,
501
- data: {
502
- totalMarketCap: 0,
503
- // Would need separate API
504
- totalVolume24h: result.data.markets.reduce((sum, m) => sum + (parseFloat(m.volume24h) || 0), 0),
505
- btcDominance: 0,
506
- // Would need separate API
507
- markets: result.data.markets
508
- }
509
- };
510
- }
511
- return { success: false, error: result.error };
512
- }
513
- // ===============================
514
- // NFT ENDPOINTS
515
- // ===============================
516
- /**
517
- * Get user's NFTs
518
- */
519
- async getUserNFTs(walletAddress, options) {
520
- const params = new URLSearchParams({ address: walletAddress });
521
- if (options?.chainId) params.set("chainId", options.chainId.toString());
522
- if (options?.limit) params.set("limit", options.limit.toString());
523
- if (options?.offset) params.set("offset", options.offset.toString());
524
- return this.request(`/api/v1/assets/nfts?${params}`, { method: "GET" });
525
- }
526
- /**
527
- * Get NFT details
528
- */
529
- async getNFTDetails(contractAddress, tokenId, chainId) {
530
- return this.request(`/api/v1/assets/nfts/${contractAddress}/${tokenId}?chainId=${chainId}`, { method: "GET" });
531
- }
532
- /**
533
- * Get NFT collection
534
- */
535
- async getNFTCollection(contractAddress, chainId) {
536
- return this.request(`/api/v1/assets/nfts/collection/${contractAddress}?chainId=${chainId}`, { method: "GET" });
537
- }
538
- /**
539
- * Transfer NFT
540
- */
541
- async transferNFT(params) {
542
- return this.request("/api/v1/assets/nfts/transfer", {
543
- method: "POST",
544
- body: JSON.stringify(params)
545
- });
546
- }
547
- // ===============================
548
- // CONTRACT ENDPOINTS
549
- // ===============================
550
- /**
551
- * Get user's contracts
552
- */
553
- async getUserContracts(options) {
554
- const params = new URLSearchParams();
555
- if (options?.chainId) params.set("chainId", options.chainId.toString());
556
- if (options?.limit) params.set("limit", options.limit.toString());
557
- if (options?.offset) params.set("offset", options.offset.toString());
558
- return this.request(`/api/v1/contracts?${params}`, { method: "GET" });
559
- }
560
- /**
561
- * Get contract details
562
- */
563
- async getContractDetails(address, chainId) {
564
- return this.request(`/api/v1/contracts/${address}?chainId=${chainId}`, { method: "GET" });
565
- }
566
- /**
567
- * Read contract (call view function)
568
- */
569
- async readContract(params) {
570
- return this.request("/api/v1/contracts/read", {
571
- method: "POST",
572
- body: JSON.stringify(params)
573
- });
574
- }
575
- /**
576
- * Write to contract (execute transaction)
577
- */
578
- async writeContract(params) {
579
- return this.request("/api/v1/contracts/write", {
580
- method: "POST",
581
- body: JSON.stringify(params)
582
- });
583
- }
584
- /**
585
- * Deploy contract
586
- */
587
- async deployContract(params) {
588
- return this.request("/api/v1/contracts/deploy", {
589
- method: "POST",
590
- body: JSON.stringify(params)
591
- });
592
- }
593
- // ===============================
594
- // OFFRAMP ENDPOINTS (Crypto-to-Fiat)
595
- // ===============================
596
- /**
597
- * Get offramp quote
598
- */
599
- async getOfframpQuote(cryptoCurrency, cryptoAmount, fiatCurrency, payoutMethod) {
600
- const params = new URLSearchParams({
601
- cryptoCurrency,
602
- cryptoAmount: cryptoAmount.toString(),
603
- fiatCurrency
604
- });
605
- if (payoutMethod) params.set("payoutMethod", payoutMethod);
606
- return this.request(`/api/v1/fiat/offramp/quote?${params}`, { method: "GET" });
607
- }
608
- /**
609
- * Create offramp transaction
610
- */
611
- async createOfframpTransaction(request) {
612
- return this.request("/api/v1/fiat/offramp", {
613
- method: "POST",
614
- body: JSON.stringify(request)
615
- });
616
- }
617
- /**
618
- * Get offramp transaction status
619
- */
620
- async getOfframpStatus(transactionId) {
621
- return this.request(`/api/v1/fiat/offramp/${transactionId}`, { method: "GET" });
622
- }
623
- /**
624
- * Get supported payout methods
625
- */
626
- async getSupportedPayoutMethods(country) {
627
- const params = country ? `?country=${country}` : "";
628
- return this.request(`/api/v1/fiat/offramp/methods${params}`, { method: "GET" });
629
- }
630
- // ===============================
631
- // BILL PAYMENT ENDPOINTS
632
- // ===============================
633
- /**
634
- * Get bill providers
635
- */
636
- async getBillProviders(country, category) {
637
- const params = new URLSearchParams();
638
- if (country) params.set("country", country);
639
- if (category) params.set("category", category);
640
- return this.request(`/api/v1/bills/providers?${params}`, { method: "GET" });
641
- }
642
- /**
643
- * Get bill details/validate account
644
- */
645
- async validateBillAccount(providerId, accountNumber) {
646
- return this.request("/api/v1/bills/validate", {
647
- method: "POST",
648
- body: JSON.stringify({ providerId, accountNumber })
649
- });
650
- }
651
- /**
652
- * Pay bill
653
- */
654
- async payBill(params) {
655
- return this.request("/api/v1/bills/pay", {
656
- method: "POST",
657
- body: JSON.stringify(params)
658
- });
659
- }
660
- /**
661
- * Get bill payment history
662
- */
663
- async getBillHistory(options) {
664
- const params = new URLSearchParams();
665
- if (options?.limit) params.set("limit", options.limit.toString());
666
- if (options?.offset) params.set("offset", options.offset.toString());
667
- return this.request(`/api/v1/bills/history?${params}`, { method: "GET" });
668
- }
669
- // ===============================
670
- // STAKING ENDPOINTS
671
- // ===============================
672
- /**
673
- * Get staking pools
674
- */
675
- async getStakingPools(chainId) {
676
- const params = chainId ? `?chainId=${chainId}` : "";
677
- return this.request(`/api/v1/staking/pools${params}`, { method: "GET" });
678
- }
679
- /**
680
- * Get user's staking positions
681
- */
682
- async getStakingPositions() {
683
- return this.request("/api/v1/staking/positions", { method: "GET" });
684
- }
685
- /**
686
- * Stake tokens
687
- */
688
- async stake(params) {
689
- return this.request("/api/v1/staking/stake", {
690
- method: "POST",
691
- body: JSON.stringify(params)
692
- });
693
- }
694
- /**
695
- * Unstake tokens
696
- */
697
- async unstake(params) {
698
- return this.request("/api/v1/staking/unstake", {
699
- method: "POST",
700
- body: JSON.stringify(params)
701
- });
702
- }
703
- /**
704
- * Claim staking rewards
705
- */
706
- async claimStakingRewards(positionId) {
707
- return this.request("/api/v1/staking/claim", {
708
- method: "POST",
709
- body: JSON.stringify({ positionId })
710
- });
711
- }
712
- // ===============================
713
- // USER PROFILE ENDPOINTS
714
- // ===============================
715
- /**
716
- * Get user profile
717
- */
718
- async getUserProfile() {
719
- return this.request("/api/v1/user/profile", { method: "GET" });
720
- }
721
- /**
722
- * Update user profile
723
- */
724
- async updateUserProfile(updates) {
725
- return this.request("/api/v1/user/profile", {
726
- method: "PATCH",
727
- body: JSON.stringify(updates)
728
- });
729
- }
730
- /**
731
- * Get user settings
732
- */
733
- async getUserSettings() {
734
- return this.request("/api/v1/user/settings", { method: "GET" });
735
- }
736
- /**
737
- * Update user settings
738
- */
739
- async updateUserSettings(updates) {
740
- return this.request("/api/v1/user/settings", {
741
- method: "PATCH",
742
- body: JSON.stringify(updates)
743
- });
744
- }
745
- // ===============================
746
- // NOTIFICATION ENDPOINTS
747
- // ===============================
748
- /**
749
- * Get notifications
750
- */
751
- async getNotifications(options) {
752
- const params = new URLSearchParams();
753
- if (options?.unreadOnly) params.set("unreadOnly", "true");
754
- if (options?.limit) params.set("limit", options.limit.toString());
755
- if (options?.offset) params.set("offset", options.offset.toString());
756
- return this.request(`/api/v1/notifications?${params}`, { method: "GET" });
757
- }
758
- /**
759
- * Mark notification as read
760
- */
761
- async markNotificationRead(notificationId) {
762
- return this.request(`/api/v1/notifications/${notificationId}/read`, { method: "POST" });
763
- }
764
- /**
765
- * Mark all notifications as read
766
- */
767
- async markAllNotificationsRead() {
768
- return this.request("/api/v1/notifications/read-all", { method: "POST" });
769
- }
770
- // ===============================
771
- // REFERRAL ENDPOINTS
772
- // ===============================
773
- /**
774
- * Get referral info
775
- */
776
- async getReferralInfo() {
777
- return this.request("/api/v1/referral", { method: "GET" });
778
- }
779
- /**
780
- * Get referred users
781
- */
782
- async getReferrals() {
783
- return this.request("/api/v1/referral/list", { method: "GET" });
784
- }
785
- /**
786
- * Apply referral code
787
- */
788
- async applyReferralCode(code) {
789
- return this.request("/api/v1/referral/apply", {
790
- method: "POST",
791
- body: JSON.stringify({ code })
792
- });
793
- }
794
- /**
795
- * Claim referral rewards
796
- */
797
- async claimReferralRewards() {
798
- return this.request("/api/v1/referral/claim", { method: "POST" });
799
- }
800
- // ===============================
801
- // KYC ENDPOINTS
802
- // ===============================
803
- /**
804
- * Get KYC status
805
- */
806
- async getKycStatus() {
807
- return this.request("/api/v1/kyc/status", { method: "GET" });
808
- }
809
- /**
810
- * Start KYC verification
811
- */
812
- async startKycVerification(level) {
813
- return this.request("/api/v1/kyc/start", {
814
- method: "POST",
815
- body: JSON.stringify({ level })
816
- });
817
- }
818
- /**
819
- * Submit KYC documents
820
- */
821
- async submitKycDocuments(params) {
822
- return this.request("/api/v1/kyc/submit", {
823
- method: "POST",
824
- body: JSON.stringify(params)
825
- });
826
- }
827
- // ===============================
828
- // BRIDGE ENDPOINTS
829
- // ===============================
830
- /**
831
- * Get bridge quote
832
- */
833
- async getBridgeQuote(params) {
834
- return this.request("/api/v1/bridge/quote", {
835
- method: "POST",
836
- body: JSON.stringify(params)
837
- });
838
- }
839
- /**
840
- * Execute bridge transaction
841
- */
842
- async executeBridge(params) {
843
- return this.request("/api/v1/bridge/execute", {
844
- method: "POST",
845
- body: JSON.stringify(params)
846
- });
847
- }
848
- /**
849
- * Get bridge transaction status
850
- */
851
- async getBridgeStatus(bridgeId) {
852
- return this.request(`/api/v1/bridge/${bridgeId}`, { method: "GET" });
853
- }
854
- /**
855
- * Get supported bridge routes
856
- */
857
- async getSupportedBridgeRoutes() {
858
- return this.request("/api/v1/bridge/routes", { method: "GET" });
859
- }
860
- // ===============================
861
- // GAS ENDPOINTS
862
- // ===============================
863
- /**
864
- * Get gas estimate for transaction
865
- */
866
- async getGasEstimate(params) {
867
- return this.request("/api/v1/gas/estimate", {
868
- method: "POST",
869
- body: JSON.stringify(params)
870
- });
871
- }
872
- /**
873
- * Get current gas prices for chain
874
- */
875
- async getGasPrice(chainId) {
876
- return this.request(`/api/v1/gas/price?chainId=${chainId}`, { method: "GET" });
877
- }
878
- // ===============================
879
- // WALLET IMPORT/EXPORT ENDPOINTS
880
- // ===============================
881
- /**
882
- * Import wallet from private key or mnemonic
883
- */
884
- async importWallet(request) {
885
- return this.request("/api/v1/wallet/import", {
886
- method: "POST",
887
- body: JSON.stringify(request)
888
- }, true);
889
- }
890
- /**
891
- * Export wallet (get encrypted private key)
892
- * Requires additional authentication
893
- */
894
- async exportWallet(walletId, pin) {
895
- return this.request("/api/v1/wallet/export", {
896
- method: "POST",
897
- body: JSON.stringify({ walletId, pin })
898
- }, true);
899
- }
900
- /**
901
- * Generate new mnemonic phrase
902
- */
903
- async generateMnemonic() {
904
- return this.request("/api/v1/wallet/generate-mnemonic", { method: "POST" }, true);
905
- }
906
- /**
907
- * Validate mnemonic phrase
908
- */
909
- async validateMnemonic(mnemonic) {
910
- return this.request("/api/v1/wallet/validate-mnemonic", {
911
- method: "POST",
912
- body: JSON.stringify({ mnemonic })
913
- });
914
- }
915
- // ===============================
916
- // PORTFOLIO ANALYTICS ENDPOINTS
917
- // ===============================
918
- /**
919
- * Get portfolio analytics with historical data
920
- */
921
- async getPortfolioAnalytics(walletAddress, period = "30d") {
922
- const params = new URLSearchParams({ address: walletAddress, period });
923
- return this.request(`/api/v1/analytics/portfolio?${params}`, { method: "GET" });
924
- }
925
- /**
926
- * Get transaction analytics
927
- */
928
- async getTransactionAnalytics(walletAddress, period = "30d") {
929
- const params = new URLSearchParams({ address: walletAddress, period });
930
- return this.request(`/api/v1/analytics/transactions?${params}`, { method: "GET" });
931
- }
932
- // ===============================
933
- // ADVANCED TRADING ENDPOINTS
934
- // ===============================
935
- /**
936
- * Create limit order
937
- */
938
- async createLimitOrder(params) {
939
- return this.request("/api/v1/trading/limit-orders", {
940
- method: "POST",
941
- body: JSON.stringify(params)
942
- });
943
- }
944
- /**
945
- * Get user's limit orders
946
- */
947
- async getLimitOrders(status) {
948
- const params = status ? `?status=${status}` : "";
949
- return this.request(`/api/v1/trading/limit-orders${params}`, { method: "GET" });
950
- }
951
- /**
952
- * Cancel limit order
953
- */
954
- async cancelLimitOrder(orderId) {
955
- return this.request(`/api/v1/trading/limit-orders/${orderId}`, { method: "DELETE" });
956
- }
957
- /**
958
- * Set price alert
959
- */
960
- async setPriceAlert(params) {
961
- return this.request("/api/v1/trading/alerts", {
962
- method: "POST",
963
- body: JSON.stringify(params)
964
- });
965
- }
966
- /**
967
- * Get price alerts
968
- */
969
- async getPriceAlerts() {
970
- return this.request("/api/v1/trading/alerts", { method: "GET" });
971
- }
972
- /**
973
- * Delete price alert
974
- */
975
- async deletePriceAlert(alertId) {
976
- return this.request(`/api/v1/trading/alerts/${alertId}`, { method: "DELETE" });
977
- }
978
- // ===============================
979
- // SESSION MANAGEMENT
980
- // ===============================
981
- /**
982
- * Get active sessions
983
- */
984
- async getActiveSessions() {
985
- return this.request("/api/v1/auth/sessions", { method: "GET" });
986
- }
987
- /**
988
- * Revoke session
989
- */
990
- async revokeSession(sessionId) {
991
- return this.request(`/api/v1/auth/sessions/${sessionId}`, { method: "DELETE" });
992
- }
993
- /**
994
- * Revoke all other sessions
995
- */
996
- async revokeAllOtherSessions() {
997
- return this.request("/api/v1/auth/sessions/revoke-all", { method: "POST" });
998
- }
999
- // ========== Webhooks ==========
1000
- /**
1001
- * List webhooks for the project
1002
- */
1003
- async listWebhooks(options) {
1004
- const params = new URLSearchParams();
1005
- if (options?.isActive !== void 0) params.set("isActive", String(options.isActive));
1006
- const query = params.toString();
1007
- return this.request(`/api/v1/webhooks${query ? `?${query}` : ""}`, { method: "GET" });
1008
- }
1009
- /**
1010
- * Get webhook by ID
1011
- */
1012
- async getWebhook(webhookId) {
1013
- return this.request(`/api/v1/webhooks/${webhookId}`, { method: "GET" });
1014
- }
1015
- /**
1016
- * Create a webhook
1017
- */
1018
- async createWebhook(input) {
1019
- return this.request("/api/v1/webhooks", {
1020
- method: "POST",
1021
- body: JSON.stringify(input)
1022
- });
1023
- }
1024
- /**
1025
- * Update a webhook
1026
- */
1027
- async updateWebhook(webhookId, input) {
1028
- return this.request(`/api/v1/webhooks/${webhookId}`, {
1029
- method: "PATCH",
1030
- body: JSON.stringify(input)
1031
- });
1032
- }
1033
- /**
1034
- * Delete a webhook
1035
- */
1036
- async deleteWebhook(webhookId) {
1037
- return this.request(`/api/v1/webhooks/${webhookId}`, { method: "DELETE" });
1038
- }
1039
- /**
1040
- * Get webhook deliveries
1041
- */
1042
- async getWebhookDeliveries(webhookId, options) {
1043
- const params = new URLSearchParams();
1044
- if (options?.status) params.set("status", options.status);
1045
- if (options?.limit) params.set("limit", String(options.limit));
1046
- if (options?.offset) params.set("offset", String(options.offset));
1047
- const query = params.toString();
1048
- return this.request(`/api/v1/webhooks/${webhookId}/deliveries${query ? `?${query}` : ""}`, { method: "GET" });
1049
- }
1050
- /**
1051
- * Test a webhook
1052
- */
1053
- async testWebhook(webhookId) {
1054
- return this.request(`/api/v1/webhooks/${webhookId}/test`, { method: "POST" });
1055
- }
1056
- // ========== Admin (requires admin role) ==========
1057
- /**
1058
- * List all users (admin only)
1059
- */
1060
- async adminListUsers(options) {
1061
- const params = new URLSearchParams();
1062
- if (options?.page) params.set("page", String(options.page));
1063
- if (options?.limit) params.set("limit", String(options.limit));
1064
- if (options?.search) params.set("search", options.search);
1065
- if (options?.sortBy) params.set("sortBy", options.sortBy);
1066
- if (options?.sortOrder) params.set("sortOrder", options.sortOrder);
1067
- if (options?.role) params.set("role", options.role);
1068
- if (options?.kycStatus) params.set("kycStatus", options.kycStatus);
1069
- if (options?.isActive !== void 0) params.set("isActive", String(options.isActive));
1070
- const query = params.toString();
1071
- return this.request(`/api/v1/admin/users${query ? `?${query}` : ""}`, { method: "GET" });
1072
- }
1073
- /**
1074
- * Get user by ID (admin only)
1075
- */
1076
- async adminGetUser(userId) {
1077
- return this.request(`/api/v1/admin/users/${userId}`, { method: "GET" });
1078
- }
1079
- /**
1080
- * Update user (admin only)
1081
- */
1082
- async adminUpdateUser(userId, data) {
1083
- return this.request(`/api/v1/admin/users/${userId}`, {
1084
- method: "PATCH",
1085
- body: JSON.stringify(data)
1086
- });
1087
- }
1088
- /**
1089
- * List all projects (admin only)
1090
- */
1091
- async adminListProjects(options) {
1092
- const params = new URLSearchParams();
1093
- if (options?.page) params.set("page", String(options.page));
1094
- if (options?.limit) params.set("limit", String(options.limit));
1095
- if (options?.search) params.set("search", options.search);
1096
- if (options?.sortBy) params.set("sortBy", options.sortBy);
1097
- if (options?.sortOrder) params.set("sortOrder", options.sortOrder);
1098
- if (options?.isActive !== void 0) params.set("isActive", String(options.isActive));
1099
- const query = params.toString();
1100
- return this.request(`/api/v1/admin/projects${query ? `?${query}` : ""}`, { method: "GET" });
1101
- }
1102
- /**
1103
- * Get project by ID (admin only)
1104
- */
1105
- async adminGetProject(projectId) {
1106
- return this.request(`/api/v1/admin/projects/${projectId}`, { method: "GET" });
1107
- }
1108
- /**
1109
- * Update project (admin only)
1110
- */
1111
- async adminUpdateProject(projectId, data) {
1112
- return this.request(`/api/v1/admin/projects/${projectId}`, {
1113
- method: "PATCH",
1114
- body: JSON.stringify(data)
1115
- });
1116
- }
1117
- /**
1118
- * Regenerate project API key (admin only)
1119
- */
1120
- async adminRegenerateApiKey(projectId) {
1121
- return this.request(`/api/v1/admin/projects/${projectId}/regenerate-key`, { method: "POST" });
1122
- }
1123
- /**
1124
- * Get system statistics (admin only)
1125
- */
1126
- async adminGetStats(days) {
1127
- const query = days ? `?days=${days}` : "";
1128
- return this.request(`/api/v1/admin/stats${query}`, { method: "GET" });
1129
- }
1130
- /**
1131
- * Get system logs (admin only)
1132
- */
1133
- async adminGetLogs(options) {
1134
- const params = new URLSearchParams();
1135
- if (options?.level) params.set("level", options.level);
1136
- if (options?.service) params.set("service", options.service);
1137
- if (options?.limit) params.set("limit", String(options.limit));
1138
- if (options?.offset) params.set("offset", String(options.offset));
1139
- if (options?.startDate) params.set("startDate", options.startDate);
1140
- if (options?.endDate) params.set("endDate", options.endDate);
1141
- const query = params.toString();
1142
- return this.request(`/api/v1/admin/logs${query ? `?${query}` : ""}`, { method: "GET" });
1143
- }
1144
- /**
1145
- * Get rate limit status (admin only)
1146
- */
1147
- async adminGetRateLimits(options) {
1148
- const params = new URLSearchParams();
1149
- if (options?.identifier) params.set("identifier", options.identifier);
1150
- if (options?.limit) params.set("limit", String(options.limit));
1151
- const query = params.toString();
1152
- return this.request(`/api/v1/admin/rate-limits${query ? `?${query}` : ""}`, { method: "GET" });
1153
- }
1154
- /**
1155
- * Clear rate limits for an identifier (admin only)
1156
- */
1157
- async adminClearRateLimits(identifier) {
1158
- return this.request(`/api/v1/admin/rate-limits/${identifier}`, { method: "DELETE" });
1159
- }
1160
- // ========== AI Quant Trading ==========
1161
- /**
1162
- * Get all AI trading strategies
1163
- */
1164
- async getAIStrategies(filters) {
1165
- const params = new URLSearchParams();
1166
- if (filters?.category) params.set("category", filters.category);
1167
- if (filters?.riskLevel) params.set("risk_level", String(filters.riskLevel));
1168
- if (filters?.minTvl) params.set("min_tvl", String(filters.minTvl));
1169
- if (filters?.isActive !== void 0) params.set("is_active", String(filters.isActive));
1170
- const query = params.toString();
1171
- return this.request(`/api/v1/ai-quant/strategies${query ? `?${query}` : ""}`, { method: "GET" });
1172
- }
1173
- /**
1174
- * Get AI strategy details
1175
- */
1176
- async getAIStrategy(strategyId, include) {
1177
- const params = new URLSearchParams();
1178
- if (include?.length) params.set("include", include.join(","));
1179
- const query = params.toString();
1180
- return this.request(`/api/v1/ai-quant/strategies/${strategyId}${query ? `?${query}` : ""}`, { method: "GET" });
1181
- }
1182
- /**
1183
- * Get strategy performance history
1184
- */
1185
- async getAIStrategyPerformance(strategyId, days = 30) {
1186
- return this.request(`/api/v1/ai-quant/strategies/${strategyId}?include=performance&days=${days}`, { method: "GET" });
1187
- }
1188
- /**
1189
- * Get real-time market data for strategy pairs
1190
- */
1191
- async getAIStrategyMarketData(strategyId) {
1192
- return this.request(`/api/v1/ai-quant/strategies/${strategyId}?include=market`, { method: "GET" });
1193
- }
1194
- /**
1195
- * Create AI trading order
1196
- */
1197
- async createAIOrder(request) {
1198
- return this.request("/api/v1/ai-quant/orders", {
1199
- method: "POST",
1200
- body: JSON.stringify(request)
1201
- });
1202
- }
1203
- /**
1204
- * Get user's AI orders
1205
- */
1206
- async getAIOrders(filters) {
1207
- const params = new URLSearchParams();
1208
- if (filters?.strategyId) params.set("strategy_id", filters.strategyId);
1209
- if (filters?.status) params.set("status", filters.status);
1210
- const query = params.toString();
1211
- return this.request(`/api/v1/ai-quant/orders${query ? `?${query}` : ""}`, { method: "GET" });
1212
- }
1213
- /**
1214
- * Get AI order details
1215
- */
1216
- async getAIOrder(orderId) {
1217
- return this.request(`/api/v1/ai-quant/orders/${orderId}`, { method: "GET" });
1218
- }
1219
- /**
1220
- * Pause AI order
1221
- */
1222
- async pauseAIOrder(orderId) {
1223
- return this.request(`/api/v1/ai-quant/orders/${orderId}/pause`, { method: "POST" });
1224
- }
1225
- /**
1226
- * Resume AI order
1227
- */
1228
- async resumeAIOrder(orderId) {
1229
- return this.request(`/api/v1/ai-quant/orders/${orderId}/resume`, { method: "POST" });
1230
- }
1231
- /**
1232
- * Request redemption for AI order
1233
- */
1234
- async redeemAIOrder(orderId) {
1235
- return this.request(`/api/v1/ai-quant/orders/${orderId}/redeem`, { method: "POST" });
1236
- }
1237
- /**
1238
- * Get AI portfolio summary
1239
- */
1240
- async getAIPortfolio(include) {
1241
- const params = new URLSearchParams();
1242
- if (include?.length) params.set("include", include.join(","));
1243
- const query = params.toString();
1244
- return this.request(`/api/v1/ai-quant/portfolio${query ? `?${query}` : ""}`, { method: "GET" });
1245
- }
1246
- /**
1247
- * Get user's trade allocations
1248
- */
1249
- async getAITradeAllocations(limit = 50) {
1250
- return this.request(`/api/v1/ai-quant/portfolio?include=allocations&limit=${limit}`, { method: "GET" });
1251
- }
1252
- /**
1253
- * Get trade history for a strategy
1254
- */
1255
- async getAITradeHistory(strategyId, limit = 50) {
1256
- return this.request(`/api/v1/ai-quant/strategies/${strategyId}?include=trades&limit=${limit}`, { method: "GET" });
1257
- }
1258
- /**
1259
- * Execute AI signals for a strategy (admin only)
1260
- */
1261
- async executeAISignals(strategyId) {
1262
- return this.request("/api/v1/ai-quant/execute", {
1263
- method: "POST",
1264
- body: JSON.stringify({ strategyId })
1265
- });
1266
- }
1267
- // ========== Free Price APIs (No API Key Required) ==========
1268
- /**
1269
- * Get cryptocurrency prices (FREE - uses CoinGecko/Binance/CoinCap)
1270
- */
1271
- async getCryptoPrices(symbols) {
1272
- return this.request(`/api/v1/prices?symbols=${symbols.join(",")}`, { method: "GET" });
1273
- }
1274
- /**
1275
- * Get single cryptocurrency price (FREE)
1276
- */
1277
- async getCryptoPrice(symbol) {
1278
- return this.request(`/api/v1/prices/${symbol}`, { method: "GET" });
1279
- }
1280
- /**
1281
- * Get OHLCV candles for charting (FREE - from Binance)
1282
- */
1283
- async getCryptoCandles(symbol, interval = "1h", limit = 100) {
1284
- return this.request(`/api/v1/prices/${symbol}?candles=true&interval=${interval}&limit=${limit}`, { method: "GET" });
1285
- }
1286
- /**
1287
- * Get top cryptocurrencies by market cap (FREE)
1288
- */
1289
- async getTopCryptos(limit = 20) {
1290
- return this.request(`/api/v1/prices?type=top&limit=${limit}`, { method: "GET" });
1291
- }
1292
- /**
1293
- * Get crypto market overview (FREE)
1294
- */
1295
- async getCryptoMarketOverview() {
1296
- return this.request("/api/v1/prices?type=overview", { method: "GET" });
1297
- }
1298
- };
1299
- function createOneEngineClient(options) {
1300
- return new OneEngineClient(options);
1301
- }
1302
-
1303
- // src/services/price.ts
1304
- var COINGECKO_API = "https://api.coingecko.com/api/v3";
1305
- var FALLBACK_PRICES = {
1306
- ETH: 3500,
1307
- BTC: 95e3,
1308
- BNB: 700,
1309
- MATIC: 0.5,
1310
- AVAX: 40,
1311
- USDT: 1,
1312
- USDC: 1,
1313
- DAI: 1,
1314
- WBTC: 95e3,
1315
- WETH: 3500,
1316
- ARB: 1.2,
1317
- OP: 2.5,
1318
- LINK: 20,
1319
- UNI: 12,
1320
- AAVE: 250,
1321
- SOL: 200
1322
- };
1323
- var PriceService = class {
1324
- constructor() {
1325
- this.cache = /* @__PURE__ */ new Map();
1326
- this.cacheTTL = 60 * 1e3;
1327
- }
1328
- // 1 minute cache
1329
- async getPrice(symbol) {
1330
- const upperSymbol = symbol.toUpperCase();
1331
- const cached = this.cache.get(upperSymbol);
1332
- if (cached && Date.now() - cached.timestamp < this.cacheTTL) {
1333
- return cached.price;
1334
- }
1335
- const coinId = COINGECKO_IDS[upperSymbol];
1336
- if (!coinId) {
1337
- return this.getFallbackPrice(upperSymbol);
1338
- }
1339
- try {
1340
- const response = await fetch(
1341
- `${COINGECKO_API}/simple/price?ids=${coinId}&vs_currencies=usd&include_24hr_change=true&include_market_cap=true&include_24hr_vol=true`,
1342
- { headers: { Accept: "application/json" } }
1343
- );
1344
- if (!response.ok) {
1345
- throw new Error(`CoinGecko API error: ${response.status}`);
1346
- }
1347
- const data = await response.json();
1348
- const coinData = data[coinId];
1349
- if (!coinData) {
1350
- return this.getFallbackPrice(upperSymbol);
1351
- }
1352
- const change24h = coinData.usd_24h_change || 0;
1353
- const price = {
1354
- symbol: upperSymbol,
1355
- price: coinData.usd || 0,
1356
- change24h,
1357
- changePercent24h: change24h,
1358
- priceChange24h: change24h,
1359
- marketCap: coinData.usd_market_cap,
1360
- volume24h: coinData.usd_24h_vol
1361
- };
1362
- this.cache.set(upperSymbol, { price, timestamp: Date.now() });
1363
- return price;
1364
- } catch (error) {
1365
- console.warn(`Failed to fetch price for ${upperSymbol}:`, error);
1366
- return this.getFallbackPrice(upperSymbol);
1367
- }
1368
- }
1369
- async getPrices(symbols) {
1370
- const results = {};
1371
- const withIds = [];
1372
- const withoutIds = [];
1373
- for (const symbol of symbols) {
1374
- const upper = symbol.toUpperCase();
1375
- if (COINGECKO_IDS[upper]) {
1376
- withIds.push(upper);
1377
- } else {
1378
- withoutIds.push(upper);
1379
- }
1380
- }
1381
- for (const symbol of withoutIds) {
1382
- results[symbol] = this.getFallbackPrice(symbol);
1383
- }
1384
- if (withIds.length === 0) {
1385
- return results;
1386
- }
1387
- const coinIds = withIds.map((s) => COINGECKO_IDS[s]).join(",");
1388
- try {
1389
- const response = await fetch(
1390
- `${COINGECKO_API}/simple/price?ids=${coinIds}&vs_currencies=usd&include_24hr_change=true`,
1391
- { headers: { Accept: "application/json" } }
1392
- );
1393
- if (!response.ok) {
1394
- throw new Error(`CoinGecko API error: ${response.status}`);
1395
- }
1396
- const data = await response.json();
1397
- for (const symbol of withIds) {
1398
- const coinId = COINGECKO_IDS[symbol];
1399
- const coinData = data[coinId];
1400
- if (coinData) {
1401
- const change24h = coinData.usd_24h_change || 0;
1402
- results[symbol] = {
1403
- symbol,
1404
- price: coinData.usd || 0,
1405
- change24h,
1406
- changePercent24h: change24h,
1407
- priceChange24h: change24h
1408
- };
1409
- } else {
1410
- results[symbol] = this.getFallbackPrice(symbol);
1411
- }
1412
- }
1413
- } catch (error) {
1414
- console.warn("Failed to fetch batch prices:", error);
1415
- for (const symbol of withIds) {
1416
- results[symbol] = this.getFallbackPrice(symbol);
1417
- }
1418
- }
1419
- return results;
1420
- }
1421
- getFallbackPrice(symbol) {
1422
- const price = FALLBACK_PRICES[symbol] || 0;
1423
- return {
1424
- symbol,
1425
- price,
1426
- change24h: 0,
1427
- changePercent24h: 0,
1428
- priceChange24h: 0
1429
- };
1430
- }
1431
- clearCache() {
1432
- this.cache.clear();
1433
- }
1434
- };
1435
- var priceService = new PriceService();
1436
-
1437
- // src/utils/index.ts
1438
- function shortenAddress(address, chars = 4) {
1439
- if (!address) return "";
1440
- return `${address.slice(0, chars + 2)}...${address.slice(-chars)}`;
1441
- }
1442
- function isValidAddress(address) {
1443
- return /^0x[a-fA-F0-9]{40}$/.test(address);
1444
- }
1445
- function checksumAddress(address) {
1446
- return address.toLowerCase();
1447
- }
1448
- function formatNumber(value, options = {}) {
1449
- const { decimals = 2, compact = false, currency, locale = "en-US" } = options;
1450
- if (currency) {
1451
- return new Intl.NumberFormat(locale, {
1452
- style: "currency",
1453
- currency,
1454
- minimumFractionDigits: decimals,
1455
- maximumFractionDigits: decimals,
1456
- notation: compact ? "compact" : "standard"
1457
- }).format(value);
1458
- }
1459
- return new Intl.NumberFormat(locale, {
1460
- minimumFractionDigits: decimals,
1461
- maximumFractionDigits: decimals,
1462
- notation: compact ? "compact" : "standard"
1463
- }).format(value);
1464
- }
1465
- function formatUSD(value, compact = false) {
1466
- return formatNumber(value, { currency: "USD", compact });
1467
- }
1468
- function formatPercent(value, decimals = 2) {
1469
- const sign = value >= 0 ? "+" : "";
1470
- return `${sign}${value.toFixed(decimals)}%`;
1471
- }
1472
- function formatTokenAmount(amount, decimals = 6) {
1473
- if (amount === 0) return "0";
1474
- if (amount < 1e-6) return "<0.000001";
1475
- if (amount < 1) return amount.toFixed(decimals);
1476
- if (amount < 1e3) return amount.toFixed(4);
1477
- if (amount < 1e6) return formatNumber(amount, { decimals: 2 });
1478
- return formatNumber(amount, { decimals: 2, compact: true });
1479
- }
1480
- function formatDate(date, options = {
1481
- year: "numeric",
1482
- month: "short",
1483
- day: "numeric"
1484
- }) {
1485
- const d = typeof date === "string" ? new Date(date) : date;
1486
- return d.toLocaleDateString("en-US", options);
1487
- }
1488
- function formatDateTime(date) {
1489
- const d = typeof date === "string" ? new Date(date) : date;
1490
- return d.toLocaleString("en-US", {
1491
- year: "numeric",
1492
- month: "short",
1493
- day: "numeric",
1494
- hour: "2-digit",
1495
- minute: "2-digit"
1496
- });
1497
- }
1498
- function formatRelativeTime(date) {
1499
- const d = typeof date === "string" ? new Date(date) : date;
1500
- const now = /* @__PURE__ */ new Date();
1501
- const diffMs = now.getTime() - d.getTime();
1502
- const diffSec = Math.floor(diffMs / 1e3);
1503
- const diffMin = Math.floor(diffSec / 60);
1504
- const diffHour = Math.floor(diffMin / 60);
1505
- const diffDay = Math.floor(diffHour / 24);
1506
- if (diffSec < 60) return "just now";
1507
- if (diffMin < 60) return `${diffMin}m ago`;
1508
- if (diffHour < 24) return `${diffHour}h ago`;
1509
- if (diffDay < 7) return `${diffDay}d ago`;
1510
- return formatDate(d);
1511
- }
1512
- function isValidEmail(email) {
1513
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1514
- return emailRegex.test(email);
1515
- }
1516
- function isValidPhone(phone) {
1517
- const phoneRegex = /^\+?[1-9]\d{1,14}$/;
1518
- return phoneRegex.test(phone.replace(/[\s-()]/g, ""));
1519
- }
1520
- function capitalize(str) {
1521
- return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
1522
- }
1523
- function truncate(str, length) {
1524
- if (str.length <= length) return str;
1525
- return `${str.slice(0, length)}...`;
1526
- }
1527
- function slugify(str) {
1528
- return str.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
1529
- }
1530
- function sleep(ms) {
1531
- return new Promise((resolve) => setTimeout(resolve, ms));
1532
- }
1533
- async function retry(fn, options = {}) {
1534
- const { maxAttempts = 3, delay = 1e3, backoff = 2 } = options;
1535
- let lastError;
1536
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1537
- try {
1538
- return await fn();
1539
- } catch (error) {
1540
- lastError = error instanceof Error ? error : new Error(String(error));
1541
- if (attempt < maxAttempts) {
1542
- await sleep(delay * Math.pow(backoff, attempt - 1));
1543
- }
1544
- }
1545
- }
1546
- throw lastError;
1547
- }
1548
- function omit(obj, keys) {
1549
- const result = { ...obj };
1550
- for (const key of keys) {
1551
- delete result[key];
1552
- }
1553
- return result;
1554
- }
1555
- function pick(obj, keys) {
1556
- const result = {};
1557
- for (const key of keys) {
1558
- if (key in obj) {
1559
- result[key] = obj[key];
1560
- }
1561
- }
1562
- return result;
1563
- }
1564
- var OneSDKError = class extends Error {
1565
- constructor(message, code, details) {
1566
- super(message);
1567
- this.name = "OneSDKError";
1568
- this.code = code;
1569
- this.details = details;
1570
- }
1571
- };
1572
- function isOneSDKError(error) {
1573
- return error instanceof OneSDKError;
1574
- }
1575
-
1576
- // src/react-native.ts
1577
- function createCachedEngineClient(storage, options) {
1578
- const client = createOneEngineClient(options);
1579
- return {
1580
- ...client,
1581
- /**
1582
- * Initialize with stored token
1583
- */
1584
- async initialize() {
1585
- const token = await storage.getItem("one_access_token");
1586
- if (token) {
1587
- client.setAccessToken(token);
1588
- return true;
1589
- }
1590
- return false;
1591
- },
1592
- /**
1593
- * Login and persist token
1594
- */
1595
- async login(email, otp) {
1596
- const result = await client.verifyEmailOtp(email, otp);
1597
- if (result.success && result.data?.accessToken) {
1598
- await storage.setItem("one_access_token", result.data.accessToken);
1599
- if (result.data.refreshToken) {
1600
- await storage.setItem("one_refresh_token", result.data.refreshToken);
1601
- }
1602
- }
1603
- return result;
1604
- },
1605
- /**
1606
- * Logout and clear stored tokens
1607
- */
1608
- async logout() {
1609
- await client.signOut();
1610
- await storage.removeItem("one_access_token");
1611
- await storage.removeItem("one_refresh_token");
1612
- client.clearAccessToken();
1613
- },
1614
- /**
1615
- * Refresh token from storage
1616
- */
1617
- async refreshFromStorage() {
1618
- const refreshToken = await storage.getItem("one_refresh_token");
1619
- if (refreshToken) {
1620
- const result = await client.refreshToken(refreshToken);
1621
- if (result.success && result.data?.accessToken) {
1622
- await storage.setItem("one_access_token", result.data.accessToken);
1623
- if (result.data.refreshToken) {
1624
- await storage.setItem("one_refresh_token", result.data.refreshToken);
1625
- }
1626
- return true;
1627
- }
1628
- }
1629
- return false;
1630
- },
1631
- // Expose underlying client
1632
- getClient: () => client
1633
- };
1634
- }
1635
- function createDeepLinkHandler(scheme = "onewallet") {
1636
- return {
1637
- parse(url) {
1638
- try {
1639
- const urlObj = new URL(url);
1640
- const path = urlObj.pathname.replace(/^\//, "");
1641
- const params = {};
1642
- urlObj.searchParams.forEach((value, key) => {
1643
- params[key] = value;
1644
- });
1645
- let type = "unknown";
1646
- if (path.includes("onramp") || path.includes("callback")) {
1647
- type = "onramp_callback";
1648
- } else if (path.includes("wc") || path.includes("walletconnect")) {
1649
- type = "wallet_connect";
1650
- } else if (path.includes("pay") || path.includes("payment")) {
1651
- type = "payment";
1652
- }
1653
- return { type, params };
1654
- } catch {
1655
- return { type: "unknown", params: {} };
1656
- }
1657
- },
1658
- generate(type, params) {
1659
- const searchParams = new URLSearchParams(params);
1660
- return `${scheme}://${type}?${searchParams.toString()}`;
1661
- }
1662
- };
1663
- }
1664
- function parseQRCode(data) {
1665
- if (/^0x[a-fA-F0-9]{40}$/.test(data)) {
1666
- return {
1667
- type: "address",
1668
- data,
1669
- parsed: { address: data }
1670
- };
1671
- }
1672
- if (data.startsWith("ethereum:")) {
1673
- const match = data.match(/^ethereum:(0x[a-fA-F0-9]{40})(?:@(\d+))?(?:\?(.*))?$/);
1674
- if (match) {
1675
- const [, address, chainId, queryString] = match;
1676
- const params = new URLSearchParams(queryString || "");
1677
- return {
1678
- type: "payment_request",
1679
- data,
1680
- parsed: {
1681
- address,
1682
- chainId: chainId ? parseInt(chainId) : void 0,
1683
- amount: params.get("value") || void 0,
1684
- token: params.get("token") || void 0,
1685
- message: params.get("message") || void 0
1686
- }
1687
- };
1688
- }
1689
- }
1690
- if (data.startsWith("wc:")) {
1691
- return {
1692
- type: "wallet_connect",
1693
- data
1694
- };
1695
- }
1696
- return { type: "unknown", data };
1697
- }
1698
- function formatCryptoAmount(amount, symbol, options = {}) {
1699
- const { maxDecimals = 6, showSymbol = true, compact = false } = options;
1700
- const num = typeof amount === "string" ? parseFloat(amount) : amount;
1701
- if (isNaN(num)) return showSymbol ? `0 ${symbol}` : "0";
1702
- let formatted;
1703
- if (compact && num >= 1e6) {
1704
- formatted = (num / 1e6).toFixed(2) + "M";
1705
- } else if (compact && num >= 1e3) {
1706
- formatted = (num / 1e3).toFixed(2) + "K";
1707
- } else if (num < 1e-6 && num > 0) {
1708
- formatted = "<0.000001";
1709
- } else {
1710
- const decimals = num < 1 ? maxDecimals : Math.min(maxDecimals, 4);
1711
- formatted = num.toFixed(decimals).replace(/\.?0+$/, "");
1712
- }
1713
- return showSymbol ? `${formatted} ${symbol}` : formatted;
1714
- }
1715
- function generateShareContent(params) {
1716
- const { type, address, amount, token, txHash, chainId } = params;
1717
- switch (type) {
1718
- case "receive":
1719
- return {
1720
- title: "My Wallet Address",
1721
- message: `Send ${token || "crypto"} to my wallet:
1722
- ${address}`,
1723
- url: address ? `ethereum:${address}${chainId ? `@${chainId}` : ""}` : void 0
1724
- };
1725
- case "payment_request":
1726
- return {
1727
- title: "Payment Request",
1728
- message: `Please send ${amount} ${token} to:
1729
- ${address}`,
1730
- url: `ethereum:${address}${chainId ? `@${chainId}` : ""}?value=${amount}${token ? `&token=${token}` : ""}`
1731
- };
1732
- case "transaction":
1733
- return {
1734
- title: "Transaction Sent",
1735
- message: `Transaction confirmed!
1736
- Hash: ${txHash}`,
1737
- url: txHash ? getExplorerUrl(chainId || 1, txHash, "tx") : void 0
1738
- };
1739
- default:
1740
- return { title: "", message: "" };
1741
- }
1742
- }
1743
- function getExplorerUrl(chainId, hash, type = "tx") {
1744
- const explorers = {
1745
- 1: "https://etherscan.io",
1746
- 137: "https://polygonscan.com",
1747
- 42161: "https://arbiscan.io",
1748
- 10: "https://optimistic.etherscan.io",
1749
- 8453: "https://basescan.org",
1750
- 56: "https://bscscan.com",
1751
- 43114: "https://snowtrace.io"
1752
- };
1753
- const baseUrl = explorers[chainId] || explorers[1];
1754
- return `${baseUrl}/${type}/${hash}`;
1755
- }
1756
-
1757
- exports.CHAIN_CONFIGS = CHAIN_CONFIGS;
1758
- exports.COINGECKO_IDS = COINGECKO_IDS;
1759
- exports.OneEngineClient = OneEngineClient;
1760
- exports.OneSDKError = OneSDKError;
1761
- exports.PriceService = PriceService;
1762
- exports.TOKEN_NAMES = TOKEN_NAMES;
1763
- exports.capitalize = capitalize;
1764
- exports.checksumAddress = checksumAddress;
1765
- exports.createCachedEngineClient = createCachedEngineClient;
1766
- exports.createDeepLinkHandler = createDeepLinkHandler;
1767
- exports.createOneEngineClient = createOneEngineClient;
1768
- exports.formatCryptoAmount = formatCryptoAmount;
1769
- exports.formatDate = formatDate;
1770
- exports.formatDateTime = formatDateTime;
1771
- exports.formatNumber = formatNumber;
1772
- exports.formatPercent = formatPercent;
1773
- exports.formatRelativeTime = formatRelativeTime;
1774
- exports.formatTokenAmount = formatTokenAmount;
1775
- exports.formatUSD = formatUSD;
1776
- exports.generateShareContent = generateShareContent;
1777
- exports.getConfig = getConfig;
1778
- exports.getExplorerUrl = getExplorerUrl;
1779
- exports.initOneSDK = initOneSDK;
1780
- exports.isOneSDKError = isOneSDKError;
1781
- exports.isValidAddress = isValidAddress;
1782
- exports.isValidEmail = isValidEmail;
1783
- exports.isValidPhone = isValidPhone;
1784
- exports.omit = omit;
1785
- exports.parseQRCode = parseQRCode;
1786
- exports.pick = pick;
1787
- exports.priceService = priceService;
1788
- exports.retry = retry;
1789
- exports.shortenAddress = shortenAddress;
1790
- exports.sleep = sleep;
1791
- exports.slugify = slugify;
1792
- exports.truncate = truncate;
1793
- //# sourceMappingURL=react-native.js.map
1794
- //# sourceMappingURL=react-native.js.map