@one_deploy/sdk 1.0.3 → 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 (69) 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/hooks/index.ts +20 -0
  10. package/src/hooks/useAITrading.ts +444 -0
  11. package/src/index.ts +20 -0
  12. package/src/react-native.ts +23 -0
  13. package/src/services/engine.ts +184 -0
  14. package/src/services/index.ts +16 -0
  15. package/src/services/usage.ts +249 -0
  16. package/.turbo/turbo-build.log +0 -0
  17. package/.turbo/turbo-type-check.log +0 -0
  18. package/dist/config/index.d.mts +0 -74
  19. package/dist/config/index.d.ts +0 -74
  20. package/dist/config/index.js +0 -244
  21. package/dist/config/index.js.map +0 -1
  22. package/dist/config/index.mjs +0 -226
  23. package/dist/config/index.mjs.map +0 -1
  24. package/dist/engine-5ndtBaCr.d.ts +0 -1039
  25. package/dist/engine-CrlhH0nw.d.mts +0 -1039
  26. package/dist/hooks/index.d.mts +0 -56
  27. package/dist/hooks/index.d.ts +0 -56
  28. package/dist/hooks/index.js +0 -1360
  29. package/dist/hooks/index.js.map +0 -1
  30. package/dist/hooks/index.mjs +0 -1356
  31. package/dist/hooks/index.mjs.map +0 -1
  32. package/dist/index.d.mts +0 -356
  33. package/dist/index.d.ts +0 -356
  34. package/dist/index.js +0 -5069
  35. package/dist/index.js.map +0 -1
  36. package/dist/index.mjs +0 -4950
  37. package/dist/index.mjs.map +0 -1
  38. package/dist/price-CgqXPnT3.d.ts +0 -13
  39. package/dist/price-ClbLHHjv.d.mts +0 -13
  40. package/dist/providers/index.d.mts +0 -121
  41. package/dist/providers/index.d.ts +0 -121
  42. package/dist/providers/index.js +0 -1643
  43. package/dist/providers/index.js.map +0 -1
  44. package/dist/providers/index.mjs +0 -1601
  45. package/dist/providers/index.mjs.map +0 -1
  46. package/dist/react-native.d.mts +0 -120
  47. package/dist/react-native.d.ts +0 -120
  48. package/dist/react-native.js +0 -1794
  49. package/dist/react-native.js.map +0 -1
  50. package/dist/react-native.mjs +0 -1757
  51. package/dist/react-native.mjs.map +0 -1
  52. package/dist/services/index.d.mts +0 -85
  53. package/dist/services/index.d.ts +0 -85
  54. package/dist/services/index.js +0 -1466
  55. package/dist/services/index.js.map +0 -1
  56. package/dist/services/index.mjs +0 -1458
  57. package/dist/services/index.mjs.map +0 -1
  58. package/dist/types/index.d.mts +0 -759
  59. package/dist/types/index.d.ts +0 -759
  60. package/dist/types/index.js +0 -4
  61. package/dist/types/index.js.map +0 -1
  62. package/dist/types/index.mjs +0 -3
  63. package/dist/types/index.mjs.map +0 -1
  64. package/dist/utils/index.d.mts +0 -36
  65. package/dist/utils/index.d.ts +0 -36
  66. package/dist/utils/index.js +0 -164
  67. package/dist/utils/index.js.map +0 -1
  68. package/dist/utils/index.mjs +0 -142
  69. package/dist/utils/index.mjs.map +0 -1
package/dist/index.mjs DELETED
@@ -1,4950 +0,0 @@
1
- import { createClient } from '@supabase/supabase-js';
2
- import React2, { createContext, useMemo, useState, useCallback, useEffect, useContext, useRef } from 'react';
3
- import { jsx, jsxs } from 'react/jsx-runtime';
4
- import { createThirdwebClient, prepareTransaction, toWei } from 'thirdweb';
5
- import { ThirdwebProvider, ConnectButton, PayEmbed, TransactionButton, useActiveAccount, useSendTransaction, useWalletBalance, MediaRenderer } from 'thirdweb/react';
6
- import { inAppWallet, smartWallet } from 'thirdweb/wallets';
7
- export { inAppWallet, smartWallet } from 'thirdweb/wallets';
8
- import { arbitrum, polygon, ethereum, base, optimism, bsc, avalanche } from 'thirdweb/chains';
9
- export { arbitrum, base, ethereum, optimism, polygon } from 'thirdweb/chains';
10
-
11
- // src/config/index.ts
12
- var DEFAULT_ENGINE_URL = "https://api.one23.io";
13
- var DEFAULT_CLIENT_ID = "one_pk_e8f647bfa643fdcfaa3a23f760488e49be09f929296eed4a6c399d437d907f60";
14
- var config = null;
15
- function initOneSDK(options) {
16
- const engineUrl = options.oneEngineUrl || DEFAULT_ENGINE_URL;
17
- const clientId = options.oneClientId || DEFAULT_CLIENT_ID;
18
- config = {
19
- ...options,
20
- oneEngineUrl: engineUrl,
21
- oneClientId: clientId
22
- };
23
- }
24
- function getConfig() {
25
- if (!config) {
26
- throw new Error("ONE SDK not initialized. Call initOneSDK() first.");
27
- }
28
- return config;
29
- }
30
- function isInitialized() {
31
- return config !== null;
32
- }
33
- function getEngineUrl() {
34
- return config?.oneEngineUrl || process.env.NEXT_PUBLIC_ONE_ENGINE_URL || DEFAULT_ENGINE_URL;
35
- }
36
- var chainsCache = null;
37
- var chainsCacheTimestamp = 0;
38
- var CACHE_TTL = 5 * 60 * 1e3;
39
- async function fetchChains(options) {
40
- const engineUrl = getEngineUrl();
41
- const params = new URLSearchParams();
42
- if (options?.category) params.set("category", options.category);
43
- if (options?.smartWallet) params.set("smartWallet", "true");
44
- if (options?.limit) params.set("limit", options.limit.toString());
45
- const response = await fetch(`${engineUrl}/v1/chains?${params}`);
46
- const data = await response.json();
47
- if (!data.success) {
48
- throw new Error(data.error?.message || "Failed to fetch chains");
49
- }
50
- return data.data.chains.map((chain) => ({
51
- id: chain.id,
52
- name: chain.name,
53
- shortName: chain.shortName || chain.slug || chain.name.toLowerCase(),
54
- icon: getChainIcon(chain.id),
55
- nativeCurrency: chain.nativeCurrency,
56
- rpcUrls: Array.isArray(chain.rpc) ? chain.rpc : [chain.rpc],
57
- blockExplorerUrls: chain.blockExplorer ? [chain.blockExplorer] : [],
58
- testnet: chain.testnet
59
- }));
60
- }
61
- async function getChains() {
62
- const now = Date.now();
63
- if (chainsCache && now - chainsCacheTimestamp < CACHE_TTL) {
64
- return chainsCache;
65
- }
66
- chainsCache = await fetchChains({ limit: 200 });
67
- chainsCacheTimestamp = now;
68
- return chainsCache;
69
- }
70
- async function getChainById(chainId) {
71
- const chains = await getChains();
72
- return chains.find((c) => c.id === chainId);
73
- }
74
- async function getChainByName(name) {
75
- const chains = await getChains();
76
- const lowerName = name.toLowerCase();
77
- return chains.find(
78
- (c) => c.name.toLowerCase() === lowerName || c.shortName.toLowerCase() === lowerName
79
- );
80
- }
81
- async function getRecommendedChains() {
82
- return fetchChains({ category: "recommended", limit: 10 });
83
- }
84
- async function getSmartWalletChains() {
85
- return fetchChains({ smartWallet: true, limit: 50 });
86
- }
87
- var CHAIN_IDS = {
88
- ETHEREUM: 1,
89
- POLYGON: 137,
90
- BSC: 56,
91
- ARBITRUM: 42161,
92
- OPTIMISM: 10,
93
- BASE: 8453,
94
- AVALANCHE: 43114,
95
- ZKSYNC: 324,
96
- LINEA: 59144,
97
- SCROLL: 534352,
98
- BLAST: 81457,
99
- // Testnets
100
- SEPOLIA: 11155111,
101
- BASE_SEPOLIA: 84532,
102
- ARBITRUM_SEPOLIA: 421614
103
- };
104
- var DEFAULT_CHAIN_ID = CHAIN_IDS.BASE;
105
- var CHAIN_ICONS = {
106
- 1: "\u229F",
107
- // Ethereum
108
- 137: "\u{1F7E3}",
109
- // Polygon
110
- 56: "\u{1F7E1}",
111
- // BSC
112
- 42161: "\u{1F535}",
113
- // Arbitrum
114
- 10: "\u{1F534}",
115
- // Optimism
116
- 8453: "\u{1F537}",
117
- // Base
118
- 43114: "\u{1F53A}",
119
- // Avalanche
120
- 324: "\u26A1",
121
- // zkSync
122
- 59144: "\u{1F539}",
123
- // Linea
124
- 534352: "\u{1F4DC}"
125
- // Scroll
126
- };
127
- function getChainIcon(chainId) {
128
- return CHAIN_ICONS[chainId] || "\u{1F517}";
129
- }
130
- var TOKEN_NAMES = {
131
- ETH: "Ethereum",
132
- BTC: "Bitcoin",
133
- BNB: "BNB",
134
- MATIC: "Polygon",
135
- POL: "Polygon",
136
- AVAX: "Avalanche",
137
- USDT: "Tether",
138
- USDC: "USD Coin",
139
- DAI: "Dai",
140
- WBTC: "Wrapped Bitcoin",
141
- WETH: "Wrapped Ether",
142
- ARB: "Arbitrum",
143
- OP: "Optimism",
144
- LINK: "Chainlink",
145
- UNI: "Uniswap",
146
- AAVE: "Aave",
147
- CRV: "Curve",
148
- MKR: "Maker",
149
- SNX: "Synthetix",
150
- COMP: "Compound",
151
- SUSHI: "SushiSwap",
152
- YFI: "Yearn Finance",
153
- SOL: "Solana",
154
- DOT: "Polkadot",
155
- ATOM: "Cosmos",
156
- NEAR: "Near Protocol"
157
- };
158
- var COINGECKO_IDS = {
159
- ETH: "ethereum",
160
- BTC: "bitcoin",
161
- BNB: "binancecoin",
162
- MATIC: "matic-network",
163
- POL: "matic-network",
164
- AVAX: "avalanche-2",
165
- USDT: "tether",
166
- USDC: "usd-coin",
167
- DAI: "dai",
168
- WBTC: "wrapped-bitcoin",
169
- WETH: "weth",
170
- ARB: "arbitrum",
171
- OP: "optimism",
172
- LINK: "chainlink",
173
- UNI: "uniswap",
174
- AAVE: "aave",
175
- SOL: "solana"
176
- };
177
- var CHAIN_CONFIGS = {
178
- ethereum: {
179
- id: 1,
180
- name: "Ethereum",
181
- shortName: "ETH",
182
- icon: "\u229F",
183
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
184
- rpcUrls: ["https://ethereum.rpc.thirdweb.com"],
185
- blockExplorerUrls: ["https://etherscan.io"],
186
- testnet: false
187
- },
188
- polygon: {
189
- id: 137,
190
- name: "Polygon",
191
- shortName: "MATIC",
192
- icon: "\u{1F7E3}",
193
- nativeCurrency: { name: "POL", symbol: "POL", decimals: 18 },
194
- rpcUrls: ["https://polygon.rpc.thirdweb.com"],
195
- blockExplorerUrls: ["https://polygonscan.com"],
196
- testnet: false
197
- },
198
- base: {
199
- id: 8453,
200
- name: "Base",
201
- shortName: "BASE",
202
- icon: "\u{1F537}",
203
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
204
- rpcUrls: ["https://base.rpc.thirdweb.com"],
205
- blockExplorerUrls: ["https://basescan.org"],
206
- testnet: false
207
- },
208
- arbitrum: {
209
- id: 42161,
210
- name: "Arbitrum One",
211
- shortName: "ARB",
212
- icon: "\u{1F535}",
213
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
214
- rpcUrls: ["https://arbitrum.rpc.thirdweb.com"],
215
- blockExplorerUrls: ["https://arbiscan.io"],
216
- testnet: false
217
- },
218
- optimism: {
219
- id: 10,
220
- name: "Optimism",
221
- shortName: "OP",
222
- icon: "\u{1F534}",
223
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
224
- rpcUrls: ["https://optimism.rpc.thirdweb.com"],
225
- blockExplorerUrls: ["https://optimistic.etherscan.io"],
226
- testnet: false
227
- }
228
- };
229
- var SUPPORTED_CHAINS = Object.keys(CHAIN_CONFIGS);
230
- function getChainConfig(chain) {
231
- return CHAIN_CONFIGS[chain.toLowerCase()];
232
- }
233
-
234
- // src/services/engine.ts
235
- var OneEngineClient = class {
236
- constructor(options) {
237
- const config2 = getConfig();
238
- this.baseUrl = options?.baseUrl || config2.oneEngineUrl;
239
- this.clientId = options?.clientId || config2.oneClientId || "";
240
- this.secretKey = options?.secretKey || config2.oneSecretKey;
241
- }
242
- /**
243
- * Set access token for authenticated requests
244
- */
245
- setAccessToken(token) {
246
- this.accessToken = token;
247
- }
248
- /**
249
- * Clear access token
250
- */
251
- clearAccessToken() {
252
- this.accessToken = void 0;
253
- }
254
- getHeaders(includeSecret = false) {
255
- const headers = {
256
- "Content-Type": "application/json",
257
- "x-client-id": this.clientId
258
- };
259
- if (this.accessToken) {
260
- headers["Authorization"] = `Bearer ${this.accessToken}`;
261
- }
262
- if (includeSecret && this.secretKey) {
263
- headers["x-secret-key"] = this.secretKey;
264
- }
265
- return headers;
266
- }
267
- async request(endpoint, options = {}, includeSecret = false) {
268
- try {
269
- const response = await fetch(`${this.baseUrl}${endpoint}`, {
270
- ...options,
271
- headers: {
272
- ...this.getHeaders(includeSecret),
273
- ...options.headers
274
- }
275
- });
276
- const data = await response.json();
277
- if (!response.ok) {
278
- return {
279
- success: false,
280
- error: {
281
- code: data.error?.code || `HTTP_${response.status}`,
282
- message: data.error?.message || "Request failed"
283
- }
284
- };
285
- }
286
- return {
287
- success: true,
288
- data: data.data || data
289
- };
290
- } catch (error) {
291
- return {
292
- success: false,
293
- error: {
294
- code: "NETWORK_ERROR",
295
- message: error instanceof Error ? error.message : "Network request failed"
296
- }
297
- };
298
- }
299
- }
300
- // ===============================
301
- // AUTH ENDPOINTS
302
- // ===============================
303
- /**
304
- * Send OTP to email for authentication
305
- */
306
- async sendEmailOtp(email) {
307
- return this.request("/api/v1/auth/otp", {
308
- method: "POST",
309
- body: JSON.stringify({ email })
310
- });
311
- }
312
- /**
313
- * Verify OTP and get access token
314
- */
315
- async verifyEmailOtp(email, otp) {
316
- return this.request("/api/v1/auth/otp/verify", {
317
- method: "POST",
318
- body: JSON.stringify({ email, otp })
319
- });
320
- }
321
- /**
322
- * Authenticate with wallet signature
323
- */
324
- async authWithWallet(walletAddress, signature, message) {
325
- return this.request("/api/v1/auth/wallet", {
326
- method: "POST",
327
- body: JSON.stringify({ walletAddress, signature, message })
328
- });
329
- }
330
- /**
331
- * Refresh access token
332
- */
333
- async refreshToken(refreshToken) {
334
- return this.request("/api/v1/auth/refresh", {
335
- method: "POST",
336
- body: JSON.stringify({ refreshToken })
337
- });
338
- }
339
- /**
340
- * Get current user
341
- */
342
- async getCurrentUser() {
343
- return this.request("/api/v1/auth/me", { method: "GET" });
344
- }
345
- /**
346
- * Sign out
347
- */
348
- async signOut() {
349
- return this.request("/api/v1/auth/logout", { method: "POST" });
350
- }
351
- // ===============================
352
- // WALLET/ASSETS ENDPOINTS
353
- // ===============================
354
- /**
355
- * Get wallet balance across all chains
356
- */
357
- async getWalletBalance(walletAddress, chains) {
358
- const params = new URLSearchParams({ address: walletAddress });
359
- if (chains?.length && chains.length > 0) {
360
- params.set("chainId", chains[0].toString());
361
- }
362
- return this.request(`/api/v1/assets?${params}`, { method: "GET" });
363
- }
364
- /**
365
- * Get portfolio summary
366
- */
367
- async getPortfolioSummary(walletAddress) {
368
- const params = new URLSearchParams({ address: walletAddress });
369
- return this.request(`/api/v1/assets/portfolio?${params}`, { method: "GET" });
370
- }
371
- /**
372
- * Get user's wallets
373
- */
374
- async getUserWallets(chainId) {
375
- const params = chainId ? `?chainId=${chainId}` : "";
376
- return this.request(`/api/v1/wallet${params}`, { method: "GET" });
377
- }
378
- /**
379
- * Create a new wallet
380
- */
381
- async createWallet(chainId = 8453, type = "smart") {
382
- return this.request("/api/v1/wallet", {
383
- method: "POST",
384
- body: JSON.stringify({ chainId, type })
385
- });
386
- }
387
- /**
388
- * Get wallet transactions (placeholder - needs endpoint)
389
- */
390
- async getWalletTransactions(walletAddress, options) {
391
- const params = new URLSearchParams({ address: walletAddress });
392
- if (options?.limit) params.set("limit", options.limit.toString());
393
- if (options?.offset) params.set("offset", options.offset.toString());
394
- if (options?.chainId) params.set("chainId", options.chainId.toString());
395
- return this.request(`/api/v1/assets/transactions?${params}`, { method: "GET" });
396
- }
397
- /**
398
- * Send native token or ERC20
399
- */
400
- async sendTransaction(request) {
401
- return this.request("/api/v1/wallet/send", {
402
- method: "POST",
403
- body: JSON.stringify(request)
404
- });
405
- }
406
- /**
407
- * Get transaction status
408
- */
409
- async getTransactionStatus(txId) {
410
- return this.request(`/api/v1/wallet/transaction/${txId}`, { method: "GET" });
411
- }
412
- // ===============================
413
- // ONRAMP ENDPOINTS (Fiat-to-Crypto)
414
- // ===============================
415
- /**
416
- * Get onramp quote
417
- */
418
- async getOnrampQuote(fiatCurrency, fiatAmount, cryptoCurrency, paymentMethod) {
419
- const params = new URLSearchParams({
420
- fiatCurrency,
421
- fiatAmount: fiatAmount.toString(),
422
- cryptoCurrency
423
- });
424
- if (paymentMethod) params.set("paymentMethod", paymentMethod);
425
- return this.request(`/api/v1/fiat/onramp/quote?${params}`, { method: "GET" });
426
- }
427
- /**
428
- * Create onramp session (returns widget URL)
429
- */
430
- async createOnrampSession(request) {
431
- return this.request("/api/v1/fiat/onramp", {
432
- method: "POST",
433
- body: JSON.stringify({
434
- fiatCurrency: request.fiatCurrency || "USD",
435
- fiatAmount: request.fiatAmount || 100,
436
- cryptoCurrency: request.cryptoCurrency || "ETH",
437
- walletAddress: request.walletAddress,
438
- chainId: 8453
439
- // Default to Base
440
- })
441
- });
442
- }
443
- /**
444
- * Get onramp session status
445
- */
446
- async getOnrampStatus(sessionId) {
447
- return this.request(`/api/v1/fiat/onramp/${sessionId}`, { method: "GET" });
448
- }
449
- /**
450
- * Get supported currencies (fiat + crypto)
451
- */
452
- async getSupportedCurrencies() {
453
- return this.request("/api/v1/fiat/onramp", { method: "GET" });
454
- }
455
- /**
456
- * Get supported fiat currencies
457
- */
458
- async getSupportedFiatCurrencies() {
459
- const result = await this.getSupportedCurrencies();
460
- if (result.success && result.data) {
461
- return { success: true, data: result.data.fiatCurrencies };
462
- }
463
- return { success: false, error: result.error };
464
- }
465
- /**
466
- * Get supported payment methods
467
- */
468
- async getSupportedPaymentMethods(country) {
469
- return { success: true, data: ["card", "bank_transfer", "apple_pay", "google_pay"] };
470
- }
471
- // ===============================
472
- // SWAP ENDPOINTS
473
- // ===============================
474
- /**
475
- * Get swap quote
476
- */
477
- async getSwapQuote(request) {
478
- return this.request("/api/v1/swap/quote", {
479
- method: "POST",
480
- body: JSON.stringify(request)
481
- });
482
- }
483
- /**
484
- * Execute swap
485
- */
486
- async executeSwap(request) {
487
- return this.request("/api/v1/swap/execute", {
488
- method: "POST",
489
- body: JSON.stringify(request)
490
- });
491
- }
492
- /**
493
- * Get swap status
494
- */
495
- async getSwapStatus(swapId) {
496
- return this.request(`/api/v1/swap/${swapId}`, { method: "GET" });
497
- }
498
- /**
499
- * Get supported tokens for swap
500
- */
501
- async getSupportedSwapTokens(chainId) {
502
- const params = chainId ? `?chainId=${chainId}` : "";
503
- return this.request(`/api/v1/swap/tokens${params}`, { method: "GET" });
504
- }
505
- /**
506
- * Get supported chains for swap
507
- */
508
- async getSupportedSwapChains() {
509
- return this.request("/api/v1/swap/chains", { method: "GET" });
510
- }
511
- // ===============================
512
- // AI TRADING/QUANT ENDPOINTS
513
- // ===============================
514
- /**
515
- * Get available AI trading strategies
516
- */
517
- async getStrategies() {
518
- return this.request("/api/v1/quant/strategies", { method: "GET" });
519
- }
520
- /**
521
- * Get strategy details
522
- */
523
- async getStrategy(strategyId) {
524
- return this.request(`/api/v1/quant/strategies/${strategyId}`, { method: "GET" });
525
- }
526
- /**
527
- * Get user's positions
528
- */
529
- async getPositions() {
530
- return this.request("/api/v1/quant/positions", { method: "GET" });
531
- }
532
- /**
533
- * Create investment order
534
- */
535
- async createOrder(strategyId, amount, currency) {
536
- return this.request("/api/v1/trading/orders", {
537
- method: "POST",
538
- body: JSON.stringify({ strategyId, amount, currency })
539
- });
540
- }
541
- /**
542
- * Get user's orders
543
- */
544
- async getUserOrders() {
545
- return this.request("/api/v1/trading/orders", { method: "GET" });
546
- }
547
- /**
548
- * Get user's portfolio stats from positions
549
- */
550
- async getPortfolioStats() {
551
- const positionsResult = await this.getPositions();
552
- if (positionsResult.success && positionsResult.data) {
553
- const positions = positionsResult.data;
554
- const totalInvested = positions.reduce((sum, p) => sum + (p.investedAmount || 0), 0);
555
- const totalValue = positions.reduce((sum, p) => sum + (p.currentValue || 0), 0);
556
- const totalPnl = totalValue - totalInvested;
557
- const totalPnlPercent = totalInvested > 0 ? totalPnl / totalInvested * 100 : 0;
558
- return {
559
- success: true,
560
- data: {
561
- totalInvested,
562
- totalValue,
563
- totalPnl,
564
- totalPnlPercent,
565
- activePositions: positions.filter((p) => p.status === "active").length
566
- }
567
- };
568
- }
569
- return {
570
- success: true,
571
- data: { totalInvested: 0, totalValue: 0, totalPnl: 0, totalPnlPercent: 0, activePositions: 0 }
572
- };
573
- }
574
- // ===============================
575
- // MARKET/PRICE ENDPOINTS
576
- // ===============================
577
- /**
578
- * Get token prices
579
- */
580
- async getTokenPrices(symbols) {
581
- const bybitSymbols = symbols.map((s) => {
582
- const upper = s.toUpperCase();
583
- if (upper.endsWith("USDT")) return upper;
584
- return `${upper}USDT`;
585
- });
586
- const result = await this.request(
587
- `/api/v1/trading/market?symbols=${bybitSymbols.join(",")}`,
588
- { method: "GET" }
589
- );
590
- if (result.success && result.data?.markets) {
591
- const prices = {};
592
- for (const market of result.data.markets) {
593
- const symbol = market.symbol?.replace("USDT", "") || "";
594
- prices[symbol] = {
595
- price: parseFloat(market.lastPrice) || 0,
596
- change24h: parseFloat(market.price24hPcnt) * 100 || 0,
597
- marketCap: void 0
598
- // Bybit doesn't provide this
599
- };
600
- }
601
- return { success: true, data: prices };
602
- }
603
- return { success: false, error: result.error };
604
- }
605
- /**
606
- * Get market data overview
607
- */
608
- async getMarketData() {
609
- const result = await this.request("/api/v1/trading/market", { method: "GET" });
610
- if (result.success && result.data?.markets) {
611
- return {
612
- success: true,
613
- data: {
614
- totalMarketCap: 0,
615
- // Would need separate API
616
- totalVolume24h: result.data.markets.reduce((sum, m) => sum + (parseFloat(m.volume24h) || 0), 0),
617
- btcDominance: 0,
618
- // Would need separate API
619
- markets: result.data.markets
620
- }
621
- };
622
- }
623
- return { success: false, error: result.error };
624
- }
625
- // ===============================
626
- // NFT ENDPOINTS
627
- // ===============================
628
- /**
629
- * Get user's NFTs
630
- */
631
- async getUserNFTs(walletAddress, options) {
632
- const params = new URLSearchParams({ address: walletAddress });
633
- if (options?.chainId) params.set("chainId", options.chainId.toString());
634
- if (options?.limit) params.set("limit", options.limit.toString());
635
- if (options?.offset) params.set("offset", options.offset.toString());
636
- return this.request(`/api/v1/assets/nfts?${params}`, { method: "GET" });
637
- }
638
- /**
639
- * Get NFT details
640
- */
641
- async getNFTDetails(contractAddress, tokenId, chainId) {
642
- return this.request(`/api/v1/assets/nfts/${contractAddress}/${tokenId}?chainId=${chainId}`, { method: "GET" });
643
- }
644
- /**
645
- * Get NFT collection
646
- */
647
- async getNFTCollection(contractAddress, chainId) {
648
- return this.request(`/api/v1/assets/nfts/collection/${contractAddress}?chainId=${chainId}`, { method: "GET" });
649
- }
650
- /**
651
- * Transfer NFT
652
- */
653
- async transferNFT(params) {
654
- return this.request("/api/v1/assets/nfts/transfer", {
655
- method: "POST",
656
- body: JSON.stringify(params)
657
- });
658
- }
659
- // ===============================
660
- // CONTRACT ENDPOINTS
661
- // ===============================
662
- /**
663
- * Get user's contracts
664
- */
665
- async getUserContracts(options) {
666
- const params = new URLSearchParams();
667
- if (options?.chainId) params.set("chainId", options.chainId.toString());
668
- if (options?.limit) params.set("limit", options.limit.toString());
669
- if (options?.offset) params.set("offset", options.offset.toString());
670
- return this.request(`/api/v1/contracts?${params}`, { method: "GET" });
671
- }
672
- /**
673
- * Get contract details
674
- */
675
- async getContractDetails(address, chainId) {
676
- return this.request(`/api/v1/contracts/${address}?chainId=${chainId}`, { method: "GET" });
677
- }
678
- /**
679
- * Read contract (call view function)
680
- */
681
- async readContract(params) {
682
- return this.request("/api/v1/contracts/read", {
683
- method: "POST",
684
- body: JSON.stringify(params)
685
- });
686
- }
687
- /**
688
- * Write to contract (execute transaction)
689
- */
690
- async writeContract(params) {
691
- return this.request("/api/v1/contracts/write", {
692
- method: "POST",
693
- body: JSON.stringify(params)
694
- });
695
- }
696
- /**
697
- * Deploy contract
698
- */
699
- async deployContract(params) {
700
- return this.request("/api/v1/contracts/deploy", {
701
- method: "POST",
702
- body: JSON.stringify(params)
703
- });
704
- }
705
- // ===============================
706
- // OFFRAMP ENDPOINTS (Crypto-to-Fiat)
707
- // ===============================
708
- /**
709
- * Get offramp quote
710
- */
711
- async getOfframpQuote(cryptoCurrency, cryptoAmount, fiatCurrency, payoutMethod) {
712
- const params = new URLSearchParams({
713
- cryptoCurrency,
714
- cryptoAmount: cryptoAmount.toString(),
715
- fiatCurrency
716
- });
717
- if (payoutMethod) params.set("payoutMethod", payoutMethod);
718
- return this.request(`/api/v1/fiat/offramp/quote?${params}`, { method: "GET" });
719
- }
720
- /**
721
- * Create offramp transaction
722
- */
723
- async createOfframpTransaction(request) {
724
- return this.request("/api/v1/fiat/offramp", {
725
- method: "POST",
726
- body: JSON.stringify(request)
727
- });
728
- }
729
- /**
730
- * Get offramp transaction status
731
- */
732
- async getOfframpStatus(transactionId) {
733
- return this.request(`/api/v1/fiat/offramp/${transactionId}`, { method: "GET" });
734
- }
735
- /**
736
- * Get supported payout methods
737
- */
738
- async getSupportedPayoutMethods(country) {
739
- const params = country ? `?country=${country}` : "";
740
- return this.request(`/api/v1/fiat/offramp/methods${params}`, { method: "GET" });
741
- }
742
- // ===============================
743
- // BILL PAYMENT ENDPOINTS
744
- // ===============================
745
- /**
746
- * Get bill providers
747
- */
748
- async getBillProviders(country, category) {
749
- const params = new URLSearchParams();
750
- if (country) params.set("country", country);
751
- if (category) params.set("category", category);
752
- return this.request(`/api/v1/bills/providers?${params}`, { method: "GET" });
753
- }
754
- /**
755
- * Get bill details/validate account
756
- */
757
- async validateBillAccount(providerId, accountNumber) {
758
- return this.request("/api/v1/bills/validate", {
759
- method: "POST",
760
- body: JSON.stringify({ providerId, accountNumber })
761
- });
762
- }
763
- /**
764
- * Pay bill
765
- */
766
- async payBill(params) {
767
- return this.request("/api/v1/bills/pay", {
768
- method: "POST",
769
- body: JSON.stringify(params)
770
- });
771
- }
772
- /**
773
- * Get bill payment history
774
- */
775
- async getBillHistory(options) {
776
- const params = new URLSearchParams();
777
- if (options?.limit) params.set("limit", options.limit.toString());
778
- if (options?.offset) params.set("offset", options.offset.toString());
779
- return this.request(`/api/v1/bills/history?${params}`, { method: "GET" });
780
- }
781
- // ===============================
782
- // STAKING ENDPOINTS
783
- // ===============================
784
- /**
785
- * Get staking pools
786
- */
787
- async getStakingPools(chainId) {
788
- const params = chainId ? `?chainId=${chainId}` : "";
789
- return this.request(`/api/v1/staking/pools${params}`, { method: "GET" });
790
- }
791
- /**
792
- * Get user's staking positions
793
- */
794
- async getStakingPositions() {
795
- return this.request("/api/v1/staking/positions", { method: "GET" });
796
- }
797
- /**
798
- * Stake tokens
799
- */
800
- async stake(params) {
801
- return this.request("/api/v1/staking/stake", {
802
- method: "POST",
803
- body: JSON.stringify(params)
804
- });
805
- }
806
- /**
807
- * Unstake tokens
808
- */
809
- async unstake(params) {
810
- return this.request("/api/v1/staking/unstake", {
811
- method: "POST",
812
- body: JSON.stringify(params)
813
- });
814
- }
815
- /**
816
- * Claim staking rewards
817
- */
818
- async claimStakingRewards(positionId) {
819
- return this.request("/api/v1/staking/claim", {
820
- method: "POST",
821
- body: JSON.stringify({ positionId })
822
- });
823
- }
824
- // ===============================
825
- // USER PROFILE ENDPOINTS
826
- // ===============================
827
- /**
828
- * Get user profile
829
- */
830
- async getUserProfile() {
831
- return this.request("/api/v1/user/profile", { method: "GET" });
832
- }
833
- /**
834
- * Update user profile
835
- */
836
- async updateUserProfile(updates) {
837
- return this.request("/api/v1/user/profile", {
838
- method: "PATCH",
839
- body: JSON.stringify(updates)
840
- });
841
- }
842
- /**
843
- * Get user settings
844
- */
845
- async getUserSettings() {
846
- return this.request("/api/v1/user/settings", { method: "GET" });
847
- }
848
- /**
849
- * Update user settings
850
- */
851
- async updateUserSettings(updates) {
852
- return this.request("/api/v1/user/settings", {
853
- method: "PATCH",
854
- body: JSON.stringify(updates)
855
- });
856
- }
857
- // ===============================
858
- // NOTIFICATION ENDPOINTS
859
- // ===============================
860
- /**
861
- * Get notifications
862
- */
863
- async getNotifications(options) {
864
- const params = new URLSearchParams();
865
- if (options?.unreadOnly) params.set("unreadOnly", "true");
866
- if (options?.limit) params.set("limit", options.limit.toString());
867
- if (options?.offset) params.set("offset", options.offset.toString());
868
- return this.request(`/api/v1/notifications?${params}`, { method: "GET" });
869
- }
870
- /**
871
- * Mark notification as read
872
- */
873
- async markNotificationRead(notificationId) {
874
- return this.request(`/api/v1/notifications/${notificationId}/read`, { method: "POST" });
875
- }
876
- /**
877
- * Mark all notifications as read
878
- */
879
- async markAllNotificationsRead() {
880
- return this.request("/api/v1/notifications/read-all", { method: "POST" });
881
- }
882
- // ===============================
883
- // REFERRAL ENDPOINTS
884
- // ===============================
885
- /**
886
- * Get referral info
887
- */
888
- async getReferralInfo() {
889
- return this.request("/api/v1/referral", { method: "GET" });
890
- }
891
- /**
892
- * Get referred users
893
- */
894
- async getReferrals() {
895
- return this.request("/api/v1/referral/list", { method: "GET" });
896
- }
897
- /**
898
- * Apply referral code
899
- */
900
- async applyReferralCode(code) {
901
- return this.request("/api/v1/referral/apply", {
902
- method: "POST",
903
- body: JSON.stringify({ code })
904
- });
905
- }
906
- /**
907
- * Claim referral rewards
908
- */
909
- async claimReferralRewards() {
910
- return this.request("/api/v1/referral/claim", { method: "POST" });
911
- }
912
- // ===============================
913
- // KYC ENDPOINTS
914
- // ===============================
915
- /**
916
- * Get KYC status
917
- */
918
- async getKycStatus() {
919
- return this.request("/api/v1/kyc/status", { method: "GET" });
920
- }
921
- /**
922
- * Start KYC verification
923
- */
924
- async startKycVerification(level) {
925
- return this.request("/api/v1/kyc/start", {
926
- method: "POST",
927
- body: JSON.stringify({ level })
928
- });
929
- }
930
- /**
931
- * Submit KYC documents
932
- */
933
- async submitKycDocuments(params) {
934
- return this.request("/api/v1/kyc/submit", {
935
- method: "POST",
936
- body: JSON.stringify(params)
937
- });
938
- }
939
- // ===============================
940
- // BRIDGE ENDPOINTS
941
- // ===============================
942
- /**
943
- * Get bridge quote
944
- */
945
- async getBridgeQuote(params) {
946
- return this.request("/api/v1/bridge/quote", {
947
- method: "POST",
948
- body: JSON.stringify(params)
949
- });
950
- }
951
- /**
952
- * Execute bridge transaction
953
- */
954
- async executeBridge(params) {
955
- return this.request("/api/v1/bridge/execute", {
956
- method: "POST",
957
- body: JSON.stringify(params)
958
- });
959
- }
960
- /**
961
- * Get bridge transaction status
962
- */
963
- async getBridgeStatus(bridgeId) {
964
- return this.request(`/api/v1/bridge/${bridgeId}`, { method: "GET" });
965
- }
966
- /**
967
- * Get supported bridge routes
968
- */
969
- async getSupportedBridgeRoutes() {
970
- return this.request("/api/v1/bridge/routes", { method: "GET" });
971
- }
972
- // ===============================
973
- // GAS ENDPOINTS
974
- // ===============================
975
- /**
976
- * Get gas estimate for transaction
977
- */
978
- async getGasEstimate(params) {
979
- return this.request("/api/v1/gas/estimate", {
980
- method: "POST",
981
- body: JSON.stringify(params)
982
- });
983
- }
984
- /**
985
- * Get current gas prices for chain
986
- */
987
- async getGasPrice(chainId) {
988
- return this.request(`/api/v1/gas/price?chainId=${chainId}`, { method: "GET" });
989
- }
990
- // ===============================
991
- // WALLET IMPORT/EXPORT ENDPOINTS
992
- // ===============================
993
- /**
994
- * Import wallet from private key or mnemonic
995
- */
996
- async importWallet(request) {
997
- return this.request("/api/v1/wallet/import", {
998
- method: "POST",
999
- body: JSON.stringify(request)
1000
- }, true);
1001
- }
1002
- /**
1003
- * Export wallet (get encrypted private key)
1004
- * Requires additional authentication
1005
- */
1006
- async exportWallet(walletId, pin) {
1007
- return this.request("/api/v1/wallet/export", {
1008
- method: "POST",
1009
- body: JSON.stringify({ walletId, pin })
1010
- }, true);
1011
- }
1012
- /**
1013
- * Generate new mnemonic phrase
1014
- */
1015
- async generateMnemonic() {
1016
- return this.request("/api/v1/wallet/generate-mnemonic", { method: "POST" }, true);
1017
- }
1018
- /**
1019
- * Validate mnemonic phrase
1020
- */
1021
- async validateMnemonic(mnemonic) {
1022
- return this.request("/api/v1/wallet/validate-mnemonic", {
1023
- method: "POST",
1024
- body: JSON.stringify({ mnemonic })
1025
- });
1026
- }
1027
- // ===============================
1028
- // PORTFOLIO ANALYTICS ENDPOINTS
1029
- // ===============================
1030
- /**
1031
- * Get portfolio analytics with historical data
1032
- */
1033
- async getPortfolioAnalytics(walletAddress, period = "30d") {
1034
- const params = new URLSearchParams({ address: walletAddress, period });
1035
- return this.request(`/api/v1/analytics/portfolio?${params}`, { method: "GET" });
1036
- }
1037
- /**
1038
- * Get transaction analytics
1039
- */
1040
- async getTransactionAnalytics(walletAddress, period = "30d") {
1041
- const params = new URLSearchParams({ address: walletAddress, period });
1042
- return this.request(`/api/v1/analytics/transactions?${params}`, { method: "GET" });
1043
- }
1044
- // ===============================
1045
- // ADVANCED TRADING ENDPOINTS
1046
- // ===============================
1047
- /**
1048
- * Create limit order
1049
- */
1050
- async createLimitOrder(params) {
1051
- return this.request("/api/v1/trading/limit-orders", {
1052
- method: "POST",
1053
- body: JSON.stringify(params)
1054
- });
1055
- }
1056
- /**
1057
- * Get user's limit orders
1058
- */
1059
- async getLimitOrders(status) {
1060
- const params = status ? `?status=${status}` : "";
1061
- return this.request(`/api/v1/trading/limit-orders${params}`, { method: "GET" });
1062
- }
1063
- /**
1064
- * Cancel limit order
1065
- */
1066
- async cancelLimitOrder(orderId) {
1067
- return this.request(`/api/v1/trading/limit-orders/${orderId}`, { method: "DELETE" });
1068
- }
1069
- /**
1070
- * Set price alert
1071
- */
1072
- async setPriceAlert(params) {
1073
- return this.request("/api/v1/trading/alerts", {
1074
- method: "POST",
1075
- body: JSON.stringify(params)
1076
- });
1077
- }
1078
- /**
1079
- * Get price alerts
1080
- */
1081
- async getPriceAlerts() {
1082
- return this.request("/api/v1/trading/alerts", { method: "GET" });
1083
- }
1084
- /**
1085
- * Delete price alert
1086
- */
1087
- async deletePriceAlert(alertId) {
1088
- return this.request(`/api/v1/trading/alerts/${alertId}`, { method: "DELETE" });
1089
- }
1090
- // ===============================
1091
- // SESSION MANAGEMENT
1092
- // ===============================
1093
- /**
1094
- * Get active sessions
1095
- */
1096
- async getActiveSessions() {
1097
- return this.request("/api/v1/auth/sessions", { method: "GET" });
1098
- }
1099
- /**
1100
- * Revoke session
1101
- */
1102
- async revokeSession(sessionId) {
1103
- return this.request(`/api/v1/auth/sessions/${sessionId}`, { method: "DELETE" });
1104
- }
1105
- /**
1106
- * Revoke all other sessions
1107
- */
1108
- async revokeAllOtherSessions() {
1109
- return this.request("/api/v1/auth/sessions/revoke-all", { method: "POST" });
1110
- }
1111
- // ========== Webhooks ==========
1112
- /**
1113
- * List webhooks for the project
1114
- */
1115
- async listWebhooks(options) {
1116
- const params = new URLSearchParams();
1117
- if (options?.isActive !== void 0) params.set("isActive", String(options.isActive));
1118
- const query = params.toString();
1119
- return this.request(`/api/v1/webhooks${query ? `?${query}` : ""}`, { method: "GET" });
1120
- }
1121
- /**
1122
- * Get webhook by ID
1123
- */
1124
- async getWebhook(webhookId) {
1125
- return this.request(`/api/v1/webhooks/${webhookId}`, { method: "GET" });
1126
- }
1127
- /**
1128
- * Create a webhook
1129
- */
1130
- async createWebhook(input) {
1131
- return this.request("/api/v1/webhooks", {
1132
- method: "POST",
1133
- body: JSON.stringify(input)
1134
- });
1135
- }
1136
- /**
1137
- * Update a webhook
1138
- */
1139
- async updateWebhook(webhookId, input) {
1140
- return this.request(`/api/v1/webhooks/${webhookId}`, {
1141
- method: "PATCH",
1142
- body: JSON.stringify(input)
1143
- });
1144
- }
1145
- /**
1146
- * Delete a webhook
1147
- */
1148
- async deleteWebhook(webhookId) {
1149
- return this.request(`/api/v1/webhooks/${webhookId}`, { method: "DELETE" });
1150
- }
1151
- /**
1152
- * Get webhook deliveries
1153
- */
1154
- async getWebhookDeliveries(webhookId, options) {
1155
- const params = new URLSearchParams();
1156
- if (options?.status) params.set("status", options.status);
1157
- if (options?.limit) params.set("limit", String(options.limit));
1158
- if (options?.offset) params.set("offset", String(options.offset));
1159
- const query = params.toString();
1160
- return this.request(`/api/v1/webhooks/${webhookId}/deliveries${query ? `?${query}` : ""}`, { method: "GET" });
1161
- }
1162
- /**
1163
- * Test a webhook
1164
- */
1165
- async testWebhook(webhookId) {
1166
- return this.request(`/api/v1/webhooks/${webhookId}/test`, { method: "POST" });
1167
- }
1168
- // ========== Admin (requires admin role) ==========
1169
- /**
1170
- * List all users (admin only)
1171
- */
1172
- async adminListUsers(options) {
1173
- const params = new URLSearchParams();
1174
- if (options?.page) params.set("page", String(options.page));
1175
- if (options?.limit) params.set("limit", String(options.limit));
1176
- if (options?.search) params.set("search", options.search);
1177
- if (options?.sortBy) params.set("sortBy", options.sortBy);
1178
- if (options?.sortOrder) params.set("sortOrder", options.sortOrder);
1179
- if (options?.role) params.set("role", options.role);
1180
- if (options?.kycStatus) params.set("kycStatus", options.kycStatus);
1181
- if (options?.isActive !== void 0) params.set("isActive", String(options.isActive));
1182
- const query = params.toString();
1183
- return this.request(`/api/v1/admin/users${query ? `?${query}` : ""}`, { method: "GET" });
1184
- }
1185
- /**
1186
- * Get user by ID (admin only)
1187
- */
1188
- async adminGetUser(userId) {
1189
- return this.request(`/api/v1/admin/users/${userId}`, { method: "GET" });
1190
- }
1191
- /**
1192
- * Update user (admin only)
1193
- */
1194
- async adminUpdateUser(userId, data) {
1195
- return this.request(`/api/v1/admin/users/${userId}`, {
1196
- method: "PATCH",
1197
- body: JSON.stringify(data)
1198
- });
1199
- }
1200
- /**
1201
- * List all projects (admin only)
1202
- */
1203
- async adminListProjects(options) {
1204
- const params = new URLSearchParams();
1205
- if (options?.page) params.set("page", String(options.page));
1206
- if (options?.limit) params.set("limit", String(options.limit));
1207
- if (options?.search) params.set("search", options.search);
1208
- if (options?.sortBy) params.set("sortBy", options.sortBy);
1209
- if (options?.sortOrder) params.set("sortOrder", options.sortOrder);
1210
- if (options?.isActive !== void 0) params.set("isActive", String(options.isActive));
1211
- const query = params.toString();
1212
- return this.request(`/api/v1/admin/projects${query ? `?${query}` : ""}`, { method: "GET" });
1213
- }
1214
- /**
1215
- * Get project by ID (admin only)
1216
- */
1217
- async adminGetProject(projectId) {
1218
- return this.request(`/api/v1/admin/projects/${projectId}`, { method: "GET" });
1219
- }
1220
- /**
1221
- * Update project (admin only)
1222
- */
1223
- async adminUpdateProject(projectId, data) {
1224
- return this.request(`/api/v1/admin/projects/${projectId}`, {
1225
- method: "PATCH",
1226
- body: JSON.stringify(data)
1227
- });
1228
- }
1229
- /**
1230
- * Regenerate project API key (admin only)
1231
- */
1232
- async adminRegenerateApiKey(projectId) {
1233
- return this.request(`/api/v1/admin/projects/${projectId}/regenerate-key`, { method: "POST" });
1234
- }
1235
- /**
1236
- * Get system statistics (admin only)
1237
- */
1238
- async adminGetStats(days) {
1239
- const query = days ? `?days=${days}` : "";
1240
- return this.request(`/api/v1/admin/stats${query}`, { method: "GET" });
1241
- }
1242
- /**
1243
- * Get system logs (admin only)
1244
- */
1245
- async adminGetLogs(options) {
1246
- const params = new URLSearchParams();
1247
- if (options?.level) params.set("level", options.level);
1248
- if (options?.service) params.set("service", options.service);
1249
- if (options?.limit) params.set("limit", String(options.limit));
1250
- if (options?.offset) params.set("offset", String(options.offset));
1251
- if (options?.startDate) params.set("startDate", options.startDate);
1252
- if (options?.endDate) params.set("endDate", options.endDate);
1253
- const query = params.toString();
1254
- return this.request(`/api/v1/admin/logs${query ? `?${query}` : ""}`, { method: "GET" });
1255
- }
1256
- /**
1257
- * Get rate limit status (admin only)
1258
- */
1259
- async adminGetRateLimits(options) {
1260
- const params = new URLSearchParams();
1261
- if (options?.identifier) params.set("identifier", options.identifier);
1262
- if (options?.limit) params.set("limit", String(options.limit));
1263
- const query = params.toString();
1264
- return this.request(`/api/v1/admin/rate-limits${query ? `?${query}` : ""}`, { method: "GET" });
1265
- }
1266
- /**
1267
- * Clear rate limits for an identifier (admin only)
1268
- */
1269
- async adminClearRateLimits(identifier) {
1270
- return this.request(`/api/v1/admin/rate-limits/${identifier}`, { method: "DELETE" });
1271
- }
1272
- // ========== AI Quant Trading ==========
1273
- /**
1274
- * Get all AI trading strategies
1275
- */
1276
- async getAIStrategies(filters) {
1277
- const params = new URLSearchParams();
1278
- if (filters?.category) params.set("category", filters.category);
1279
- if (filters?.riskLevel) params.set("risk_level", String(filters.riskLevel));
1280
- if (filters?.minTvl) params.set("min_tvl", String(filters.minTvl));
1281
- if (filters?.isActive !== void 0) params.set("is_active", String(filters.isActive));
1282
- const query = params.toString();
1283
- return this.request(`/api/v1/ai-quant/strategies${query ? `?${query}` : ""}`, { method: "GET" });
1284
- }
1285
- /**
1286
- * Get AI strategy details
1287
- */
1288
- async getAIStrategy(strategyId, include) {
1289
- const params = new URLSearchParams();
1290
- if (include?.length) params.set("include", include.join(","));
1291
- const query = params.toString();
1292
- return this.request(`/api/v1/ai-quant/strategies/${strategyId}${query ? `?${query}` : ""}`, { method: "GET" });
1293
- }
1294
- /**
1295
- * Get strategy performance history
1296
- */
1297
- async getAIStrategyPerformance(strategyId, days = 30) {
1298
- return this.request(`/api/v1/ai-quant/strategies/${strategyId}?include=performance&days=${days}`, { method: "GET" });
1299
- }
1300
- /**
1301
- * Get real-time market data for strategy pairs
1302
- */
1303
- async getAIStrategyMarketData(strategyId) {
1304
- return this.request(`/api/v1/ai-quant/strategies/${strategyId}?include=market`, { method: "GET" });
1305
- }
1306
- /**
1307
- * Create AI trading order
1308
- */
1309
- async createAIOrder(request) {
1310
- return this.request("/api/v1/ai-quant/orders", {
1311
- method: "POST",
1312
- body: JSON.stringify(request)
1313
- });
1314
- }
1315
- /**
1316
- * Get user's AI orders
1317
- */
1318
- async getAIOrders(filters) {
1319
- const params = new URLSearchParams();
1320
- if (filters?.strategyId) params.set("strategy_id", filters.strategyId);
1321
- if (filters?.status) params.set("status", filters.status);
1322
- const query = params.toString();
1323
- return this.request(`/api/v1/ai-quant/orders${query ? `?${query}` : ""}`, { method: "GET" });
1324
- }
1325
- /**
1326
- * Get AI order details
1327
- */
1328
- async getAIOrder(orderId) {
1329
- return this.request(`/api/v1/ai-quant/orders/${orderId}`, { method: "GET" });
1330
- }
1331
- /**
1332
- * Pause AI order
1333
- */
1334
- async pauseAIOrder(orderId) {
1335
- return this.request(`/api/v1/ai-quant/orders/${orderId}/pause`, { method: "POST" });
1336
- }
1337
- /**
1338
- * Resume AI order
1339
- */
1340
- async resumeAIOrder(orderId) {
1341
- return this.request(`/api/v1/ai-quant/orders/${orderId}/resume`, { method: "POST" });
1342
- }
1343
- /**
1344
- * Request redemption for AI order
1345
- */
1346
- async redeemAIOrder(orderId) {
1347
- return this.request(`/api/v1/ai-quant/orders/${orderId}/redeem`, { method: "POST" });
1348
- }
1349
- /**
1350
- * Get AI portfolio summary
1351
- */
1352
- async getAIPortfolio(include) {
1353
- const params = new URLSearchParams();
1354
- if (include?.length) params.set("include", include.join(","));
1355
- const query = params.toString();
1356
- return this.request(`/api/v1/ai-quant/portfolio${query ? `?${query}` : ""}`, { method: "GET" });
1357
- }
1358
- /**
1359
- * Get user's trade allocations
1360
- */
1361
- async getAITradeAllocations(limit = 50) {
1362
- return this.request(`/api/v1/ai-quant/portfolio?include=allocations&limit=${limit}`, { method: "GET" });
1363
- }
1364
- /**
1365
- * Get trade history for a strategy
1366
- */
1367
- async getAITradeHistory(strategyId, limit = 50) {
1368
- return this.request(`/api/v1/ai-quant/strategies/${strategyId}?include=trades&limit=${limit}`, { method: "GET" });
1369
- }
1370
- /**
1371
- * Execute AI signals for a strategy (admin only)
1372
- */
1373
- async executeAISignals(strategyId) {
1374
- return this.request("/api/v1/ai-quant/execute", {
1375
- method: "POST",
1376
- body: JSON.stringify({ strategyId })
1377
- });
1378
- }
1379
- // ========== Free Price APIs (No API Key Required) ==========
1380
- /**
1381
- * Get cryptocurrency prices (FREE - uses CoinGecko/Binance/CoinCap)
1382
- */
1383
- async getCryptoPrices(symbols) {
1384
- return this.request(`/api/v1/prices?symbols=${symbols.join(",")}`, { method: "GET" });
1385
- }
1386
- /**
1387
- * Get single cryptocurrency price (FREE)
1388
- */
1389
- async getCryptoPrice(symbol) {
1390
- return this.request(`/api/v1/prices/${symbol}`, { method: "GET" });
1391
- }
1392
- /**
1393
- * Get OHLCV candles for charting (FREE - from Binance)
1394
- */
1395
- async getCryptoCandles(symbol, interval = "1h", limit = 100) {
1396
- return this.request(`/api/v1/prices/${symbol}?candles=true&interval=${interval}&limit=${limit}`, { method: "GET" });
1397
- }
1398
- /**
1399
- * Get top cryptocurrencies by market cap (FREE)
1400
- */
1401
- async getTopCryptos(limit = 20) {
1402
- return this.request(`/api/v1/prices?type=top&limit=${limit}`, { method: "GET" });
1403
- }
1404
- /**
1405
- * Get crypto market overview (FREE)
1406
- */
1407
- async getCryptoMarketOverview() {
1408
- return this.request("/api/v1/prices?type=overview", { method: "GET" });
1409
- }
1410
- };
1411
- function createOneEngineClient(options) {
1412
- return new OneEngineClient(options);
1413
- }
1414
- var supabaseInstance = null;
1415
- function createSupabaseClient(url, anonKey) {
1416
- const config2 = getConfig();
1417
- const supabaseUrl = url || config2.supabaseUrl;
1418
- const supabaseAnonKey = anonKey || config2.supabaseAnonKey;
1419
- if (!supabaseUrl || !supabaseAnonKey) {
1420
- throw new Error("Supabase URL and Anon Key are required");
1421
- }
1422
- return createClient(supabaseUrl, supabaseAnonKey, {
1423
- auth: {
1424
- autoRefreshToken: true,
1425
- persistSession: true,
1426
- detectSessionInUrl: true
1427
- }
1428
- });
1429
- }
1430
- function getSupabaseClient() {
1431
- if (!supabaseInstance) {
1432
- supabaseInstance = createSupabaseClient();
1433
- }
1434
- return supabaseInstance;
1435
- }
1436
- var SupabaseService = class {
1437
- constructor(client) {
1438
- this.client = client || getSupabaseClient();
1439
- }
1440
- // ===== Auth Methods =====
1441
- async signInWithEmail(email) {
1442
- const { data, error } = await this.client.auth.signInWithOtp({
1443
- email,
1444
- options: {
1445
- shouldCreateUser: true
1446
- }
1447
- });
1448
- return { data, error };
1449
- }
1450
- async verifyOtp(email, token) {
1451
- const { data, error } = await this.client.auth.verifyOtp({
1452
- email,
1453
- token,
1454
- type: "email"
1455
- });
1456
- return { data, error };
1457
- }
1458
- async signOut() {
1459
- const { error } = await this.client.auth.signOut();
1460
- return { error };
1461
- }
1462
- async getSession() {
1463
- const { data, error } = await this.client.auth.getSession();
1464
- return { session: data.session, error };
1465
- }
1466
- async getUser() {
1467
- const { data, error } = await this.client.auth.getUser();
1468
- return { user: data.user, error };
1469
- }
1470
- // ===== User Profile Methods =====
1471
- async getUserProfile(userId) {
1472
- const { data, error } = await this.client.from("user_profiles").select("*").eq("user_id", userId).single();
1473
- return { data, error };
1474
- }
1475
- async updateUserProfile(userId, updates) {
1476
- const { data, error } = await this.client.from("user_profiles").update(updates).eq("user_id", userId).select().single();
1477
- return { data, error };
1478
- }
1479
- // ===== Transaction Methods =====
1480
- async getTransactions(userId, limit = 50) {
1481
- const { data, error } = await this.client.from("transactions").select("*").eq("user_id", userId).order("created_at", { ascending: false }).limit(limit);
1482
- return { data, error };
1483
- }
1484
- async createTransaction(transaction) {
1485
- const { data, error } = await this.client.from("transactions").insert(transaction).select().single();
1486
- return { data, error };
1487
- }
1488
- // ===== AI Trading Methods =====
1489
- async getStrategies(status = "active") {
1490
- const { data, error } = await this.client.from("ai_strategies").select("*").eq("status", status).order("total_aum", { ascending: false });
1491
- return { data, error };
1492
- }
1493
- async getStrategyById(strategyId) {
1494
- const { data, error } = await this.client.from("ai_strategies").select("*").eq("id", strategyId).single();
1495
- return { data, error };
1496
- }
1497
- async getUserOrders(userId) {
1498
- const { data, error } = await this.client.from("ai_orders").select(`*, ai_strategies (name)`).eq("user_id", userId).order("created_at", { ascending: false });
1499
- return { data, error };
1500
- }
1501
- async createOrder(order) {
1502
- const { data, error } = await this.client.from("ai_orders").insert(order).select().single();
1503
- return { data, error };
1504
- }
1505
- // ===== Card Methods =====
1506
- async getUserCards(userId) {
1507
- const { data, error } = await this.client.from("cards").select("*").eq("user_id", userId).order("created_at", { ascending: false });
1508
- return { data, error };
1509
- }
1510
- // ===== Realtime Subscriptions =====
1511
- subscribeToTransactions(userId, callback) {
1512
- return this.client.channel(`transactions:${userId}`).on(
1513
- "postgres_changes",
1514
- {
1515
- event: "*",
1516
- schema: "public",
1517
- table: "transactions",
1518
- filter: `user_id=eq.${userId}`
1519
- },
1520
- callback
1521
- ).subscribe();
1522
- }
1523
- unsubscribe(channel) {
1524
- return this.client.removeChannel(channel);
1525
- }
1526
- };
1527
-
1528
- // src/services/price.ts
1529
- var COINGECKO_API = "https://api.coingecko.com/api/v3";
1530
- var FALLBACK_PRICES = {
1531
- ETH: 3500,
1532
- BTC: 95e3,
1533
- BNB: 700,
1534
- MATIC: 0.5,
1535
- AVAX: 40,
1536
- USDT: 1,
1537
- USDC: 1,
1538
- DAI: 1,
1539
- WBTC: 95e3,
1540
- WETH: 3500,
1541
- ARB: 1.2,
1542
- OP: 2.5,
1543
- LINK: 20,
1544
- UNI: 12,
1545
- AAVE: 250,
1546
- SOL: 200
1547
- };
1548
- var PriceService = class {
1549
- constructor() {
1550
- this.cache = /* @__PURE__ */ new Map();
1551
- this.cacheTTL = 60 * 1e3;
1552
- }
1553
- // 1 minute cache
1554
- async getPrice(symbol) {
1555
- const upperSymbol = symbol.toUpperCase();
1556
- const cached = this.cache.get(upperSymbol);
1557
- if (cached && Date.now() - cached.timestamp < this.cacheTTL) {
1558
- return cached.price;
1559
- }
1560
- const coinId = COINGECKO_IDS[upperSymbol];
1561
- if (!coinId) {
1562
- return this.getFallbackPrice(upperSymbol);
1563
- }
1564
- try {
1565
- const response = await fetch(
1566
- `${COINGECKO_API}/simple/price?ids=${coinId}&vs_currencies=usd&include_24hr_change=true&include_market_cap=true&include_24hr_vol=true`,
1567
- { headers: { Accept: "application/json" } }
1568
- );
1569
- if (!response.ok) {
1570
- throw new Error(`CoinGecko API error: ${response.status}`);
1571
- }
1572
- const data = await response.json();
1573
- const coinData = data[coinId];
1574
- if (!coinData) {
1575
- return this.getFallbackPrice(upperSymbol);
1576
- }
1577
- const change24h = coinData.usd_24h_change || 0;
1578
- const price = {
1579
- symbol: upperSymbol,
1580
- price: coinData.usd || 0,
1581
- change24h,
1582
- changePercent24h: change24h,
1583
- priceChange24h: change24h,
1584
- marketCap: coinData.usd_market_cap,
1585
- volume24h: coinData.usd_24h_vol
1586
- };
1587
- this.cache.set(upperSymbol, { price, timestamp: Date.now() });
1588
- return price;
1589
- } catch (error) {
1590
- console.warn(`Failed to fetch price for ${upperSymbol}:`, error);
1591
- return this.getFallbackPrice(upperSymbol);
1592
- }
1593
- }
1594
- async getPrices(symbols) {
1595
- const results = {};
1596
- const withIds = [];
1597
- const withoutIds = [];
1598
- for (const symbol of symbols) {
1599
- const upper = symbol.toUpperCase();
1600
- if (COINGECKO_IDS[upper]) {
1601
- withIds.push(upper);
1602
- } else {
1603
- withoutIds.push(upper);
1604
- }
1605
- }
1606
- for (const symbol of withoutIds) {
1607
- results[symbol] = this.getFallbackPrice(symbol);
1608
- }
1609
- if (withIds.length === 0) {
1610
- return results;
1611
- }
1612
- const coinIds = withIds.map((s) => COINGECKO_IDS[s]).join(",");
1613
- try {
1614
- const response = await fetch(
1615
- `${COINGECKO_API}/simple/price?ids=${coinIds}&vs_currencies=usd&include_24hr_change=true`,
1616
- { headers: { Accept: "application/json" } }
1617
- );
1618
- if (!response.ok) {
1619
- throw new Error(`CoinGecko API error: ${response.status}`);
1620
- }
1621
- const data = await response.json();
1622
- for (const symbol of withIds) {
1623
- const coinId = COINGECKO_IDS[symbol];
1624
- const coinData = data[coinId];
1625
- if (coinData) {
1626
- const change24h = coinData.usd_24h_change || 0;
1627
- results[symbol] = {
1628
- symbol,
1629
- price: coinData.usd || 0,
1630
- change24h,
1631
- changePercent24h: change24h,
1632
- priceChange24h: change24h
1633
- };
1634
- } else {
1635
- results[symbol] = this.getFallbackPrice(symbol);
1636
- }
1637
- }
1638
- } catch (error) {
1639
- console.warn("Failed to fetch batch prices:", error);
1640
- for (const symbol of withIds) {
1641
- results[symbol] = this.getFallbackPrice(symbol);
1642
- }
1643
- }
1644
- return results;
1645
- }
1646
- getFallbackPrice(symbol) {
1647
- const price = FALLBACK_PRICES[symbol] || 0;
1648
- return {
1649
- symbol,
1650
- price,
1651
- change24h: 0,
1652
- changePercent24h: 0,
1653
- priceChange24h: 0
1654
- };
1655
- }
1656
- clearCache() {
1657
- this.cache.clear();
1658
- }
1659
- };
1660
- var priceService = new PriceService();
1661
- var OneContext = createContext(null);
1662
- function OneProvider({
1663
- children,
1664
- config: config2,
1665
- autoFetchBalance = true
1666
- }) {
1667
- useMemo(() => {
1668
- initOneSDK(config2);
1669
- }, [config2]);
1670
- const [isInitialized2, setIsInitialized] = useState(true);
1671
- const engine = useMemo(() => createOneEngineClient({
1672
- baseUrl: config2.oneEngineUrl,
1673
- clientId: config2.oneClientId,
1674
- secretKey: config2.oneSecretKey
1675
- }), [config2]);
1676
- const [user, setUser] = useState(null);
1677
- const [accessToken, setAccessToken] = useState(null);
1678
- const [authLoading, setAuthLoading] = useState(true);
1679
- const sendOtp = useCallback(async (email) => {
1680
- const result = await engine.sendEmailOtp(email);
1681
- if (!result.success) {
1682
- return { success: false, error: result.error?.message };
1683
- }
1684
- return { success: true };
1685
- }, [engine]);
1686
- const verifyOtp = useCallback(async (email, otp) => {
1687
- const result = await engine.verifyEmailOtp(email, otp);
1688
- if (!result.success || !result.data) {
1689
- return { success: false, error: result.error?.message };
1690
- }
1691
- const { user: authUser, accessToken: token } = result.data;
1692
- setUser(authUser);
1693
- setAccessToken(token);
1694
- engine.setAccessToken(token);
1695
- return { success: true };
1696
- }, [engine]);
1697
- const signOut = useCallback(async () => {
1698
- await engine.signOut();
1699
- setUser(null);
1700
- setAccessToken(null);
1701
- engine.clearAccessToken();
1702
- }, [engine]);
1703
- const refreshUser = useCallback(async () => {
1704
- try {
1705
- if (accessToken) {
1706
- engine.setAccessToken(accessToken);
1707
- const result = await engine.getCurrentUser();
1708
- if (result.success && result.data) {
1709
- setUser(result.data);
1710
- }
1711
- }
1712
- } finally {
1713
- setAuthLoading(false);
1714
- }
1715
- }, [engine, accessToken]);
1716
- useEffect(() => {
1717
- refreshUser();
1718
- }, []);
1719
- const [walletAddress, setWalletAddress] = useState(null);
1720
- const [walletBalance, setWalletBalance] = useState(null);
1721
- const [walletLoading, setWalletLoading] = useState(false);
1722
- const [walletError, setWalletError] = useState(null);
1723
- const fetchBalance = useCallback(async (chains) => {
1724
- if (!walletAddress) return;
1725
- setWalletLoading(true);
1726
- setWalletError(null);
1727
- try {
1728
- const result = await engine.getWalletBalance(walletAddress, chains);
1729
- if (result.success && result.data) {
1730
- setWalletBalance(result.data);
1731
- } else {
1732
- setWalletError(result.error?.message || "Failed to fetch balance");
1733
- }
1734
- } catch (error) {
1735
- setWalletError(error instanceof Error ? error.message : "Failed to fetch balance");
1736
- } finally {
1737
- setWalletLoading(false);
1738
- }
1739
- }, [walletAddress, engine]);
1740
- const refreshBalance = useCallback(async () => {
1741
- await fetchBalance();
1742
- }, [fetchBalance]);
1743
- useEffect(() => {
1744
- if (autoFetchBalance && walletAddress && isInitialized2) {
1745
- fetchBalance();
1746
- }
1747
- }, [walletAddress, autoFetchBalance, isInitialized2, fetchBalance]);
1748
- const [onrampOpen, setOnrampOpen] = useState(false);
1749
- const [onrampUrl, setOnrampUrl] = useState(null);
1750
- const [onrampSessionId, setOnrampSessionId] = useState(null);
1751
- const openOnramp = useCallback(async (options) => {
1752
- if (!walletAddress) return;
1753
- const result = await engine.createOnrampSession({
1754
- walletAddress,
1755
- fiatCurrency: "USD",
1756
- cryptoCurrency: "ETH",
1757
- ...options
1758
- });
1759
- if (result.success && result.data) {
1760
- setOnrampUrl(result.data.widgetUrl);
1761
- setOnrampSessionId(result.data.sessionId);
1762
- setOnrampOpen(true);
1763
- }
1764
- }, [walletAddress, engine]);
1765
- const closeOnramp = useCallback(() => {
1766
- setOnrampOpen(false);
1767
- setOnrampUrl(null);
1768
- }, []);
1769
- const getOnrampQuote = useCallback(async (fiatCurrency, fiatAmount, cryptoCurrency) => {
1770
- const result = await engine.getOnrampQuote(fiatCurrency, fiatAmount, cryptoCurrency);
1771
- return result.success ? result.data : null;
1772
- }, [engine]);
1773
- const getSwapQuote = useCallback(async (request) => {
1774
- const result = await engine.getSwapQuote(request);
1775
- return result.success ? result.data || null : null;
1776
- }, [engine]);
1777
- const executeSwap = useCallback(async (quoteId) => {
1778
- if (!walletAddress) return null;
1779
- const result = await engine.executeSwap({ quoteId, walletAddress });
1780
- return result.success ? result.data : null;
1781
- }, [engine, walletAddress]);
1782
- const getSupportedTokens = useCallback(async (chainId) => {
1783
- const result = await engine.getSupportedSwapTokens(chainId);
1784
- return result.success && result.data ? result.data.tokens : [];
1785
- }, [engine]);
1786
- const getSupportedChains = useCallback(async () => {
1787
- const result = await engine.getSupportedSwapChains();
1788
- return result.success && result.data ? result.data.chains : [];
1789
- }, [engine]);
1790
- const [strategies, setStrategies] = useState([]);
1791
- const [orders, setOrders] = useState([]);
1792
- const [portfolioStats, setPortfolioStats] = useState(null);
1793
- const [tradingLoading, setTradingLoading] = useState(false);
1794
- const fetchStrategies = useCallback(async () => {
1795
- setTradingLoading(true);
1796
- try {
1797
- const result = await engine.getStrategies();
1798
- if (result.success && result.data) {
1799
- setStrategies(result.data);
1800
- }
1801
- } finally {
1802
- setTradingLoading(false);
1803
- }
1804
- }, [engine]);
1805
- const fetchOrders = useCallback(async () => {
1806
- const result = await engine.getUserOrders();
1807
- if (result.success && result.data) {
1808
- setOrders(result.data);
1809
- }
1810
- }, [engine]);
1811
- const fetchPortfolio = useCallback(async () => {
1812
- const result = await engine.getPortfolioStats();
1813
- if (result.success && result.data) {
1814
- setPortfolioStats(result.data);
1815
- }
1816
- }, [engine]);
1817
- const createOrder = useCallback(async (strategyId, amount, currency) => {
1818
- const result = await engine.createOrder(strategyId, amount, currency);
1819
- if (result.success) {
1820
- await fetchOrders();
1821
- await fetchPortfolio();
1822
- }
1823
- return result;
1824
- }, [engine, fetchOrders, fetchPortfolio]);
1825
- const contextValue = useMemo(() => ({
1826
- isInitialized: isInitialized2,
1827
- config: isInitialized2 ? config2 : null,
1828
- engine,
1829
- auth: {
1830
- user,
1831
- isAuthenticated: !!user,
1832
- isLoading: authLoading,
1833
- accessToken,
1834
- sendOtp,
1835
- verifyOtp,
1836
- signOut,
1837
- refreshUser
1838
- },
1839
- wallet: {
1840
- address: walletAddress,
1841
- balance: walletBalance,
1842
- tokens: walletBalance?.tokens || [],
1843
- totalUsd: walletBalance?.totalUsd || 0,
1844
- isLoading: walletLoading,
1845
- error: walletError,
1846
- setAddress: setWalletAddress,
1847
- fetchBalance,
1848
- refreshBalance
1849
- },
1850
- onramp: {
1851
- isOpen: onrampOpen,
1852
- widgetUrl: onrampUrl,
1853
- sessionId: onrampSessionId,
1854
- openOnramp,
1855
- closeOnramp,
1856
- getQuote: getOnrampQuote
1857
- },
1858
- swap: {
1859
- getQuote: getSwapQuote,
1860
- executeSwap,
1861
- getSupportedTokens,
1862
- getSupportedChains
1863
- },
1864
- trading: {
1865
- strategies,
1866
- orders,
1867
- portfolioStats,
1868
- isLoading: tradingLoading,
1869
- fetchStrategies,
1870
- fetchOrders,
1871
- fetchPortfolio,
1872
- createOrder
1873
- }
1874
- }), [
1875
- isInitialized2,
1876
- config2,
1877
- engine,
1878
- user,
1879
- authLoading,
1880
- accessToken,
1881
- sendOtp,
1882
- verifyOtp,
1883
- signOut,
1884
- refreshUser,
1885
- walletAddress,
1886
- walletBalance,
1887
- walletLoading,
1888
- walletError,
1889
- fetchBalance,
1890
- refreshBalance,
1891
- onrampOpen,
1892
- onrampUrl,
1893
- onrampSessionId,
1894
- openOnramp,
1895
- closeOnramp,
1896
- getOnrampQuote,
1897
- getSwapQuote,
1898
- executeSwap,
1899
- getSupportedTokens,
1900
- getSupportedChains,
1901
- strategies,
1902
- orders,
1903
- portfolioStats,
1904
- tradingLoading,
1905
- fetchStrategies,
1906
- fetchOrders,
1907
- fetchPortfolio,
1908
- createOrder
1909
- ]);
1910
- return /* @__PURE__ */ jsx(OneContext.Provider, { value: contextValue, children });
1911
- }
1912
- function useOne() {
1913
- const context = useContext(OneContext);
1914
- if (!context) {
1915
- throw new Error("useOne must be used within a OneProvider");
1916
- }
1917
- return context;
1918
- }
1919
- function useOneAuth() {
1920
- const { auth } = useOne();
1921
- return auth;
1922
- }
1923
- function useOneWallet() {
1924
- const { wallet } = useOne();
1925
- return wallet;
1926
- }
1927
- function useOneOnramp() {
1928
- const { onramp } = useOne();
1929
- return onramp;
1930
- }
1931
- function useOneSwap() {
1932
- const { swap } = useOne();
1933
- return swap;
1934
- }
1935
- function useOneTrading() {
1936
- const { trading } = useOne();
1937
- return trading;
1938
- }
1939
- function useOneEngine() {
1940
- const { engine } = useOne();
1941
- return engine;
1942
- }
1943
- var DEFAULT_AUTH_OPTIONS = {
1944
- email: true,
1945
- phone: false,
1946
- google: true,
1947
- apple: true,
1948
- facebook: false,
1949
- discord: false,
1950
- passkey: true,
1951
- guest: false
1952
- };
1953
- var ThirdwebClientContext = React2.createContext(null);
1954
- function useThirdwebClient() {
1955
- const client = React2.useContext(ThirdwebClientContext);
1956
- if (!client) {
1957
- throw new Error("useThirdwebClient must be used within OneThirdwebProvider");
1958
- }
1959
- return client;
1960
- }
1961
- function createWalletConfig(config2) {
1962
- const authOptions = { ...DEFAULT_AUTH_OPTIONS, ...config2.authOptions };
1963
- const authMethods = [];
1964
- if (authOptions.google) authMethods.push("google");
1965
- if (authOptions.apple) authMethods.push("apple");
1966
- if (authOptions.facebook) authMethods.push("facebook");
1967
- if (authOptions.discord) authMethods.push("discord");
1968
- if (authOptions.passkey) authMethods.push("passkey");
1969
- const inApp = inAppWallet({
1970
- auth: {
1971
- options: authMethods
1972
- },
1973
- metadata: config2.appName ? {
1974
- name: config2.appName,
1975
- image: config2.appIcon ? { src: config2.appIcon, width: 100, height: 100 } : void 0
1976
- } : void 0
1977
- });
1978
- if (config2.sponsorGas) {
1979
- const chain = config2.defaultChain || base;
1980
- return [
1981
- smartWallet({
1982
- chain,
1983
- sponsorGas: true
1984
- })
1985
- ];
1986
- }
1987
- return [inApp];
1988
- }
1989
- var DEFAULT_ENGINE_URL2 = process.env.NEXT_PUBLIC_ONE_ENGINE_URL || "/api";
1990
- function OneThirdwebProvider({
1991
- children,
1992
- config: config2 = {}
1993
- }) {
1994
- const [clientId, setClientId] = useState(null);
1995
- const [isLoading, setIsLoading] = useState(true);
1996
- const [error, setError] = useState(null);
1997
- useEffect(() => {
1998
- const fetchClientConfig = async () => {
1999
- try {
2000
- const engineUrl = config2.engineUrl || DEFAULT_ENGINE_URL2;
2001
- const response = await fetch(`${engineUrl}/v1/config/thirdweb`);
2002
- if (response.ok) {
2003
- const data = await response.json();
2004
- if (data.success && data.data?.clientId) {
2005
- setClientId(data.data.clientId);
2006
- } else {
2007
- const envClientId = process.env.NEXT_PUBLIC_THIRDWEB_CLIENT_ID;
2008
- if (envClientId) {
2009
- setClientId(envClientId);
2010
- } else {
2011
- setError("Failed to load wallet configuration");
2012
- }
2013
- }
2014
- } else {
2015
- const envClientId = process.env.NEXT_PUBLIC_THIRDWEB_CLIENT_ID;
2016
- if (envClientId) {
2017
- setClientId(envClientId);
2018
- } else {
2019
- setError("Wallet service unavailable");
2020
- }
2021
- }
2022
- } catch (err) {
2023
- const envClientId = process.env.NEXT_PUBLIC_THIRDWEB_CLIENT_ID;
2024
- if (envClientId) {
2025
- setClientId(envClientId);
2026
- } else {
2027
- console.error("Failed to fetch thirdweb config:", err);
2028
- setError("Failed to initialize wallet");
2029
- }
2030
- } finally {
2031
- setIsLoading(false);
2032
- }
2033
- };
2034
- fetchClientConfig();
2035
- }, [config2.engineUrl]);
2036
- const client = useMemo(() => {
2037
- if (!clientId) return null;
2038
- return createThirdwebClient({ clientId });
2039
- }, [clientId]);
2040
- useMemo(() => createWalletConfig(config2), [config2]);
2041
- if (isLoading) {
2042
- return /* @__PURE__ */ jsx("div", { style: { display: "flex", alignItems: "center", justifyContent: "center", minHeight: "100px" }, children: /* @__PURE__ */ jsx("span", { style: { color: "#9ca3af" }, children: "Initializing wallet..." }) });
2043
- }
2044
- if (error || !client) {
2045
- return /* @__PURE__ */ jsx("div", { style: { display: "flex", alignItems: "center", justifyContent: "center", minHeight: "100px" }, children: /* @__PURE__ */ jsx("span", { style: { color: "#ef4444" }, children: error || "Wallet initialization failed" }) });
2046
- }
2047
- return /* @__PURE__ */ jsx(ThirdwebClientContext.Provider, { value: client, children: /* @__PURE__ */ jsx(ThirdwebProvider, { children }) });
2048
- }
2049
- var ONE_THEME = {
2050
- colors: {
2051
- primaryButtonBg: "#10b981",
2052
- // emerald-500
2053
- primaryButtonText: "#ffffff"},
2054
- fontFamily: "Inter, system-ui, sans-serif"
2055
- };
2056
- function OneConnectButton({
2057
- label = "Connect Wallet",
2058
- theme = "dark",
2059
- className,
2060
- style,
2061
- chain = base,
2062
- sponsorGas = true,
2063
- authOptions = {
2064
- email: true,
2065
- google: true,
2066
- apple: true,
2067
- discord: false,
2068
- passkey: true
2069
- },
2070
- onConnect,
2071
- onDisconnect,
2072
- accountAbstraction
2073
- }) {
2074
- const client = useThirdwebClient();
2075
- const authMethods = ["email"];
2076
- if (authOptions.google) authMethods.push("google");
2077
- if (authOptions.apple) authMethods.push("apple");
2078
- if (authOptions.discord) authMethods.push("discord");
2079
- if (authOptions.passkey) authMethods.push("passkey");
2080
- const wallet = inAppWallet({
2081
- auth: {
2082
- options: authMethods
2083
- }
2084
- });
2085
- const connectProps = {
2086
- client,
2087
- wallets: [wallet],
2088
- connectButton: {
2089
- label,
2090
- style: {
2091
- backgroundColor: ONE_THEME.colors.primaryButtonBg,
2092
- color: ONE_THEME.colors.primaryButtonText,
2093
- fontFamily: ONE_THEME.fontFamily,
2094
- fontWeight: 600,
2095
- borderRadius: "12px",
2096
- padding: "12px 24px",
2097
- ...style
2098
- },
2099
- className
2100
- },
2101
- theme: theme === "dark" ? "dark" : "light"
2102
- };
2103
- if (sponsorGas || accountAbstraction) {
2104
- connectProps.accountAbstraction = {
2105
- chain: accountAbstraction?.chain || chain,
2106
- sponsorGas: accountAbstraction?.sponsorGas ?? sponsorGas
2107
- };
2108
- }
2109
- return /* @__PURE__ */ jsx(ConnectButton, { ...connectProps });
2110
- }
2111
- function OneConnectButtonSimple(props) {
2112
- return /* @__PURE__ */ jsx(
2113
- OneConnectButton,
2114
- {
2115
- ...props,
2116
- authOptions: { email: true, google: true, apple: false, passkey: false }
2117
- }
2118
- );
2119
- }
2120
- function OneConnectButtonFull(props) {
2121
- return /* @__PURE__ */ jsx(
2122
- OneConnectButton,
2123
- {
2124
- ...props,
2125
- authOptions: { email: true, google: true, apple: true, discord: true, passkey: true }
2126
- }
2127
- );
2128
- }
2129
- var DEFAULT_SUPPORTED_TOKENS = {
2130
- [base.id]: [
2131
- "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
2132
- // USDC on Base
2133
- ],
2134
- [ethereum.id]: [
2135
- "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
2136
- // USDC on Ethereum
2137
- "0xdAC17F958D2ee523a2206206994597C13D831ec7"
2138
- // USDT on Ethereum
2139
- ],
2140
- [polygon.id]: [
2141
- "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"
2142
- // USDC on Polygon
2143
- ],
2144
- [arbitrum.id]: [
2145
- "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"
2146
- // USDC on Arbitrum
2147
- ]
2148
- };
2149
- function OnePayWidget({
2150
- mode = "fund_wallet",
2151
- recipientAddress,
2152
- amount,
2153
- tokenAddress,
2154
- chainId,
2155
- transaction,
2156
- theme = "dark",
2157
- className,
2158
- style,
2159
- buyWithCrypto = true,
2160
- buyWithFiat = true,
2161
- supportedTokens = DEFAULT_SUPPORTED_TOKENS,
2162
- onSuccess,
2163
- onError,
2164
- onCancel
2165
- }) {
2166
- const client = useThirdwebClient();
2167
- let payOptions;
2168
- switch (mode) {
2169
- case "direct_payment":
2170
- if (!recipientAddress) {
2171
- console.warn("OnePayWidget: recipientAddress required for direct_payment mode");
2172
- }
2173
- payOptions = {
2174
- mode: "direct_payment",
2175
- paymentInfo: {
2176
- sellerAddress: recipientAddress || "",
2177
- amount: amount || "0",
2178
- chain: chainId ? { id: chainId } : base,
2179
- token: tokenAddress ? { address: tokenAddress } : void 0
2180
- },
2181
- buyWithCrypto: buyWithCrypto ? {} : false,
2182
- buyWithFiat: buyWithFiat ? {} : false
2183
- };
2184
- break;
2185
- case "transaction":
2186
- if (!transaction) {
2187
- console.warn("OnePayWidget: transaction required for transaction mode");
2188
- }
2189
- payOptions = {
2190
- mode: "transaction",
2191
- transaction,
2192
- buyWithCrypto: buyWithCrypto ? {} : false,
2193
- buyWithFiat: buyWithFiat ? {} : false
2194
- };
2195
- break;
2196
- case "fund_wallet":
2197
- default:
2198
- payOptions = {
2199
- mode: "fund_wallet",
2200
- buyWithCrypto: buyWithCrypto ? {} : false,
2201
- buyWithFiat: buyWithFiat ? {} : false
2202
- };
2203
- break;
2204
- }
2205
- return /* @__PURE__ */ jsx("div", { className, style, children: /* @__PURE__ */ jsx(
2206
- PayEmbed,
2207
- {
2208
- client,
2209
- payOptions,
2210
- theme,
2211
- supportedTokens
2212
- }
2213
- ) });
2214
- }
2215
- function OneFundWalletWidget(props) {
2216
- return /* @__PURE__ */ jsx(OnePayWidget, { ...props, mode: "fund_wallet" });
2217
- }
2218
- function OneDirectPayWidget(props) {
2219
- return /* @__PURE__ */ jsx(OnePayWidget, { ...props, mode: "direct_payment" });
2220
- }
2221
- function OneCryptoOnlyPayWidget(props) {
2222
- return /* @__PURE__ */ jsx(OnePayWidget, { ...props, buyWithFiat: false });
2223
- }
2224
- function OneFiatOnlyPayWidget(props) {
2225
- return /* @__PURE__ */ jsx(OnePayWidget, { ...props, buyWithCrypto: false });
2226
- }
2227
- var ONE_BUTTON_STYLE = {
2228
- backgroundColor: "#10b981",
2229
- color: "#ffffff",
2230
- fontFamily: "Inter, system-ui, sans-serif",
2231
- fontWeight: 600,
2232
- borderRadius: "12px",
2233
- padding: "12px 24px",
2234
- border: "none",
2235
- cursor: "pointer",
2236
- transition: "background-color 0.2s"
2237
- };
2238
- var ONE_BUTTON_DISABLED_STYLE = {
2239
- ...ONE_BUTTON_STYLE,
2240
- backgroundColor: "#6b7280",
2241
- cursor: "not-allowed"
2242
- };
2243
- function OneTransactionButton({
2244
- to,
2245
- value,
2246
- data,
2247
- chain,
2248
- transaction: preparedTx,
2249
- label = "Send Transaction",
2250
- loadingLabel = "Processing...",
2251
- theme = "dark",
2252
- className,
2253
- style,
2254
- disabled = false,
2255
- onSuccess,
2256
- onError,
2257
- onSubmitted
2258
- }) {
2259
- const client = useThirdwebClient();
2260
- const transaction = preparedTx || prepareTransaction({
2261
- to,
2262
- value,
2263
- data,
2264
- chain,
2265
- client
2266
- });
2267
- const buttonStyle6 = disabled ? { ...ONE_BUTTON_DISABLED_STYLE, ...style } : { ...ONE_BUTTON_STYLE, ...style };
2268
- return /* @__PURE__ */ jsx(
2269
- TransactionButton,
2270
- {
2271
- transaction: () => transaction,
2272
- onTransactionSent: (result) => onSubmitted?.(result.transactionHash),
2273
- onTransactionConfirmed: (result) => onSuccess?.({ transactionHash: result.transactionHash }),
2274
- onError,
2275
- disabled,
2276
- style: buttonStyle6,
2277
- className,
2278
- theme,
2279
- children: label
2280
- }
2281
- );
2282
- }
2283
- function OneSendETHButton({
2284
- amount,
2285
- ...props
2286
- }) {
2287
- const valueInWei = BigInt(Math.floor(parseFloat(amount) * 1e18));
2288
- return /* @__PURE__ */ jsx(
2289
- OneTransactionButton,
2290
- {
2291
- ...props,
2292
- value: valueInWei,
2293
- label: props.label || `Send ${amount} ETH`
2294
- }
2295
- );
2296
- }
2297
- function OneApproveButton({
2298
- tokenAddress,
2299
- spenderAddress,
2300
- amount = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
2301
- chain,
2302
- ...props
2303
- }) {
2304
- const approveData = `0x095ea7b3${spenderAddress.slice(2).padStart(64, "0")}${amount.toString(16).padStart(64, "0")}`;
2305
- return /* @__PURE__ */ jsx(
2306
- OneTransactionButton,
2307
- {
2308
- ...props,
2309
- to: tokenAddress,
2310
- data: approveData,
2311
- chain,
2312
- label: props.label || "Approve Token"
2313
- }
2314
- );
2315
- }
2316
- var containerStyle = {
2317
- display: "flex",
2318
- flexDirection: "column",
2319
- gap: "16px",
2320
- padding: "24px",
2321
- backgroundColor: "#1f2937",
2322
- borderRadius: "16px",
2323
- border: "1px solid #374151"
2324
- };
2325
- var inputStyle = {
2326
- width: "100%",
2327
- padding: "12px 16px",
2328
- backgroundColor: "#374151",
2329
- border: "1px solid #4b5563",
2330
- borderRadius: "12px",
2331
- color: "#ffffff",
2332
- fontSize: "16px",
2333
- outline: "none"
2334
- };
2335
- var labelStyle = {
2336
- color: "#9ca3af",
2337
- fontSize: "14px",
2338
- marginBottom: "4px"
2339
- };
2340
- var buttonStyle = {
2341
- width: "100%",
2342
- padding: "14px",
2343
- backgroundColor: "#10b981",
2344
- color: "#ffffff",
2345
- border: "none",
2346
- borderRadius: "12px",
2347
- fontSize: "16px",
2348
- fontWeight: 600,
2349
- cursor: "pointer"
2350
- };
2351
- var buttonDisabledStyle = {
2352
- ...buttonStyle,
2353
- backgroundColor: "#6b7280",
2354
- cursor: "not-allowed"
2355
- };
2356
- function OneSendWidget({
2357
- defaultRecipient = "",
2358
- defaultAmount = "",
2359
- defaultChain = base,
2360
- tokenAddress,
2361
- tokenSymbol = "ETH",
2362
- tokenDecimals = 18,
2363
- theme = "dark",
2364
- className,
2365
- style,
2366
- onSuccess,
2367
- onError,
2368
- onCancel
2369
- }) {
2370
- const client = useThirdwebClient();
2371
- const account = useActiveAccount();
2372
- const { mutate: sendTransaction, isPending } = useSendTransaction();
2373
- const [recipient, setRecipient] = useState(defaultRecipient);
2374
- const [amount, setAmount] = useState(defaultAmount);
2375
- const [error, setError] = useState(null);
2376
- const isValidAddress2 = (address) => /^0x[a-fA-F0-9]{40}$/.test(address);
2377
- const isValidAmount = (amt) => !isNaN(parseFloat(amt)) && parseFloat(amt) > 0;
2378
- const canSend = isValidAddress2(recipient) && isValidAmount(amount) && !isPending;
2379
- const handleSend = useCallback(async () => {
2380
- if (!account || !canSend) return;
2381
- setError(null);
2382
- try {
2383
- let tx;
2384
- if (tokenAddress) {
2385
- const amountInWei = BigInt(Math.floor(parseFloat(amount) * Math.pow(10, tokenDecimals)));
2386
- const transferData = `0xa9059cbb${recipient.slice(2).padStart(64, "0")}${amountInWei.toString(16).padStart(64, "0")}`;
2387
- tx = prepareTransaction({
2388
- to: tokenAddress,
2389
- data: transferData,
2390
- chain: defaultChain,
2391
- client
2392
- });
2393
- } else {
2394
- tx = prepareTransaction({
2395
- to: recipient,
2396
- value: toWei(amount),
2397
- chain: defaultChain,
2398
- client
2399
- });
2400
- }
2401
- sendTransaction(tx, {
2402
- onSuccess: (result) => {
2403
- onSuccess?.(result.transactionHash);
2404
- setRecipient("");
2405
- setAmount("");
2406
- },
2407
- onError: (err) => {
2408
- setError(err.message);
2409
- onError?.(err);
2410
- }
2411
- });
2412
- } catch (err) {
2413
- const error2 = err instanceof Error ? err : new Error("Transaction failed");
2414
- setError(error2.message);
2415
- onError?.(error2);
2416
- }
2417
- }, [account, canSend, recipient, amount, tokenAddress, tokenDecimals, defaultChain, client, sendTransaction, onSuccess, onError]);
2418
- const isDark = theme === "dark";
2419
- return /* @__PURE__ */ jsxs(
2420
- "div",
2421
- {
2422
- className,
2423
- style: {
2424
- ...containerStyle,
2425
- backgroundColor: isDark ? "#1f2937" : "#ffffff",
2426
- border: `1px solid ${isDark ? "#374151" : "#e5e7eb"}`,
2427
- ...style
2428
- },
2429
- children: [
2430
- /* @__PURE__ */ jsxs("h3", { style: { color: isDark ? "#ffffff" : "#111827", margin: 0, fontSize: "18px", fontWeight: 600 }, children: [
2431
- "Send ",
2432
- tokenSymbol
2433
- ] }),
2434
- /* @__PURE__ */ jsxs("div", { children: [
2435
- /* @__PURE__ */ jsx("label", { style: { ...labelStyle, color: isDark ? "#9ca3af" : "#6b7280" }, children: "Recipient Address" }),
2436
- /* @__PURE__ */ jsx(
2437
- "input",
2438
- {
2439
- type: "text",
2440
- value: recipient,
2441
- onChange: (e) => setRecipient(e.target.value),
2442
- placeholder: "0x...",
2443
- style: {
2444
- ...inputStyle,
2445
- backgroundColor: isDark ? "#374151" : "#f3f4f6",
2446
- color: isDark ? "#ffffff" : "#111827",
2447
- border: `1px solid ${isDark ? "#4b5563" : "#d1d5db"}`
2448
- }
2449
- }
2450
- )
2451
- ] }),
2452
- /* @__PURE__ */ jsxs("div", { children: [
2453
- /* @__PURE__ */ jsxs("label", { style: { ...labelStyle, color: isDark ? "#9ca3af" : "#6b7280" }, children: [
2454
- "Amount (",
2455
- tokenSymbol,
2456
- ")"
2457
- ] }),
2458
- /* @__PURE__ */ jsx(
2459
- "input",
2460
- {
2461
- type: "number",
2462
- value: amount,
2463
- onChange: (e) => setAmount(e.target.value),
2464
- placeholder: "0.0",
2465
- min: "0",
2466
- step: "any",
2467
- style: {
2468
- ...inputStyle,
2469
- backgroundColor: isDark ? "#374151" : "#f3f4f6",
2470
- color: isDark ? "#ffffff" : "#111827",
2471
- border: `1px solid ${isDark ? "#4b5563" : "#d1d5db"}`
2472
- }
2473
- }
2474
- )
2475
- ] }),
2476
- error && /* @__PURE__ */ jsx("div", { style: { color: "#ef4444", fontSize: "14px", padding: "8px 12px", backgroundColor: "rgba(239, 68, 68, 0.1)", borderRadius: "8px" }, children: error }),
2477
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "12px" }, children: [
2478
- onCancel && /* @__PURE__ */ jsx(
2479
- "button",
2480
- {
2481
- onClick: onCancel,
2482
- style: {
2483
- ...buttonStyle,
2484
- flex: 1,
2485
- backgroundColor: "transparent",
2486
- border: `1px solid ${isDark ? "#4b5563" : "#d1d5db"}`,
2487
- color: isDark ? "#9ca3af" : "#6b7280"
2488
- },
2489
- children: "Cancel"
2490
- }
2491
- ),
2492
- /* @__PURE__ */ jsx(
2493
- "button",
2494
- {
2495
- onClick: handleSend,
2496
- disabled: !canSend,
2497
- style: canSend ? { ...buttonStyle, flex: 1 } : { ...buttonDisabledStyle, flex: 1 },
2498
- children: isPending ? "Sending..." : `Send ${tokenSymbol}`
2499
- }
2500
- )
2501
- ] })
2502
- ]
2503
- }
2504
- );
2505
- }
2506
- function OneSendETHWidget(props) {
2507
- return /* @__PURE__ */ jsx(OneSendWidget, { ...props, tokenSymbol: "ETH", tokenDecimals: 18 });
2508
- }
2509
- function OneSendUSDCWidget(props) {
2510
- return /* @__PURE__ */ jsx(OneSendWidget, { ...props, tokenSymbol: "USDC", tokenDecimals: 6 });
2511
- }
2512
- var DEFAULT_FIATS = ["USD", "EUR", "GBP", "CNY", "JPY", "KRW", "CAD", "AUD"];
2513
- var DEFAULT_CRYPTOS = ["USDT", "USDC", "ETH", "BTC", "MATIC", "BNB", "AVAX", "SOL"];
2514
- var DEFAULT_NETWORKS = ["ethereum", "polygon", "arbitrum", "optimism", "base", "bsc", "avalanche"];
2515
- var NETWORK_DISPLAY_NAMES = {
2516
- ethereum: "Ethereum",
2517
- polygon: "Polygon",
2518
- arbitrum: "Arbitrum",
2519
- optimism: "Optimism",
2520
- base: "Base",
2521
- bsc: "BNB Chain",
2522
- avalanche: "Avalanche",
2523
- solana: "Solana"
2524
- };
2525
- var CRYPTO_RATES = {
2526
- ETH: 3500,
2527
- BTC: 95e3,
2528
- USDT: 1,
2529
- USDC: 1,
2530
- MATIC: 0.85,
2531
- BNB: 650,
2532
- AVAX: 42,
2533
- SOL: 200,
2534
- DAI: 1,
2535
- ARB: 1.2,
2536
- OP: 2.5
2537
- };
2538
- var containerStyle2 = {
2539
- display: "flex",
2540
- flexDirection: "column",
2541
- gap: "16px",
2542
- padding: "24px",
2543
- borderRadius: "16px",
2544
- border: "1px solid",
2545
- maxWidth: "420px"
2546
- };
2547
- var headerStyle = {
2548
- display: "flex",
2549
- justifyContent: "space-between",
2550
- alignItems: "center",
2551
- marginBottom: "8px"
2552
- };
2553
- var selectStyle = {
2554
- padding: "12px 16px",
2555
- borderRadius: "12px",
2556
- fontSize: "16px",
2557
- outline: "none",
2558
- cursor: "pointer",
2559
- appearance: "none",
2560
- backgroundRepeat: "no-repeat",
2561
- backgroundPosition: "right 12px center",
2562
- paddingRight: "40px"
2563
- };
2564
- var inputStyle2 = {
2565
- padding: "12px 16px",
2566
- borderRadius: "12px",
2567
- fontSize: "18px",
2568
- fontWeight: 500,
2569
- outline: "none",
2570
- width: "100%",
2571
- boxSizing: "border-box"
2572
- };
2573
- var buttonStyle2 = {
2574
- width: "100%",
2575
- padding: "16px",
2576
- border: "none",
2577
- borderRadius: "12px",
2578
- fontSize: "16px",
2579
- fontWeight: 600,
2580
- cursor: "pointer",
2581
- transition: "background-color 0.2s"
2582
- };
2583
- var rowStyle = {
2584
- display: "flex",
2585
- gap: "12px",
2586
- alignItems: "center"
2587
- };
2588
- var quoteBoxStyle = {
2589
- padding: "16px",
2590
- borderRadius: "12px",
2591
- fontSize: "14px"
2592
- };
2593
- function OneOnrampWidget({
2594
- defaultFiat = "USD",
2595
- defaultCrypto = "USDT",
2596
- defaultAmount = 100,
2597
- defaultNetwork = "base",
2598
- supportedFiats = DEFAULT_FIATS,
2599
- supportedCryptos = DEFAULT_CRYPTOS,
2600
- supportedNetworks = DEFAULT_NETWORKS,
2601
- email,
2602
- country,
2603
- theme = "dark",
2604
- accentColor = "#10b981",
2605
- className,
2606
- style,
2607
- mode = "form",
2608
- embedHeight = 600,
2609
- onSuccess,
2610
- onError,
2611
- onClose,
2612
- onQuoteUpdate
2613
- }) {
2614
- const account = useActiveAccount();
2615
- const walletAddress = account?.address;
2616
- const [fiatCurrency, setFiatCurrency] = useState(defaultFiat);
2617
- const [fiatAmount, setFiatAmount] = useState(defaultAmount.toString());
2618
- const [cryptoCurrency, setCryptoCurrency] = useState(defaultCrypto);
2619
- const [network, setNetwork] = useState(defaultNetwork);
2620
- const [isLoading, setIsLoading] = useState(false);
2621
- const [error, setError] = useState(null);
2622
- const [quote, setQuote] = useState(null);
2623
- const [widgetUrl, setWidgetUrl] = useState(null);
2624
- const isDark = theme === "dark";
2625
- const calculateQuote = useCallback(() => {
2626
- const amount = parseFloat(fiatAmount);
2627
- if (isNaN(amount) || amount <= 0) return null;
2628
- const cryptoRate = CRYPTO_RATES[cryptoCurrency.toUpperCase()] || 1;
2629
- const providerFee = amount * 0.035;
2630
- const networkFee = cryptoCurrency === "ETH" ? 5 : 1;
2631
- const totalFee = providerFee + networkFee;
2632
- const netAmount = amount - totalFee;
2633
- const cryptoAmount = netAmount / cryptoRate;
2634
- return {
2635
- fiatCurrency,
2636
- fiatAmount: amount,
2637
- cryptoCurrency,
2638
- cryptoAmount: parseFloat(cryptoAmount.toFixed(8)),
2639
- network,
2640
- rate: cryptoRate,
2641
- fees: {
2642
- network: networkFee,
2643
- provider: providerFee,
2644
- total: totalFee
2645
- },
2646
- estimatedTime: "5-15 minutes"
2647
- };
2648
- }, [fiatAmount, fiatCurrency, cryptoCurrency, network]);
2649
- useEffect(() => {
2650
- const newQuote = calculateQuote();
2651
- setQuote(newQuote);
2652
- if (newQuote) {
2653
- onQuoteUpdate?.(newQuote);
2654
- }
2655
- }, [calculateQuote, onQuoteUpdate]);
2656
- const buildWidgetUrl = useCallback(() => {
2657
- if (!walletAddress) return null;
2658
- const baseUrl = "https://buy.onramper.com";
2659
- const params = new URLSearchParams();
2660
- const apiKey = process.env.NEXT_PUBLIC_ONRAMPER_API_KEY || "";
2661
- if (apiKey) {
2662
- params.append("apiKey", apiKey);
2663
- }
2664
- params.append("wallets", `ETH:${walletAddress},MATIC:${walletAddress},BNB:${walletAddress},AVAX:${walletAddress}`);
2665
- params.append(
2666
- "networkWallets",
2667
- `ethereum:${walletAddress},polygon:${walletAddress},arbitrum:${walletAddress},optimism:${walletAddress},base:${walletAddress},bsc:${walletAddress},avalanche:${walletAddress}`
2668
- );
2669
- params.append("defaultCrypto", cryptoCurrency);
2670
- params.append("defaultFiat", fiatCurrency);
2671
- params.append("defaultAmount", fiatAmount);
2672
- params.append("mode", "buy");
2673
- if (network) {
2674
- params.append("onlyCryptoNetworks", network);
2675
- }
2676
- if (email) params.append("email", email);
2677
- if (country) params.append("country", country);
2678
- params.append("color", accentColor.replace("#", ""));
2679
- params.append("darkMode", isDark ? "true" : "false");
2680
- params.append("hideTopBar", "false");
2681
- params.append("isInAppBrowser", "true");
2682
- params.append("partnerContext", `onesdk_${Date.now()}`);
2683
- params.append("popularCryptos", "USDT,USDC,ETH,BTC");
2684
- return `${baseUrl}?${params.toString()}`;
2685
- }, [walletAddress, cryptoCurrency, fiatCurrency, fiatAmount, network, email, country, accentColor, isDark]);
2686
- const handleBuy = async () => {
2687
- if (!walletAddress) {
2688
- setError("Please connect your wallet first");
2689
- return;
2690
- }
2691
- const amount = parseFloat(fiatAmount);
2692
- if (isNaN(amount) || amount < 10) {
2693
- setError("Minimum amount is $10");
2694
- return;
2695
- }
2696
- setIsLoading(true);
2697
- setError(null);
2698
- try {
2699
- const engineUrl = getEngineUrl();
2700
- const response = await fetch(`${engineUrl}/v1/fiat/onramp`, {
2701
- method: "POST",
2702
- headers: { "Content-Type": "application/json" },
2703
- body: JSON.stringify({
2704
- walletAddress,
2705
- fiatCurrency,
2706
- fiatAmount: amount,
2707
- cryptoCurrency,
2708
- network,
2709
- email
2710
- })
2711
- });
2712
- if (response.ok) {
2713
- const data = await response.json();
2714
- if (data.success && data.data?.widgetUrl) {
2715
- setWidgetUrl(data.data.widgetUrl);
2716
- if (mode === "popup") {
2717
- window.open(data.data.widgetUrl, "_blank", "width=450,height=700");
2718
- }
2719
- return;
2720
- }
2721
- }
2722
- const directUrl = buildWidgetUrl();
2723
- if (directUrl) {
2724
- setWidgetUrl(directUrl);
2725
- if (mode === "popup") {
2726
- window.open(directUrl, "_blank", "width=450,height=700");
2727
- }
2728
- } else {
2729
- throw new Error("Failed to generate widget URL");
2730
- }
2731
- } catch (err) {
2732
- const error2 = err instanceof Error ? err : new Error("Failed to start purchase");
2733
- setError(error2.message);
2734
- onError?.(error2);
2735
- } finally {
2736
- setIsLoading(false);
2737
- }
2738
- };
2739
- const handleCloseEmbed = () => {
2740
- setWidgetUrl(null);
2741
- onClose?.();
2742
- };
2743
- const bgColor = isDark ? "#1f2937" : "#ffffff";
2744
- const borderColor = isDark ? "#374151" : "#e5e7eb";
2745
- const textColor = isDark ? "#ffffff" : "#111827";
2746
- const mutedColor = isDark ? "#9ca3af" : "#6b7280";
2747
- const inputBg = isDark ? "#374151" : "#f3f4f6";
2748
- const quoteBg = isDark ? "#374151" : "#f3f4f6";
2749
- if (mode === "embed" && widgetUrl) {
2750
- return /* @__PURE__ */ jsxs("div", { className, style: { ...style }, children: [
2751
- /* @__PURE__ */ jsx("div", { style: { display: "flex", justifyContent: "flex-end", marginBottom: "8px" }, children: /* @__PURE__ */ jsx(
2752
- "button",
2753
- {
2754
- onClick: handleCloseEmbed,
2755
- style: {
2756
- background: "none",
2757
- border: "none",
2758
- color: mutedColor,
2759
- cursor: "pointer",
2760
- fontSize: "14px"
2761
- },
2762
- children: "Close"
2763
- }
2764
- ) }),
2765
- /* @__PURE__ */ jsx(
2766
- "iframe",
2767
- {
2768
- src: widgetUrl,
2769
- width: "100%",
2770
- height: embedHeight,
2771
- style: { border: "none", borderRadius: "16px" },
2772
- allow: "payment; clipboard-read; clipboard-write"
2773
- }
2774
- )
2775
- ] });
2776
- }
2777
- return /* @__PURE__ */ jsxs(
2778
- "div",
2779
- {
2780
- className,
2781
- style: {
2782
- ...containerStyle2,
2783
- backgroundColor: bgColor,
2784
- borderColor,
2785
- ...style
2786
- },
2787
- children: [
2788
- /* @__PURE__ */ jsxs("div", { style: headerStyle, children: [
2789
- /* @__PURE__ */ jsx("h3", { style: { color: textColor, margin: 0, fontSize: "18px", fontWeight: 600 }, children: "Buy Crypto" }),
2790
- /* @__PURE__ */ jsx("span", { style: { color: mutedColor, fontSize: "12px" }, children: "Powered by Onramper" })
2791
- ] }),
2792
- /* @__PURE__ */ jsxs("div", { children: [
2793
- /* @__PURE__ */ jsx("label", { style: { color: mutedColor, fontSize: "14px", marginBottom: "8px", display: "block" }, children: "You Pay" }),
2794
- /* @__PURE__ */ jsxs("div", { style: rowStyle, children: [
2795
- /* @__PURE__ */ jsx(
2796
- "input",
2797
- {
2798
- type: "number",
2799
- value: fiatAmount,
2800
- onChange: (e) => setFiatAmount(e.target.value),
2801
- placeholder: "0",
2802
- min: "10",
2803
- style: {
2804
- ...inputStyle2,
2805
- flex: 1,
2806
- backgroundColor: inputBg,
2807
- border: `1px solid ${borderColor}`,
2808
- color: textColor
2809
- }
2810
- }
2811
- ),
2812
- /* @__PURE__ */ jsx(
2813
- "select",
2814
- {
2815
- value: fiatCurrency,
2816
- onChange: (e) => setFiatCurrency(e.target.value),
2817
- style: {
2818
- ...selectStyle,
2819
- backgroundColor: inputBg,
2820
- border: `1px solid ${borderColor}`,
2821
- color: textColor,
2822
- minWidth: "100px",
2823
- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='${isDark ? "%239ca3af" : "%236b7280"}'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E")`,
2824
- backgroundSize: "16px"
2825
- },
2826
- children: supportedFiats.map((fiat) => /* @__PURE__ */ jsx("option", { value: fiat, children: fiat }, fiat))
2827
- }
2828
- )
2829
- ] })
2830
- ] }),
2831
- /* @__PURE__ */ jsxs("div", { children: [
2832
- /* @__PURE__ */ jsx("label", { style: { color: mutedColor, fontSize: "14px", marginBottom: "8px", display: "block" }, children: "You Receive" }),
2833
- /* @__PURE__ */ jsxs("div", { style: rowStyle, children: [
2834
- /* @__PURE__ */ jsx(
2835
- "div",
2836
- {
2837
- style: {
2838
- ...inputStyle2,
2839
- flex: 1,
2840
- backgroundColor: inputBg,
2841
- border: `1px solid ${borderColor}`,
2842
- color: textColor,
2843
- display: "flex",
2844
- alignItems: "center"
2845
- },
2846
- children: /* @__PURE__ */ jsx("span", { style: { color: quote ? textColor : mutedColor }, children: quote ? `~${quote.cryptoAmount.toFixed(6)}` : "0.00" })
2847
- }
2848
- ),
2849
- /* @__PURE__ */ jsx(
2850
- "select",
2851
- {
2852
- value: cryptoCurrency,
2853
- onChange: (e) => setCryptoCurrency(e.target.value),
2854
- style: {
2855
- ...selectStyle,
2856
- backgroundColor: inputBg,
2857
- border: `1px solid ${borderColor}`,
2858
- color: textColor,
2859
- minWidth: "100px",
2860
- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='${isDark ? "%239ca3af" : "%236b7280"}'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E")`,
2861
- backgroundSize: "16px"
2862
- },
2863
- children: supportedCryptos.map((crypto) => /* @__PURE__ */ jsx("option", { value: crypto, children: crypto }, crypto))
2864
- }
2865
- )
2866
- ] })
2867
- ] }),
2868
- /* @__PURE__ */ jsxs("div", { children: [
2869
- /* @__PURE__ */ jsx("label", { style: { color: mutedColor, fontSize: "14px", marginBottom: "8px", display: "block" }, children: "Network" }),
2870
- /* @__PURE__ */ jsx(
2871
- "select",
2872
- {
2873
- value: network,
2874
- onChange: (e) => setNetwork(e.target.value),
2875
- style: {
2876
- ...selectStyle,
2877
- width: "100%",
2878
- backgroundColor: inputBg,
2879
- border: `1px solid ${borderColor}`,
2880
- color: textColor,
2881
- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='${isDark ? "%239ca3af" : "%236b7280"}'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E")`,
2882
- backgroundSize: "16px"
2883
- },
2884
- children: supportedNetworks.map((net) => /* @__PURE__ */ jsx("option", { value: net, children: NETWORK_DISPLAY_NAMES[net] || net }, net))
2885
- }
2886
- )
2887
- ] }),
2888
- quote && /* @__PURE__ */ jsxs("div", { style: { ...quoteBoxStyle, backgroundColor: quoteBg }, children: [
2889
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: "8px" }, children: [
2890
- /* @__PURE__ */ jsx("span", { style: { color: mutedColor }, children: "Rate" }),
2891
- /* @__PURE__ */ jsxs("span", { style: { color: textColor }, children: [
2892
- "1 ",
2893
- cryptoCurrency,
2894
- " = $",
2895
- quote.rate.toLocaleString()
2896
- ] })
2897
- ] }),
2898
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: "8px" }, children: [
2899
- /* @__PURE__ */ jsx("span", { style: { color: mutedColor }, children: "Fees" }),
2900
- /* @__PURE__ */ jsxs("span", { style: { color: textColor }, children: [
2901
- "~$",
2902
- quote.fees.total.toFixed(2)
2903
- ] })
2904
- ] }),
2905
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between" }, children: [
2906
- /* @__PURE__ */ jsx("span", { style: { color: mutedColor }, children: "Est. Time" }),
2907
- /* @__PURE__ */ jsx("span", { style: { color: textColor }, children: quote.estimatedTime })
2908
- ] })
2909
- ] }),
2910
- error && /* @__PURE__ */ jsx("div", { style: {
2911
- color: "#ef4444",
2912
- fontSize: "14px",
2913
- padding: "12px",
2914
- backgroundColor: "rgba(239, 68, 68, 0.1)",
2915
- borderRadius: "8px"
2916
- }, children: error }),
2917
- /* @__PURE__ */ jsx(
2918
- "button",
2919
- {
2920
- onClick: handleBuy,
2921
- disabled: isLoading || !walletAddress,
2922
- style: {
2923
- ...buttonStyle2,
2924
- backgroundColor: isLoading || !walletAddress ? "#6b7280" : accentColor,
2925
- color: "#ffffff",
2926
- cursor: isLoading || !walletAddress ? "not-allowed" : "pointer"
2927
- },
2928
- children: isLoading ? "Loading..." : !walletAddress ? "Connect Wallet" : `Buy ${cryptoCurrency}`
2929
- }
2930
- ),
2931
- walletAddress && /* @__PURE__ */ jsxs("div", { style: { textAlign: "center", color: mutedColor, fontSize: "12px" }, children: [
2932
- "Receiving to: ",
2933
- walletAddress.slice(0, 6),
2934
- "...",
2935
- walletAddress.slice(-4)
2936
- ] })
2937
- ]
2938
- }
2939
- );
2940
- }
2941
- function OneBuyUSDTWidget(props) {
2942
- return /* @__PURE__ */ jsx(OneOnrampWidget, { ...props, defaultCrypto: "USDT" });
2943
- }
2944
- function OneBuyUSDCWidget(props) {
2945
- return /* @__PURE__ */ jsx(OneOnrampWidget, { ...props, defaultCrypto: "USDC" });
2946
- }
2947
- function OneBuyETHWidget(props) {
2948
- return /* @__PURE__ */ jsx(OneOnrampWidget, { ...props, defaultCrypto: "ETH" });
2949
- }
2950
- function OneBuyBTCWidget(props) {
2951
- return /* @__PURE__ */ jsx(OneOnrampWidget, { ...props, defaultCrypto: "BTC" });
2952
- }
2953
- var DEFAULT_FIATS2 = ["USD", "EUR", "GBP", "CNY", "JPY", "KRW", "CAD", "AUD"];
2954
- var DEFAULT_CRYPTOS2 = ["USDT", "USDC", "ETH", "BTC", "MATIC", "BNB"];
2955
- var DEFAULT_NETWORKS2 = ["ethereum", "polygon", "arbitrum", "optimism", "base", "bsc", "avalanche"];
2956
- var NETWORK_DISPLAY_NAMES2 = {
2957
- ethereum: "Ethereum",
2958
- polygon: "Polygon",
2959
- arbitrum: "Arbitrum",
2960
- optimism: "Optimism",
2961
- base: "Base",
2962
- bsc: "BNB Chain",
2963
- avalanche: "Avalanche",
2964
- solana: "Solana"
2965
- };
2966
- var CRYPTO_RATES2 = {
2967
- ETH: 3500,
2968
- BTC: 95e3,
2969
- USDT: 1,
2970
- USDC: 1,
2971
- MATIC: 0.85,
2972
- BNB: 650,
2973
- AVAX: 42,
2974
- SOL: 200,
2975
- DAI: 1
2976
- };
2977
- var containerStyle3 = {
2978
- display: "flex",
2979
- flexDirection: "column",
2980
- gap: "16px",
2981
- padding: "24px",
2982
- borderRadius: "16px",
2983
- border: "1px solid",
2984
- maxWidth: "420px"
2985
- };
2986
- var headerStyle2 = {
2987
- display: "flex",
2988
- justifyContent: "space-between",
2989
- alignItems: "center",
2990
- marginBottom: "8px"
2991
- };
2992
- var selectStyle2 = {
2993
- padding: "12px 16px",
2994
- borderRadius: "12px",
2995
- fontSize: "16px",
2996
- outline: "none",
2997
- cursor: "pointer",
2998
- appearance: "none",
2999
- backgroundRepeat: "no-repeat",
3000
- backgroundPosition: "right 12px center",
3001
- paddingRight: "40px"
3002
- };
3003
- var inputStyle3 = {
3004
- padding: "12px 16px",
3005
- borderRadius: "12px",
3006
- fontSize: "18px",
3007
- fontWeight: 500,
3008
- outline: "none",
3009
- width: "100%",
3010
- boxSizing: "border-box"
3011
- };
3012
- var buttonStyle3 = {
3013
- width: "100%",
3014
- padding: "16px",
3015
- border: "none",
3016
- borderRadius: "12px",
3017
- fontSize: "16px",
3018
- fontWeight: 600,
3019
- cursor: "pointer",
3020
- transition: "background-color 0.2s"
3021
- };
3022
- var rowStyle2 = {
3023
- display: "flex",
3024
- gap: "12px",
3025
- alignItems: "center"
3026
- };
3027
- var quoteBoxStyle2 = {
3028
- padding: "16px",
3029
- borderRadius: "12px",
3030
- fontSize: "14px"
3031
- };
3032
- var balanceStyle = {
3033
- display: "flex",
3034
- justifyContent: "space-between",
3035
- fontSize: "12px",
3036
- marginTop: "4px"
3037
- };
3038
- function OneOfframpWidget({
3039
- defaultFiat = "USD",
3040
- defaultCrypto = "USDT",
3041
- defaultAmount = "",
3042
- defaultNetwork = "base",
3043
- supportedFiats = DEFAULT_FIATS2,
3044
- supportedCryptos = DEFAULT_CRYPTOS2,
3045
- supportedNetworks = DEFAULT_NETWORKS2,
3046
- email,
3047
- country,
3048
- theme = "dark",
3049
- accentColor = "#ef4444",
3050
- // Red for sell
3051
- className,
3052
- style,
3053
- mode = "form",
3054
- embedHeight = 600,
3055
- onSuccess,
3056
- onError,
3057
- onClose,
3058
- onQuoteUpdate
3059
- }) {
3060
- const client = useThirdwebClient();
3061
- const account = useActiveAccount();
3062
- const walletAddress = account?.address;
3063
- const { data: balanceData } = useWalletBalance({
3064
- client,
3065
- chain: base,
3066
- address: walletAddress
3067
- });
3068
- const [cryptoCurrency, setCryptoCurrency] = useState(defaultCrypto);
3069
- const [cryptoAmount, setCryptoAmount] = useState(defaultAmount);
3070
- const [fiatCurrency, setFiatCurrency] = useState(defaultFiat);
3071
- const [network, setNetwork] = useState(defaultNetwork);
3072
- const [isLoading, setIsLoading] = useState(false);
3073
- const [error, setError] = useState(null);
3074
- const [quote, setQuote] = useState(null);
3075
- const [widgetUrl, setWidgetUrl] = useState(null);
3076
- const isDark = theme === "dark";
3077
- const calculateQuote = useCallback(() => {
3078
- const amount = parseFloat(cryptoAmount);
3079
- if (isNaN(amount) || amount <= 0) return null;
3080
- const cryptoRate = CRYPTO_RATES2[cryptoCurrency.toUpperCase()] || 1;
3081
- const grossAmount = amount * cryptoRate;
3082
- const providerFee = grossAmount * 0.025;
3083
- const networkFee = cryptoCurrency === "ETH" ? 5 : 1;
3084
- const totalFee = providerFee + networkFee;
3085
- const netAmount = grossAmount - totalFee;
3086
- return {
3087
- cryptoCurrency,
3088
- cryptoAmount: amount,
3089
- fiatCurrency,
3090
- fiatAmount: parseFloat(netAmount.toFixed(2)),
3091
- network,
3092
- rate: cryptoRate,
3093
- fees: {
3094
- network: networkFee,
3095
- provider: providerFee,
3096
- total: totalFee
3097
- },
3098
- estimatedTime: "1-3 business days"
3099
- };
3100
- }, [cryptoAmount, cryptoCurrency, fiatCurrency, network]);
3101
- useEffect(() => {
3102
- const newQuote = calculateQuote();
3103
- setQuote(newQuote);
3104
- if (newQuote) {
3105
- onQuoteUpdate?.(newQuote);
3106
- }
3107
- }, [calculateQuote, onQuoteUpdate]);
3108
- const buildWidgetUrl = useCallback(() => {
3109
- if (!walletAddress) return null;
3110
- const baseUrl = "https://buy.onramper.com";
3111
- const params = new URLSearchParams();
3112
- const apiKey = process.env.NEXT_PUBLIC_ONRAMPER_API_KEY || "";
3113
- if (apiKey) {
3114
- params.append("apiKey", apiKey);
3115
- }
3116
- params.append("wallets", `ETH:${walletAddress},MATIC:${walletAddress},BNB:${walletAddress}`);
3117
- params.append(
3118
- "networkWallets",
3119
- `ethereum:${walletAddress},polygon:${walletAddress},arbitrum:${walletAddress},optimism:${walletAddress},base:${walletAddress},bsc:${walletAddress}`
3120
- );
3121
- params.append("mode", "sell");
3122
- params.append("defaultCrypto", cryptoCurrency);
3123
- params.append("defaultFiat", fiatCurrency);
3124
- if (cryptoAmount) {
3125
- params.append("sellDefaultAmount", cryptoAmount);
3126
- }
3127
- if (network) {
3128
- params.append("onlyCryptoNetworks", network);
3129
- }
3130
- if (email) params.append("email", email);
3131
- if (country) params.append("country", country);
3132
- params.append("color", accentColor.replace("#", ""));
3133
- params.append("darkMode", isDark ? "true" : "false");
3134
- params.append("hideTopBar", "false");
3135
- params.append("isInAppBrowser", "true");
3136
- params.append("partnerContext", `onesdk_sell_${Date.now()}`);
3137
- return `${baseUrl}?${params.toString()}`;
3138
- }, [walletAddress, cryptoCurrency, fiatCurrency, cryptoAmount, network, email, country, accentColor, isDark]);
3139
- const handleSell = async () => {
3140
- if (!walletAddress) {
3141
- setError("Please connect your wallet first");
3142
- return;
3143
- }
3144
- const amount = parseFloat(cryptoAmount);
3145
- if (isNaN(amount) || amount <= 0) {
3146
- setError("Please enter a valid amount");
3147
- return;
3148
- }
3149
- if (balanceData && cryptoCurrency === "ETH") {
3150
- const balance = parseFloat(balanceData.displayValue);
3151
- if (amount > balance) {
3152
- setError(`Insufficient balance. You have ${balance.toFixed(4)} ${cryptoCurrency}`);
3153
- return;
3154
- }
3155
- }
3156
- setIsLoading(true);
3157
- setError(null);
3158
- try {
3159
- const engineUrl = getEngineUrl();
3160
- const response = await fetch(`${engineUrl}/v1/fiat/offramp`, {
3161
- method: "POST",
3162
- headers: { "Content-Type": "application/json" },
3163
- body: JSON.stringify({
3164
- walletAddress,
3165
- cryptoCurrency,
3166
- cryptoAmount: amount,
3167
- fiatCurrency,
3168
- network,
3169
- email
3170
- })
3171
- });
3172
- if (response.ok) {
3173
- const data = await response.json();
3174
- if (data.success && data.data?.widgetUrl) {
3175
- setWidgetUrl(data.data.widgetUrl);
3176
- if (mode === "popup") {
3177
- window.open(data.data.widgetUrl, "_blank", "width=450,height=700");
3178
- }
3179
- return;
3180
- }
3181
- }
3182
- const directUrl = buildWidgetUrl();
3183
- if (directUrl) {
3184
- setWidgetUrl(directUrl);
3185
- if (mode === "popup") {
3186
- window.open(directUrl, "_blank", "width=450,height=700");
3187
- }
3188
- } else {
3189
- throw new Error("Failed to generate widget URL");
3190
- }
3191
- } catch (err) {
3192
- const error2 = err instanceof Error ? err : new Error("Failed to start sale");
3193
- setError(error2.message);
3194
- onError?.(error2);
3195
- } finally {
3196
- setIsLoading(false);
3197
- }
3198
- };
3199
- const handleUseMax = () => {
3200
- if (balanceData && cryptoCurrency === "ETH") {
3201
- const balance = parseFloat(balanceData.displayValue);
3202
- const maxAmount = Math.max(0, balance - 5e-3);
3203
- setCryptoAmount(maxAmount.toFixed(6));
3204
- }
3205
- };
3206
- const handleCloseEmbed = () => {
3207
- setWidgetUrl(null);
3208
- onClose?.();
3209
- };
3210
- const bgColor = isDark ? "#1f2937" : "#ffffff";
3211
- const borderColor = isDark ? "#374151" : "#e5e7eb";
3212
- const textColor = isDark ? "#ffffff" : "#111827";
3213
- const mutedColor = isDark ? "#9ca3af" : "#6b7280";
3214
- const inputBg = isDark ? "#374151" : "#f3f4f6";
3215
- const quoteBg = isDark ? "#374151" : "#f3f4f6";
3216
- if (mode === "embed" && widgetUrl) {
3217
- return /* @__PURE__ */ jsxs("div", { className, style: { ...style }, children: [
3218
- /* @__PURE__ */ jsx("div", { style: { display: "flex", justifyContent: "flex-end", marginBottom: "8px" }, children: /* @__PURE__ */ jsx(
3219
- "button",
3220
- {
3221
- onClick: handleCloseEmbed,
3222
- style: {
3223
- background: "none",
3224
- border: "none",
3225
- color: mutedColor,
3226
- cursor: "pointer",
3227
- fontSize: "14px"
3228
- },
3229
- children: "Close"
3230
- }
3231
- ) }),
3232
- /* @__PURE__ */ jsx(
3233
- "iframe",
3234
- {
3235
- src: widgetUrl,
3236
- width: "100%",
3237
- height: embedHeight,
3238
- style: { border: "none", borderRadius: "16px" },
3239
- allow: "payment; clipboard-read; clipboard-write"
3240
- }
3241
- )
3242
- ] });
3243
- }
3244
- return /* @__PURE__ */ jsxs(
3245
- "div",
3246
- {
3247
- className,
3248
- style: {
3249
- ...containerStyle3,
3250
- backgroundColor: bgColor,
3251
- borderColor,
3252
- ...style
3253
- },
3254
- children: [
3255
- /* @__PURE__ */ jsxs("div", { style: headerStyle2, children: [
3256
- /* @__PURE__ */ jsx("h3", { style: { color: textColor, margin: 0, fontSize: "18px", fontWeight: 600 }, children: "Sell Crypto" }),
3257
- /* @__PURE__ */ jsx("span", { style: { color: mutedColor, fontSize: "12px" }, children: "Cash out to bank" })
3258
- ] }),
3259
- /* @__PURE__ */ jsxs("div", { children: [
3260
- /* @__PURE__ */ jsx("label", { style: { color: mutedColor, fontSize: "14px", marginBottom: "8px", display: "block" }, children: "You Sell" }),
3261
- /* @__PURE__ */ jsxs("div", { style: rowStyle2, children: [
3262
- /* @__PURE__ */ jsx(
3263
- "input",
3264
- {
3265
- type: "number",
3266
- value: cryptoAmount,
3267
- onChange: (e) => setCryptoAmount(e.target.value),
3268
- placeholder: "0.0",
3269
- min: "0",
3270
- step: "any",
3271
- style: {
3272
- ...inputStyle3,
3273
- flex: 1,
3274
- backgroundColor: inputBg,
3275
- border: `1px solid ${borderColor}`,
3276
- color: textColor
3277
- }
3278
- }
3279
- ),
3280
- /* @__PURE__ */ jsx(
3281
- "select",
3282
- {
3283
- value: cryptoCurrency,
3284
- onChange: (e) => setCryptoCurrency(e.target.value),
3285
- style: {
3286
- ...selectStyle2,
3287
- backgroundColor: inputBg,
3288
- border: `1px solid ${borderColor}`,
3289
- color: textColor,
3290
- minWidth: "100px",
3291
- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='${isDark ? "%239ca3af" : "%236b7280"}'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E")`,
3292
- backgroundSize: "16px"
3293
- },
3294
- children: supportedCryptos.map((crypto) => /* @__PURE__ */ jsx("option", { value: crypto, children: crypto }, crypto))
3295
- }
3296
- )
3297
- ] }),
3298
- balanceData && cryptoCurrency === "ETH" && /* @__PURE__ */ jsxs("div", { style: balanceStyle, children: [
3299
- /* @__PURE__ */ jsxs("span", { style: { color: mutedColor }, children: [
3300
- "Balance: ",
3301
- parseFloat(balanceData.displayValue).toFixed(4),
3302
- " ETH"
3303
- ] }),
3304
- /* @__PURE__ */ jsx(
3305
- "button",
3306
- {
3307
- onClick: handleUseMax,
3308
- style: {
3309
- background: "none",
3310
- border: "none",
3311
- color: accentColor,
3312
- cursor: "pointer",
3313
- fontSize: "12px",
3314
- padding: 0
3315
- },
3316
- children: "Use Max"
3317
- }
3318
- )
3319
- ] })
3320
- ] }),
3321
- /* @__PURE__ */ jsxs("div", { children: [
3322
- /* @__PURE__ */ jsx("label", { style: { color: mutedColor, fontSize: "14px", marginBottom: "8px", display: "block" }, children: "Network" }),
3323
- /* @__PURE__ */ jsx(
3324
- "select",
3325
- {
3326
- value: network,
3327
- onChange: (e) => setNetwork(e.target.value),
3328
- style: {
3329
- ...selectStyle2,
3330
- width: "100%",
3331
- backgroundColor: inputBg,
3332
- border: `1px solid ${borderColor}`,
3333
- color: textColor,
3334
- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='${isDark ? "%239ca3af" : "%236b7280"}'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E")`,
3335
- backgroundSize: "16px"
3336
- },
3337
- children: supportedNetworks.map((net) => /* @__PURE__ */ jsx("option", { value: net, children: NETWORK_DISPLAY_NAMES2[net] || net }, net))
3338
- }
3339
- )
3340
- ] }),
3341
- /* @__PURE__ */ jsxs("div", { children: [
3342
- /* @__PURE__ */ jsx("label", { style: { color: mutedColor, fontSize: "14px", marginBottom: "8px", display: "block" }, children: "You Receive" }),
3343
- /* @__PURE__ */ jsxs("div", { style: rowStyle2, children: [
3344
- /* @__PURE__ */ jsx(
3345
- "div",
3346
- {
3347
- style: {
3348
- ...inputStyle3,
3349
- flex: 1,
3350
- backgroundColor: inputBg,
3351
- border: `1px solid ${borderColor}`,
3352
- color: textColor,
3353
- display: "flex",
3354
- alignItems: "center"
3355
- },
3356
- children: /* @__PURE__ */ jsx("span", { style: { color: quote ? textColor : mutedColor }, children: quote ? `~$${quote.fiatAmount.toLocaleString()}` : "$0.00" })
3357
- }
3358
- ),
3359
- /* @__PURE__ */ jsx(
3360
- "select",
3361
- {
3362
- value: fiatCurrency,
3363
- onChange: (e) => setFiatCurrency(e.target.value),
3364
- style: {
3365
- ...selectStyle2,
3366
- backgroundColor: inputBg,
3367
- border: `1px solid ${borderColor}`,
3368
- color: textColor,
3369
- minWidth: "100px",
3370
- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='${isDark ? "%239ca3af" : "%236b7280"}'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E")`,
3371
- backgroundSize: "16px"
3372
- },
3373
- children: supportedFiats.map((fiat) => /* @__PURE__ */ jsx("option", { value: fiat, children: fiat }, fiat))
3374
- }
3375
- )
3376
- ] })
3377
- ] }),
3378
- quote && /* @__PURE__ */ jsxs("div", { style: { ...quoteBoxStyle2, backgroundColor: quoteBg }, children: [
3379
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: "8px" }, children: [
3380
- /* @__PURE__ */ jsx("span", { style: { color: mutedColor }, children: "Rate" }),
3381
- /* @__PURE__ */ jsxs("span", { style: { color: textColor }, children: [
3382
- "1 ",
3383
- cryptoCurrency,
3384
- " = $",
3385
- quote.rate.toLocaleString()
3386
- ] })
3387
- ] }),
3388
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: "8px" }, children: [
3389
- /* @__PURE__ */ jsx("span", { style: { color: mutedColor }, children: "Fees" }),
3390
- /* @__PURE__ */ jsxs("span", { style: { color: textColor }, children: [
3391
- "~$",
3392
- quote.fees.total.toFixed(2)
3393
- ] })
3394
- ] }),
3395
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between" }, children: [
3396
- /* @__PURE__ */ jsx("span", { style: { color: mutedColor }, children: "Est. Arrival" }),
3397
- /* @__PURE__ */ jsx("span", { style: { color: textColor }, children: quote.estimatedTime })
3398
- ] })
3399
- ] }),
3400
- /* @__PURE__ */ jsx("div", { style: {
3401
- padding: "12px",
3402
- backgroundColor: isDark ? "rgba(251, 191, 36, 0.1)" : "rgba(251, 191, 36, 0.15)",
3403
- borderRadius: "8px",
3404
- fontSize: "12px",
3405
- color: "#fbbf24"
3406
- }, children: "Bank transfers typically take 1-3 business days. KYC verification may be required." }),
3407
- error && /* @__PURE__ */ jsx("div", { style: {
3408
- color: "#ef4444",
3409
- fontSize: "14px",
3410
- padding: "12px",
3411
- backgroundColor: "rgba(239, 68, 68, 0.1)",
3412
- borderRadius: "8px"
3413
- }, children: error }),
3414
- /* @__PURE__ */ jsx(
3415
- "button",
3416
- {
3417
- onClick: handleSell,
3418
- disabled: isLoading || !walletAddress,
3419
- style: {
3420
- ...buttonStyle3,
3421
- backgroundColor: isLoading || !walletAddress ? "#6b7280" : accentColor,
3422
- color: "#ffffff",
3423
- cursor: isLoading || !walletAddress ? "not-allowed" : "pointer"
3424
- },
3425
- children: isLoading ? "Loading..." : !walletAddress ? "Connect Wallet" : `Sell ${cryptoCurrency}`
3426
- }
3427
- ),
3428
- walletAddress && /* @__PURE__ */ jsxs("div", { style: { textAlign: "center", color: mutedColor, fontSize: "12px" }, children: [
3429
- "Selling from: ",
3430
- walletAddress.slice(0, 6),
3431
- "...",
3432
- walletAddress.slice(-4)
3433
- ] })
3434
- ]
3435
- }
3436
- );
3437
- }
3438
- function OneSellUSDTWidget(props) {
3439
- return /* @__PURE__ */ jsx(OneOfframpWidget, { ...props, defaultCrypto: "USDT" });
3440
- }
3441
- function OneSellUSDCWidget(props) {
3442
- return /* @__PURE__ */ jsx(OneOfframpWidget, { ...props, defaultCrypto: "USDC" });
3443
- }
3444
- function OneSellETHWidget(props) {
3445
- return /* @__PURE__ */ jsx(OneOfframpWidget, { ...props, defaultCrypto: "ETH" });
3446
- }
3447
- var CHAIN_CONFIGS2 = [
3448
- { chain: ethereum, name: "Ethereum", shortName: "ETH", nativeToken: "ETH" },
3449
- { chain: base, name: "Base", shortName: "BASE", nativeToken: "ETH" },
3450
- { chain: arbitrum, name: "Arbitrum", shortName: "ARB", nativeToken: "ETH" },
3451
- { chain: optimism, name: "Optimism", shortName: "OP", nativeToken: "ETH" },
3452
- { chain: polygon, name: "Polygon", shortName: "MATIC", nativeToken: "POL" },
3453
- { chain: bsc, name: "BNB Chain", shortName: "BSC", nativeToken: "BNB" },
3454
- { chain: avalanche, name: "Avalanche", shortName: "AVAX", nativeToken: "AVAX" }
3455
- ];
3456
- var TOKENS_BY_CHAIN = {
3457
- // Ethereum
3458
- 1: [
3459
- { address: "0x0000000000000000000000000000000000000000", symbol: "ETH", name: "Ethereum", decimals: 18, chainId: 1 },
3460
- { address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", symbol: "USDC", name: "USD Coin", decimals: 6, chainId: 1 },
3461
- { address: "0xdAC17F958D2ee523a2206206994597C13D831ec7", symbol: "USDT", name: "Tether", decimals: 6, chainId: 1 },
3462
- { address: "0x6B175474E89094C44Da98b954EescdeCB5", symbol: "DAI", name: "Dai", decimals: 18, chainId: 1 },
3463
- { address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", symbol: "WETH", name: "Wrapped Ether", decimals: 18, chainId: 1 }
3464
- ],
3465
- // Base
3466
- 8453: [
3467
- { address: "0x0000000000000000000000000000000000000000", symbol: "ETH", name: "Ethereum", decimals: 18, chainId: 8453 },
3468
- { address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", symbol: "USDC", name: "USD Coin", decimals: 6, chainId: 8453 },
3469
- { address: "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb", symbol: "DAI", name: "Dai", decimals: 18, chainId: 8453 },
3470
- { address: "0x4200000000000000000000000000000000000006", symbol: "WETH", name: "Wrapped Ether", decimals: 18, chainId: 8453 }
3471
- ],
3472
- // Arbitrum
3473
- 42161: [
3474
- { address: "0x0000000000000000000000000000000000000000", symbol: "ETH", name: "Ethereum", decimals: 18, chainId: 42161 },
3475
- { address: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", symbol: "USDC", name: "USD Coin", decimals: 6, chainId: 42161 },
3476
- { address: "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9", symbol: "USDT", name: "Tether", decimals: 6, chainId: 42161 },
3477
- { address: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1", symbol: "WETH", name: "Wrapped Ether", decimals: 18, chainId: 42161 }
3478
- ],
3479
- // Optimism
3480
- 10: [
3481
- { address: "0x0000000000000000000000000000000000000000", symbol: "ETH", name: "Ethereum", decimals: 18, chainId: 10 },
3482
- { address: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85", symbol: "USDC", name: "USD Coin", decimals: 6, chainId: 10 },
3483
- { address: "0x94b008aA00579c1307B0EF2c499aD98a8ce58e58", symbol: "USDT", name: "Tether", decimals: 6, chainId: 10 },
3484
- { address: "0x4200000000000000000000000000000000000006", symbol: "WETH", name: "Wrapped Ether", decimals: 18, chainId: 10 }
3485
- ],
3486
- // Polygon
3487
- 137: [
3488
- { address: "0x0000000000000000000000000000000000000000", symbol: "POL", name: "Polygon", decimals: 18, chainId: 137 },
3489
- { address: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", symbol: "USDC", name: "USD Coin", decimals: 6, chainId: 137 },
3490
- { address: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F", symbol: "USDT", name: "Tether", decimals: 6, chainId: 137 },
3491
- { address: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619", symbol: "WETH", name: "Wrapped Ether", decimals: 18, chainId: 137 }
3492
- ],
3493
- // BSC
3494
- 56: [
3495
- { address: "0x0000000000000000000000000000000000000000", symbol: "BNB", name: "BNB", decimals: 18, chainId: 56 },
3496
- { address: "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d", symbol: "USDC", name: "USD Coin", decimals: 18, chainId: 56 },
3497
- { address: "0x55d398326f99059fF775485246999027B3197955", symbol: "USDT", name: "Tether", decimals: 18, chainId: 56 },
3498
- { address: "0x2170Ed0880ac9A755fd29B2688956BD959F933F8", symbol: "ETH", name: "Ethereum", decimals: 18, chainId: 56 }
3499
- ],
3500
- // Avalanche
3501
- 43114: [
3502
- { address: "0x0000000000000000000000000000000000000000", symbol: "AVAX", name: "Avalanche", decimals: 18, chainId: 43114 },
3503
- { address: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E", symbol: "USDC", name: "USD Coin", decimals: 6, chainId: 43114 },
3504
- { address: "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7", symbol: "USDT", name: "Tether", decimals: 6, chainId: 43114 },
3505
- { address: "0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB", symbol: "WETH", name: "Wrapped Ether", decimals: 18, chainId: 43114 }
3506
- ]
3507
- };
3508
- var containerStyle4 = {
3509
- display: "flex",
3510
- flexDirection: "column",
3511
- gap: "16px",
3512
- padding: "24px",
3513
- borderRadius: "16px",
3514
- border: "1px solid",
3515
- maxWidth: "420px"
3516
- };
3517
- var chainSelectorStyle = {
3518
- display: "flex",
3519
- gap: "8px",
3520
- alignItems: "center"
3521
- };
3522
- var tokenInputStyle = {
3523
- display: "flex",
3524
- flexDirection: "column",
3525
- gap: "8px",
3526
- padding: "16px",
3527
- borderRadius: "12px"
3528
- };
3529
- var inputStyle4 = {
3530
- width: "100%",
3531
- padding: "8px 0",
3532
- backgroundColor: "transparent",
3533
- border: "none",
3534
- fontSize: "24px",
3535
- fontWeight: 600,
3536
- outline: "none"
3537
- };
3538
- var selectStyle3 = {
3539
- padding: "8px 12px",
3540
- border: "none",
3541
- borderRadius: "8px",
3542
- fontSize: "14px",
3543
- fontWeight: 500,
3544
- cursor: "pointer",
3545
- appearance: "none",
3546
- backgroundRepeat: "no-repeat",
3547
- backgroundPosition: "right 8px center",
3548
- paddingRight: "28px"
3549
- };
3550
- var buttonStyle4 = {
3551
- width: "100%",
3552
- padding: "16px",
3553
- border: "none",
3554
- borderRadius: "12px",
3555
- fontSize: "16px",
3556
- fontWeight: 600,
3557
- cursor: "pointer",
3558
- transition: "background-color 0.2s"
3559
- };
3560
- var routeBoxStyle = {
3561
- padding: "12px",
3562
- borderRadius: "8px",
3563
- fontSize: "13px"
3564
- };
3565
- var labelStyle2 = {
3566
- fontSize: "12px",
3567
- marginBottom: "4px"
3568
- };
3569
- function OneSwapWidget({
3570
- defaultFromToken,
3571
- defaultToToken,
3572
- defaultFromChain = base,
3573
- defaultToChain,
3574
- supportedChains,
3575
- tokens,
3576
- mode = "auto",
3577
- theme = "dark",
3578
- accentColor = "#10b981",
3579
- className,
3580
- style,
3581
- quoteEndpoint,
3582
- executeEndpoint,
3583
- onSwapSuccess,
3584
- onSwapError,
3585
- onQuoteReceived,
3586
- onChainChange
3587
- }) {
3588
- const client = useThirdwebClient();
3589
- const account = useActiveAccount();
3590
- const { mutate: sendTransaction, isPending } = useSendTransaction();
3591
- const availableChains = useMemo(() => {
3592
- if (supportedChains) {
3593
- return CHAIN_CONFIGS2.filter((c) => supportedChains.some((sc) => sc.id === c.chain.id));
3594
- }
3595
- return CHAIN_CONFIGS2;
3596
- }, [supportedChains]);
3597
- const [fromChain, setFromChain] = useState(
3598
- availableChains.find((c) => c.chain.id === defaultFromChain.id) || availableChains[0]
3599
- );
3600
- const [toChain, setToChain] = useState(
3601
- defaultToChain ? availableChains.find((c) => c.chain.id === defaultToChain.id) || availableChains[0] : fromChain
3602
- );
3603
- const fromTokens = useMemo(() => {
3604
- if (tokens) {
3605
- return tokens.filter((t) => t.chainId === fromChain.chain.id);
3606
- }
3607
- return TOKENS_BY_CHAIN[fromChain.chain.id] || [];
3608
- }, [tokens, fromChain]);
3609
- const toTokens = useMemo(() => {
3610
- if (tokens) {
3611
- return tokens.filter((t) => t.chainId === toChain.chain.id);
3612
- }
3613
- return TOKENS_BY_CHAIN[toChain.chain.id] || [];
3614
- }, [tokens, toChain]);
3615
- const [fromToken, setFromToken] = useState(defaultFromToken || fromTokens[0]);
3616
- const [toToken, setToToken] = useState(defaultToToken || toTokens[1] || toTokens[0]);
3617
- const [fromAmount, setFromAmount] = useState("");
3618
- const [toAmount, setToAmount] = useState("");
3619
- const [route, setRoute] = useState(null);
3620
- const [isLoadingQuote, setIsLoadingQuote] = useState(false);
3621
- const [error, setError] = useState(null);
3622
- const isDark = theme === "dark";
3623
- const isCrossChain = fromChain.chain.id !== toChain.chain.id;
3624
- useEffect(() => {
3625
- const newFromTokens = TOKENS_BY_CHAIN[fromChain.chain.id] || [];
3626
- if (newFromTokens.length > 0 && !newFromTokens.some((t) => t.address === fromToken?.address)) {
3627
- setFromToken(newFromTokens[0]);
3628
- }
3629
- }, [fromChain, fromToken?.address]);
3630
- useEffect(() => {
3631
- const newToTokens = TOKENS_BY_CHAIN[toChain.chain.id] || [];
3632
- if (newToTokens.length > 0 && !newToTokens.some((t) => t.address === toToken?.address)) {
3633
- const sameSymbol = newToTokens.find((t) => t.symbol === fromToken?.symbol);
3634
- setToToken(sameSymbol || newToTokens[0]);
3635
- }
3636
- }, [toChain, toToken?.address, fromToken?.symbol]);
3637
- useEffect(() => {
3638
- onChainChange?.(fromChain.chain.id, toChain.chain.id);
3639
- }, [fromChain, toChain, onChainChange]);
3640
- const fetchQuote = useCallback(async () => {
3641
- if (!fromAmount || parseFloat(fromAmount) <= 0 || !fromToken || !toToken) {
3642
- setToAmount("");
3643
- setRoute(null);
3644
- return;
3645
- }
3646
- setIsLoadingQuote(true);
3647
- setError(null);
3648
- try {
3649
- const engineUrl = getEngineUrl();
3650
- const endpoint = quoteEndpoint || `${engineUrl}/v1/swap/quote`;
3651
- const response = await fetch(endpoint, {
3652
- method: "POST",
3653
- headers: { "Content-Type": "application/json" },
3654
- body: JSON.stringify({
3655
- fromChainId: fromChain.chain.id,
3656
- toChainId: toChain.chain.id,
3657
- fromToken: fromToken.address,
3658
- toToken: toToken.address,
3659
- fromAmount,
3660
- fromDecimals: fromToken.decimals,
3661
- walletAddress: account?.address,
3662
- slippage: 0.5
3663
- // 0.5% default slippage
3664
- })
3665
- });
3666
- const data = await response.json();
3667
- if (data.success && data.data) {
3668
- const routeData = {
3669
- provider: data.data.provider || "aggregator",
3670
- fromChain: fromChain.chain.id,
3671
- toChain: toChain.chain.id,
3672
- fromToken,
3673
- toToken,
3674
- fromAmount,
3675
- toAmount: data.data.toAmount || "0",
3676
- estimatedGas: data.data.estimatedGas || "0",
3677
- priceImpact: data.data.priceImpact || "0",
3678
- executionTime: isCrossChain ? "2-5 min" : "~30 sec",
3679
- steps: data.data.steps || []
3680
- };
3681
- setRoute(routeData);
3682
- setToAmount(routeData.toAmount);
3683
- onQuoteReceived?.(routeData);
3684
- } else {
3685
- const estimatedOutput = estimateSwapOutput(fromAmount, fromToken, toToken);
3686
- setToAmount(estimatedOutput.toFixed(6));
3687
- setError(data.error?.message || null);
3688
- }
3689
- } catch (err) {
3690
- const estimatedOutput = estimateSwapOutput(fromAmount, fromToken, toToken);
3691
- setToAmount(estimatedOutput.toFixed(6));
3692
- console.error("Quote fetch error:", err);
3693
- } finally {
3694
- setIsLoadingQuote(false);
3695
- }
3696
- }, [fromAmount, fromToken, toToken, fromChain, toChain, account?.address, quoteEndpoint, isCrossChain, onQuoteReceived]);
3697
- const estimateSwapOutput = (amount, from, to) => {
3698
- const prices = {
3699
- ETH: 3500,
3700
- WETH: 3500,
3701
- BNB: 650,
3702
- AVAX: 42,
3703
- POL: 0.85,
3704
- USDC: 1,
3705
- USDT: 1,
3706
- DAI: 1
3707
- };
3708
- const fromPrice = prices[from.symbol] || 1;
3709
- const toPrice = prices[to.symbol] || 1;
3710
- return parseFloat(amount) * fromPrice / toPrice;
3711
- };
3712
- useEffect(() => {
3713
- const debounce = setTimeout(fetchQuote, 500);
3714
- return () => clearTimeout(debounce);
3715
- }, [fetchQuote]);
3716
- const handleSwapDirection = () => {
3717
- const tempChain = fromChain;
3718
- const tempToken = fromToken;
3719
- setFromChain(toChain);
3720
- setToChain(tempChain);
3721
- setFromToken(toToken);
3722
- setToToken(tempToken);
3723
- setFromAmount(toAmount);
3724
- setToAmount(fromAmount);
3725
- };
3726
- const handleSwap = async () => {
3727
- if (!account || !fromToken || !toToken) return;
3728
- setError(null);
3729
- try {
3730
- const engineUrl = getEngineUrl();
3731
- const endpoint = executeEndpoint || `${engineUrl}/v1/swap/execute`;
3732
- const response = await fetch(endpoint, {
3733
- method: "POST",
3734
- headers: { "Content-Type": "application/json" },
3735
- body: JSON.stringify({
3736
- fromChainId: fromChain.chain.id,
3737
- toChainId: toChain.chain.id,
3738
- fromToken: fromToken.address,
3739
- toToken: toToken.address,
3740
- fromAmount,
3741
- walletAddress: account.address,
3742
- slippage: 0.5
3743
- })
3744
- });
3745
- const data = await response.json();
3746
- if (data.success && data.data?.transaction) {
3747
- const tx = prepareTransaction({
3748
- to: data.data.transaction.to,
3749
- data: data.data.transaction.data,
3750
- value: BigInt(data.data.transaction.value || 0),
3751
- chain: fromChain.chain,
3752
- client
3753
- });
3754
- sendTransaction(tx, {
3755
- onSuccess: (result) => {
3756
- onSwapSuccess?.(result.transactionHash, route || void 0);
3757
- setFromAmount("");
3758
- setToAmount("");
3759
- setRoute(null);
3760
- },
3761
- onError: (err) => {
3762
- setError(err.message);
3763
- onSwapError?.(err);
3764
- }
3765
- });
3766
- } else {
3767
- throw new Error(data.error?.message || "Swap execution failed");
3768
- }
3769
- } catch (err) {
3770
- const error2 = err instanceof Error ? err : new Error("Swap failed");
3771
- setError(error2.message);
3772
- onSwapError?.(error2);
3773
- }
3774
- };
3775
- const canSwap = account && fromAmount && parseFloat(fromAmount) > 0 && !isPending && !isLoadingQuote;
3776
- const bgColor = isDark ? "#1f2937" : "#ffffff";
3777
- const borderColor = isDark ? "#374151" : "#e5e7eb";
3778
- const textColor = isDark ? "#ffffff" : "#111827";
3779
- const mutedColor = isDark ? "#9ca3af" : "#6b7280";
3780
- const inputBg = isDark ? "#374151" : "#f3f4f6";
3781
- return /* @__PURE__ */ jsxs(
3782
- "div",
3783
- {
3784
- className,
3785
- style: {
3786
- ...containerStyle4,
3787
- backgroundColor: bgColor,
3788
- borderColor,
3789
- ...style
3790
- },
3791
- children: [
3792
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
3793
- /* @__PURE__ */ jsx("h3", { style: { color: textColor, margin: 0, fontSize: "18px", fontWeight: 600 }, children: "Swap" }),
3794
- isCrossChain && /* @__PURE__ */ jsx("span", { style: {
3795
- fontSize: "11px",
3796
- padding: "4px 8px",
3797
- backgroundColor: accentColor,
3798
- color: "#fff",
3799
- borderRadius: "4px"
3800
- }, children: "Cross-Chain" })
3801
- ] }),
3802
- /* @__PURE__ */ jsxs("div", { style: { ...tokenInputStyle, backgroundColor: inputBg }, children: [
3803
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
3804
- /* @__PURE__ */ jsx("span", { style: { ...labelStyle2, color: mutedColor }, children: "From" }),
3805
- mode !== "same-chain" && /* @__PURE__ */ jsx("div", { style: chainSelectorStyle, children: /* @__PURE__ */ jsx(
3806
- "select",
3807
- {
3808
- value: fromChain.chain.id,
3809
- onChange: (e) => {
3810
- const chain = availableChains.find((c) => c.chain.id === parseInt(e.target.value));
3811
- if (chain) setFromChain(chain);
3812
- },
3813
- style: {
3814
- ...selectStyle3,
3815
- backgroundColor: isDark ? "#4b5563" : "#e5e7eb",
3816
- color: textColor,
3817
- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='${isDark ? "%239ca3af" : "%236b7280"}'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E")`,
3818
- backgroundSize: "12px",
3819
- fontSize: "12px",
3820
- padding: "6px 24px 6px 8px"
3821
- },
3822
- children: availableChains.map((c) => /* @__PURE__ */ jsx("option", { value: c.chain.id, children: c.shortName }, c.chain.id))
3823
- }
3824
- ) })
3825
- ] }),
3826
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "12px", alignItems: "center" }, children: [
3827
- /* @__PURE__ */ jsx(
3828
- "input",
3829
- {
3830
- type: "number",
3831
- value: fromAmount,
3832
- onChange: (e) => setFromAmount(e.target.value),
3833
- placeholder: "0.0",
3834
- style: { ...inputStyle4, flex: 1, color: textColor }
3835
- }
3836
- ),
3837
- /* @__PURE__ */ jsx(
3838
- "select",
3839
- {
3840
- value: fromToken?.address || "",
3841
- onChange: (e) => {
3842
- const token = fromTokens.find((t) => t.address === e.target.value);
3843
- if (token) setFromToken(token);
3844
- },
3845
- style: {
3846
- ...selectStyle3,
3847
- backgroundColor: isDark ? "#4b5563" : "#e5e7eb",
3848
- color: textColor,
3849
- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='${isDark ? "%239ca3af" : "%236b7280"}'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E")`,
3850
- backgroundSize: "12px"
3851
- },
3852
- children: fromTokens.map((token) => /* @__PURE__ */ jsx("option", { value: token.address, children: token.symbol }, token.address))
3853
- }
3854
- )
3855
- ] })
3856
- ] }),
3857
- /* @__PURE__ */ jsx("div", { style: { display: "flex", justifyContent: "center", margin: "-8px 0" }, children: /* @__PURE__ */ jsx(
3858
- "button",
3859
- {
3860
- onClick: handleSwapDirection,
3861
- style: {
3862
- width: "36px",
3863
- height: "36px",
3864
- borderRadius: "50%",
3865
- backgroundColor: inputBg,
3866
- border: `2px solid ${bgColor}`,
3867
- cursor: "pointer",
3868
- display: "flex",
3869
- alignItems: "center",
3870
- justifyContent: "center",
3871
- fontSize: "16px",
3872
- color: mutedColor,
3873
- zIndex: 1
3874
- },
3875
- children: "\u2195"
3876
- }
3877
- ) }),
3878
- /* @__PURE__ */ jsxs("div", { style: { ...tokenInputStyle, backgroundColor: inputBg }, children: [
3879
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
3880
- /* @__PURE__ */ jsx("span", { style: { ...labelStyle2, color: mutedColor }, children: "To" }),
3881
- mode !== "same-chain" && /* @__PURE__ */ jsx("div", { style: chainSelectorStyle, children: /* @__PURE__ */ jsx(
3882
- "select",
3883
- {
3884
- value: toChain.chain.id,
3885
- onChange: (e) => {
3886
- const chain = availableChains.find((c) => c.chain.id === parseInt(e.target.value));
3887
- if (chain) setToChain(chain);
3888
- },
3889
- style: {
3890
- ...selectStyle3,
3891
- backgroundColor: isDark ? "#4b5563" : "#e5e7eb",
3892
- color: textColor,
3893
- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='${isDark ? "%239ca3af" : "%236b7280"}'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E")`,
3894
- backgroundSize: "12px",
3895
- fontSize: "12px",
3896
- padding: "6px 24px 6px 8px"
3897
- },
3898
- children: availableChains.map((c) => /* @__PURE__ */ jsx("option", { value: c.chain.id, children: c.shortName }, c.chain.id))
3899
- }
3900
- ) })
3901
- ] }),
3902
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "12px", alignItems: "center" }, children: [
3903
- /* @__PURE__ */ jsx(
3904
- "input",
3905
- {
3906
- type: "number",
3907
- value: toAmount,
3908
- placeholder: "0.0",
3909
- readOnly: true,
3910
- style: { ...inputStyle4, flex: 1, color: mutedColor }
3911
- }
3912
- ),
3913
- /* @__PURE__ */ jsx(
3914
- "select",
3915
- {
3916
- value: toToken?.address || "",
3917
- onChange: (e) => {
3918
- const token = toTokens.find((t) => t.address === e.target.value);
3919
- if (token) setToToken(token);
3920
- },
3921
- style: {
3922
- ...selectStyle3,
3923
- backgroundColor: isDark ? "#4b5563" : "#e5e7eb",
3924
- color: textColor,
3925
- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='${isDark ? "%239ca3af" : "%236b7280"}'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E")`,
3926
- backgroundSize: "12px"
3927
- },
3928
- children: toTokens.map((token) => /* @__PURE__ */ jsx("option", { value: token.address, children: token.symbol }, token.address))
3929
- }
3930
- )
3931
- ] })
3932
- ] }),
3933
- (route || fromAmount && toAmount) && /* @__PURE__ */ jsxs("div", { style: { ...routeBoxStyle, backgroundColor: inputBg }, children: [
3934
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: "6px" }, children: [
3935
- /* @__PURE__ */ jsx("span", { style: { color: mutedColor }, children: "Rate" }),
3936
- /* @__PURE__ */ jsxs("span", { style: { color: textColor }, children: [
3937
- "1 ",
3938
- fromToken?.symbol,
3939
- " = ",
3940
- toAmount && fromAmount ? (parseFloat(toAmount) / parseFloat(fromAmount)).toFixed(6) : "0",
3941
- " ",
3942
- toToken?.symbol
3943
- ] })
3944
- ] }),
3945
- route?.priceImpact && parseFloat(route.priceImpact) > 0 && /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: "6px" }, children: [
3946
- /* @__PURE__ */ jsx("span", { style: { color: mutedColor }, children: "Price Impact" }),
3947
- /* @__PURE__ */ jsxs("span", { style: { color: parseFloat(route.priceImpact) > 3 ? "#ef4444" : textColor }, children: [
3948
- route.priceImpact,
3949
- "%"
3950
- ] })
3951
- ] }),
3952
- isCrossChain && /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between" }, children: [
3953
- /* @__PURE__ */ jsx("span", { style: { color: mutedColor }, children: "Est. Time" }),
3954
- /* @__PURE__ */ jsx("span", { style: { color: textColor }, children: route?.executionTime || "2-5 min" })
3955
- ] })
3956
- ] }),
3957
- error && /* @__PURE__ */ jsx("div", { style: {
3958
- color: "#ef4444",
3959
- fontSize: "14px",
3960
- padding: "10px 12px",
3961
- backgroundColor: "rgba(239, 68, 68, 0.1)",
3962
- borderRadius: "8px"
3963
- }, children: error }),
3964
- /* @__PURE__ */ jsx(
3965
- "button",
3966
- {
3967
- onClick: handleSwap,
3968
- disabled: !canSwap,
3969
- style: {
3970
- ...buttonStyle4,
3971
- backgroundColor: canSwap ? accentColor : "#6b7280",
3972
- color: "#ffffff",
3973
- cursor: canSwap ? "pointer" : "not-allowed"
3974
- },
3975
- children: isPending ? "Swapping..." : isLoadingQuote ? "Getting Quote..." : !account ? "Connect Wallet" : isCrossChain ? `Bridge & Swap` : "Swap"
3976
- }
3977
- )
3978
- ]
3979
- }
3980
- );
3981
- }
3982
- function OneSameChainSwap(props) {
3983
- return /* @__PURE__ */ jsx(OneSwapWidget, { ...props, mode: "same-chain" });
3984
- }
3985
- function OneCrossChainSwap(props) {
3986
- return /* @__PURE__ */ jsx(OneSwapWidget, { ...props, mode: "cross-chain" });
3987
- }
3988
- var containerStyle5 = {
3989
- display: "flex",
3990
- flexDirection: "column",
3991
- gap: "16px"
3992
- };
3993
- var balanceCardStyle = {
3994
- padding: "24px",
3995
- backgroundColor: "#1f2937",
3996
- borderRadius: "16px",
3997
- border: "1px solid #374151"
3998
- };
3999
- var tokenRowStyle = {
4000
- display: "flex",
4001
- alignItems: "center",
4002
- justifyContent: "space-between",
4003
- padding: "12px 16px",
4004
- borderRadius: "12px",
4005
- cursor: "pointer",
4006
- transition: "background-color 0.2s"
4007
- };
4008
- var formatUSD = (value) => {
4009
- return new Intl.NumberFormat("en-US", {
4010
- style: "currency",
4011
- currency: "USD",
4012
- minimumFractionDigits: 2,
4013
- maximumFractionDigits: 2
4014
- }).format(value);
4015
- };
4016
- var formatBalance = (value, decimals = 4) => {
4017
- const num = parseFloat(value);
4018
- if (num === 0) return "0";
4019
- if (num < 1e-4) return "<0.0001";
4020
- return num.toFixed(decimals);
4021
- };
4022
- var CHAIN_INFO = {
4023
- 1: { name: "Ethereum", icon: "\u27E0" },
4024
- 8453: { name: "Base", icon: "\u{1F535}" },
4025
- 137: { name: "Polygon", icon: "\u{1F7E3}" },
4026
- 42161: { name: "Arbitrum", icon: "\u{1F537}" },
4027
- 10: { name: "Optimism", icon: "\u{1F534}" }
4028
- };
4029
- function OneWalletBalance({
4030
- showTotalBalance = true,
4031
- showTokenList = true,
4032
- showChainFilter = true,
4033
- showPriceChange = true,
4034
- chains = [base, ethereum, polygon, arbitrum, optimism],
4035
- balanceEndpoint = "/api/v1/assets",
4036
- theme = "dark",
4037
- className,
4038
- style,
4039
- compact = false,
4040
- onTokenClick,
4041
- onRefresh
4042
- }) {
4043
- useThirdwebClient();
4044
- const account = useActiveAccount();
4045
- const [tokens, setTokens] = useState([]);
4046
- const [totalBalance, setTotalBalance] = useState(0);
4047
- const [totalChange24h, setTotalChange24h] = useState(0);
4048
- const [isLoading, setIsLoading] = useState(true);
4049
- const [selectedChain, setSelectedChain] = useState(null);
4050
- const [error, setError] = useState(null);
4051
- const fetchBalances = useCallback(async () => {
4052
- if (!account?.address) return;
4053
- setIsLoading(true);
4054
- setError(null);
4055
- try {
4056
- const chainIds = chains.map((c) => c.id).join(",");
4057
- const response = await fetch(`${balanceEndpoint}?address=${account.address}&chains=${chainIds}`);
4058
- const data = await response.json();
4059
- if (data.success && data.data) {
4060
- const balanceData = data.data;
4061
- setTokens(balanceData.tokens || []);
4062
- setTotalBalance(balanceData.totalUsd || 0);
4063
- setTotalChange24h(balanceData.change24hPercent || 0);
4064
- } else {
4065
- setError(data.error?.message || "Failed to fetch balances");
4066
- }
4067
- } catch (err) {
4068
- setError("Failed to load balances");
4069
- } finally {
4070
- setIsLoading(false);
4071
- }
4072
- }, [account?.address, balanceEndpoint, chains]);
4073
- useEffect(() => {
4074
- fetchBalances();
4075
- }, [fetchBalances]);
4076
- const handleRefresh = () => {
4077
- fetchBalances();
4078
- onRefresh?.();
4079
- };
4080
- const filteredTokens = selectedChain ? tokens.filter((t) => t.chainId === selectedChain) : tokens;
4081
- const isDark = theme === "dark";
4082
- if (!account) {
4083
- return /* @__PURE__ */ jsx("div", { className, style: { ...style, textAlign: "center", padding: "24px", color: isDark ? "#9ca3af" : "#6b7280" }, children: "Connect your wallet to view balances" });
4084
- }
4085
- return /* @__PURE__ */ jsxs("div", { className, style: { ...containerStyle5, ...style }, children: [
4086
- showTotalBalance && /* @__PURE__ */ jsx("div", { style: { ...balanceCardStyle, backgroundColor: isDark ? "#1f2937" : "#ffffff", border: `1px solid ${isDark ? "#374151" : "#e5e7eb"}` }, children: /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-start" }, children: [
4087
- /* @__PURE__ */ jsxs("div", { children: [
4088
- /* @__PURE__ */ jsx("p", { style: { margin: "0 0 4px 0", color: isDark ? "#9ca3af" : "#6b7280", fontSize: "14px" }, children: "Total Balance" }),
4089
- isLoading ? /* @__PURE__ */ jsx("div", { style: { height: "36px", width: "120px", backgroundColor: isDark ? "#374151" : "#e5e7eb", borderRadius: "8px", animation: "pulse 2s infinite" } }) : /* @__PURE__ */ jsx("h2", { style: { margin: 0, color: isDark ? "#ffffff" : "#111827", fontSize: compact ? "24px" : "32px", fontWeight: 700 }, children: formatUSD(totalBalance) }),
4090
- showPriceChange && !isLoading && /* @__PURE__ */ jsxs("p", { style: { margin: "4px 0 0 0", fontSize: "14px", color: totalChange24h >= 0 ? "#10b981" : "#ef4444" }, children: [
4091
- totalChange24h >= 0 ? "+" : "",
4092
- totalChange24h.toFixed(2),
4093
- "% (24h)"
4094
- ] })
4095
- ] }),
4096
- /* @__PURE__ */ jsx(
4097
- "button",
4098
- {
4099
- onClick: handleRefresh,
4100
- disabled: isLoading,
4101
- style: {
4102
- padding: "8px 12px",
4103
- backgroundColor: isDark ? "#374151" : "#e5e7eb",
4104
- border: "none",
4105
- borderRadius: "8px",
4106
- color: isDark ? "#ffffff" : "#111827",
4107
- cursor: isLoading ? "not-allowed" : "pointer",
4108
- fontSize: "14px"
4109
- },
4110
- children: isLoading ? "..." : "\u21BB"
4111
- }
4112
- )
4113
- ] }) }),
4114
- showChainFilter && chains.length > 1 && /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "8px", flexWrap: "wrap" }, children: [
4115
- /* @__PURE__ */ jsx(
4116
- "button",
4117
- {
4118
- onClick: () => setSelectedChain(null),
4119
- style: {
4120
- padding: "8px 16px",
4121
- backgroundColor: selectedChain === null ? "#10b981" : isDark ? "#374151" : "#e5e7eb",
4122
- border: "none",
4123
- borderRadius: "20px",
4124
- color: selectedChain === null ? "#ffffff" : isDark ? "#9ca3af" : "#6b7280",
4125
- cursor: "pointer",
4126
- fontSize: "14px"
4127
- },
4128
- children: "All"
4129
- }
4130
- ),
4131
- chains.map((chain) => /* @__PURE__ */ jsxs(
4132
- "button",
4133
- {
4134
- onClick: () => setSelectedChain(chain.id),
4135
- style: {
4136
- padding: "8px 16px",
4137
- backgroundColor: selectedChain === chain.id ? "#10b981" : isDark ? "#374151" : "#e5e7eb",
4138
- border: "none",
4139
- borderRadius: "20px",
4140
- color: selectedChain === chain.id ? "#ffffff" : isDark ? "#9ca3af" : "#6b7280",
4141
- cursor: "pointer",
4142
- fontSize: "14px"
4143
- },
4144
- children: [
4145
- CHAIN_INFO[chain.id]?.icon,
4146
- " ",
4147
- CHAIN_INFO[chain.id]?.name || `Chain ${chain.id}`
4148
- ]
4149
- },
4150
- chain.id
4151
- ))
4152
- ] }),
4153
- showTokenList && /* @__PURE__ */ jsx("div", { style: { display: "flex", flexDirection: "column", gap: "4px" }, children: isLoading ? Array(3).fill(0).map((_, i) => /* @__PURE__ */ jsx("div", { style: { ...tokenRowStyle, backgroundColor: isDark ? "#374151" : "#f3f4f6", height: "60px", animation: "pulse 2s infinite" } }, i)) : error ? /* @__PURE__ */ jsx("div", { style: { textAlign: "center", padding: "24px", color: "#ef4444" }, children: error }) : filteredTokens.length === 0 ? /* @__PURE__ */ jsx("div", { style: { textAlign: "center", padding: "24px", color: isDark ? "#9ca3af" : "#6b7280" }, children: "No tokens found" }) : filteredTokens.map((token, index) => /* @__PURE__ */ jsxs(
4154
- "div",
4155
- {
4156
- style: {
4157
- ...tokenRowStyle,
4158
- backgroundColor: "transparent"
4159
- },
4160
- onClick: () => onTokenClick?.(token),
4161
- onMouseEnter: (e) => {
4162
- e.currentTarget.style.backgroundColor = isDark ? "#374151" : "#f3f4f6";
4163
- },
4164
- onMouseLeave: (e) => {
4165
- e.currentTarget.style.backgroundColor = "transparent";
4166
- },
4167
- children: [
4168
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", alignItems: "center", gap: "12px" }, children: [
4169
- /* @__PURE__ */ jsx("div", { style: {
4170
- width: "40px",
4171
- height: "40px",
4172
- borderRadius: "50%",
4173
- backgroundColor: isDark ? "#374151" : "#e5e7eb",
4174
- display: "flex",
4175
- alignItems: "center",
4176
- justifyContent: "center",
4177
- fontSize: "16px",
4178
- fontWeight: 600,
4179
- color: isDark ? "#ffffff" : "#111827"
4180
- }, children: token.logoURI ? /* @__PURE__ */ jsx("img", { src: token.logoURI, alt: token.symbol, style: { width: "100%", height: "100%", borderRadius: "50%" } }) : token.symbol.slice(0, 2) }),
4181
- /* @__PURE__ */ jsxs("div", { children: [
4182
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", alignItems: "center", gap: "8px" }, children: [
4183
- /* @__PURE__ */ jsx("span", { style: { color: isDark ? "#ffffff" : "#111827", fontWeight: 600 }, children: token.symbol }),
4184
- /* @__PURE__ */ jsx("span", { style: {
4185
- fontSize: "10px",
4186
- padding: "2px 6px",
4187
- backgroundColor: isDark ? "#374151" : "#e5e7eb",
4188
- borderRadius: "4px",
4189
- color: isDark ? "#9ca3af" : "#6b7280"
4190
- }, children: CHAIN_INFO[token.chainId]?.name || token.chain })
4191
- ] }),
4192
- /* @__PURE__ */ jsxs("span", { style: { color: isDark ? "#9ca3af" : "#6b7280", fontSize: "14px" }, children: [
4193
- formatBalance(token.balanceFormatted),
4194
- " ",
4195
- token.symbol
4196
- ] })
4197
- ] })
4198
- ] }),
4199
- /* @__PURE__ */ jsxs("div", { style: { textAlign: "right" }, children: [
4200
- /* @__PURE__ */ jsx("div", { style: { color: isDark ? "#ffffff" : "#111827", fontWeight: 600 }, children: formatUSD(token.balanceUsd) }),
4201
- showPriceChange && /* @__PURE__ */ jsxs("div", { style: { fontSize: "14px", color: token.priceChange24h >= 0 ? "#10b981" : "#ef4444" }, children: [
4202
- token.priceChange24h >= 0 ? "+" : "",
4203
- token.priceChange24h.toFixed(2),
4204
- "%"
4205
- ] })
4206
- ] })
4207
- ]
4208
- },
4209
- `${token.chainId}-${token.symbol}-${index}`
4210
- )) })
4211
- ] });
4212
- }
4213
- function OneBalanceDisplay({
4214
- theme = "dark",
4215
- className,
4216
- style
4217
- }) {
4218
- return /* @__PURE__ */ jsx(
4219
- OneWalletBalance,
4220
- {
4221
- theme,
4222
- className,
4223
- style,
4224
- showTotalBalance: true,
4225
- showTokenList: false,
4226
- showChainFilter: false,
4227
- compact: true
4228
- }
4229
- );
4230
- }
4231
- var galleryStyle = {
4232
- display: "grid",
4233
- gap: "16px"
4234
- };
4235
- var cardStyle = {
4236
- backgroundColor: "#1f2937",
4237
- borderRadius: "16px",
4238
- overflow: "hidden",
4239
- border: "1px solid #374151",
4240
- cursor: "pointer",
4241
- transition: "transform 0.2s, box-shadow 0.2s"
4242
- };
4243
- var imageContainerStyle = {
4244
- aspectRatio: "1",
4245
- backgroundColor: "#374151",
4246
- display: "flex",
4247
- alignItems: "center",
4248
- justifyContent: "center",
4249
- overflow: "hidden"
4250
- };
4251
- var infoStyle = {
4252
- padding: "12px"
4253
- };
4254
- function OneNFTGallery({
4255
- nfts: propNfts,
4256
- fetchEndpoint = "/api/v1/assets/nft",
4257
- columns = 3,
4258
- showCollection = true,
4259
- showChain = true,
4260
- theme = "dark",
4261
- className,
4262
- style,
4263
- onNFTClick,
4264
- onTransfer
4265
- }) {
4266
- const client = useThirdwebClient();
4267
- const account = useActiveAccount();
4268
- const [nfts, setNfts] = useState(propNfts || []);
4269
- const [isLoading, setIsLoading] = useState(!propNfts);
4270
- const [error, setError] = useState(null);
4271
- const [selectedNFT, setSelectedNFT] = useState(null);
4272
- const fetchNFTs = useCallback(async () => {
4273
- if (!account?.address || propNfts) return;
4274
- setIsLoading(true);
4275
- setError(null);
4276
- try {
4277
- const response = await fetch(`${fetchEndpoint}?address=${account.address}`);
4278
- const data = await response.json();
4279
- if (data.success && data.data) {
4280
- setNfts(data.data.nfts || []);
4281
- } else {
4282
- setError(data.error?.message || "Failed to fetch NFTs");
4283
- }
4284
- } catch (err) {
4285
- setError("Failed to load NFTs");
4286
- } finally {
4287
- setIsLoading(false);
4288
- }
4289
- }, [account?.address, fetchEndpoint, propNfts]);
4290
- useEffect(() => {
4291
- fetchNFTs();
4292
- }, [fetchNFTs]);
4293
- useEffect(() => {
4294
- if (propNfts) {
4295
- setNfts(propNfts);
4296
- }
4297
- }, [propNfts]);
4298
- const isDark = theme === "dark";
4299
- const gridColumns = {
4300
- 2: "repeat(2, 1fr)",
4301
- 3: "repeat(3, 1fr)",
4302
- 4: "repeat(4, 1fr)"
4303
- };
4304
- if (isLoading) {
4305
- return /* @__PURE__ */ jsx("div", { className, style: { ...style, textAlign: "center", padding: "40px", color: isDark ? "#9ca3af" : "#6b7280" }, children: "Loading NFTs..." });
4306
- }
4307
- if (error) {
4308
- return /* @__PURE__ */ jsx("div", { className, style: { ...style, textAlign: "center", padding: "40px", color: "#ef4444" }, children: error });
4309
- }
4310
- if (nfts.length === 0) {
4311
- return /* @__PURE__ */ jsx("div", { className, style: { ...style, textAlign: "center", padding: "40px", color: isDark ? "#9ca3af" : "#6b7280" }, children: "No NFTs found" });
4312
- }
4313
- return /* @__PURE__ */ jsxs("div", { className, style, children: [
4314
- /* @__PURE__ */ jsx("div", { style: { ...galleryStyle, gridTemplateColumns: gridColumns[columns] }, children: nfts.map((nft) => /* @__PURE__ */ jsxs(
4315
- "div",
4316
- {
4317
- style: {
4318
- ...cardStyle,
4319
- backgroundColor: isDark ? "#1f2937" : "#ffffff",
4320
- border: `1px solid ${isDark ? "#374151" : "#e5e7eb"}`
4321
- },
4322
- onClick: () => {
4323
- setSelectedNFT(nft);
4324
- onNFTClick?.(nft);
4325
- },
4326
- onMouseEnter: (e) => {
4327
- e.currentTarget.style.transform = "translateY(-4px)";
4328
- e.currentTarget.style.boxShadow = "0 10px 40px rgba(0,0,0,0.3)";
4329
- },
4330
- onMouseLeave: (e) => {
4331
- e.currentTarget.style.transform = "translateY(0)";
4332
- e.currentTarget.style.boxShadow = "none";
4333
- },
4334
- children: [
4335
- /* @__PURE__ */ jsx("div", { style: { ...imageContainerStyle, backgroundColor: isDark ? "#374151" : "#f3f4f6" }, children: nft.image ? /* @__PURE__ */ jsx(
4336
- MediaRenderer,
4337
- {
4338
- client,
4339
- src: nft.image,
4340
- style: { width: "100%", height: "100%", objectFit: "cover" }
4341
- }
4342
- ) : /* @__PURE__ */ jsx("span", { style: { color: isDark ? "#6b7280" : "#9ca3af", fontSize: "14px" }, children: "No Image" }) }),
4343
- /* @__PURE__ */ jsxs("div", { style: infoStyle, children: [
4344
- /* @__PURE__ */ jsx("h4", { style: { margin: "0 0 4px 0", color: isDark ? "#ffffff" : "#111827", fontSize: "14px", fontWeight: 600 }, children: nft.name || `#${nft.tokenId}` }),
4345
- showCollection && nft.collection && /* @__PURE__ */ jsx("p", { style: { margin: 0, color: isDark ? "#9ca3af" : "#6b7280", fontSize: "12px" }, children: nft.collection.name }),
4346
- showChain && /* @__PURE__ */ jsx("span", { style: {
4347
- display: "inline-block",
4348
- marginTop: "8px",
4349
- padding: "2px 8px",
4350
- backgroundColor: isDark ? "#374151" : "#e5e7eb",
4351
- borderRadius: "4px",
4352
- fontSize: "10px",
4353
- color: isDark ? "#9ca3af" : "#6b7280"
4354
- }, children: nft.chain })
4355
- ] })
4356
- ]
4357
- },
4358
- `${nft.contractAddress}-${nft.tokenId}`
4359
- )) }),
4360
- selectedNFT && /* @__PURE__ */ jsx(
4361
- "div",
4362
- {
4363
- style: {
4364
- position: "fixed",
4365
- inset: 0,
4366
- backgroundColor: "rgba(0,0,0,0.8)",
4367
- display: "flex",
4368
- alignItems: "center",
4369
- justifyContent: "center",
4370
- zIndex: 1e3
4371
- },
4372
- onClick: () => setSelectedNFT(null),
4373
- children: /* @__PURE__ */ jsxs(
4374
- "div",
4375
- {
4376
- style: {
4377
- backgroundColor: isDark ? "#1f2937" : "#ffffff",
4378
- borderRadius: "16px",
4379
- padding: "24px",
4380
- maxWidth: "500px",
4381
- width: "90%",
4382
- maxHeight: "90vh",
4383
- overflow: "auto"
4384
- },
4385
- onClick: (e) => e.stopPropagation(),
4386
- children: [
4387
- selectedNFT.image && /* @__PURE__ */ jsx(
4388
- MediaRenderer,
4389
- {
4390
- client,
4391
- src: selectedNFT.image,
4392
- style: { width: "100%", borderRadius: "12px", marginBottom: "16px" }
4393
- }
4394
- ),
4395
- /* @__PURE__ */ jsx("h3", { style: { margin: "0 0 8px 0", color: isDark ? "#ffffff" : "#111827" }, children: selectedNFT.name || `#${selectedNFT.tokenId}` }),
4396
- selectedNFT.description && /* @__PURE__ */ jsx("p", { style: { margin: "0 0 16px 0", color: isDark ? "#9ca3af" : "#6b7280", fontSize: "14px" }, children: selectedNFT.description }),
4397
- selectedNFT.attributes && selectedNFT.attributes.length > 0 && /* @__PURE__ */ jsx("div", { style: { display: "flex", flexWrap: "wrap", gap: "8px", marginBottom: "16px" }, children: selectedNFT.attributes.map((attr, i) => /* @__PURE__ */ jsxs(
4398
- "div",
4399
- {
4400
- style: {
4401
- padding: "8px 12px",
4402
- backgroundColor: isDark ? "#374151" : "#f3f4f6",
4403
- borderRadius: "8px"
4404
- },
4405
- children: [
4406
- /* @__PURE__ */ jsx("div", { style: { fontSize: "10px", color: isDark ? "#9ca3af" : "#6b7280" }, children: attr.trait_type }),
4407
- /* @__PURE__ */ jsx("div", { style: { fontSize: "14px", color: isDark ? "#ffffff" : "#111827", fontWeight: 500 }, children: attr.value })
4408
- ]
4409
- },
4410
- i
4411
- )) }),
4412
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "12px" }, children: [
4413
- /* @__PURE__ */ jsx(
4414
- "button",
4415
- {
4416
- onClick: () => setSelectedNFT(null),
4417
- style: {
4418
- flex: 1,
4419
- padding: "12px",
4420
- backgroundColor: "transparent",
4421
- border: `1px solid ${isDark ? "#374151" : "#e5e7eb"}`,
4422
- borderRadius: "8px",
4423
- color: isDark ? "#9ca3af" : "#6b7280",
4424
- cursor: "pointer"
4425
- },
4426
- children: "Close"
4427
- }
4428
- ),
4429
- onTransfer && /* @__PURE__ */ jsx(
4430
- "button",
4431
- {
4432
- onClick: () => {
4433
- onTransfer(selectedNFT);
4434
- setSelectedNFT(null);
4435
- },
4436
- style: {
4437
- flex: 1,
4438
- padding: "12px",
4439
- backgroundColor: "#10b981",
4440
- border: "none",
4441
- borderRadius: "8px",
4442
- color: "#ffffff",
4443
- fontWeight: 600,
4444
- cursor: "pointer"
4445
- },
4446
- children: "Transfer"
4447
- }
4448
- )
4449
- ] })
4450
- ]
4451
- }
4452
- )
4453
- }
4454
- )
4455
- ] });
4456
- }
4457
- function generateQRMatrix(data) {
4458
- const size = 21;
4459
- const matrix = Array(size).fill(null).map(() => Array(size).fill(false));
4460
- const addFinderPattern = (x, y) => {
4461
- for (let i = 0; i < 7; i++) {
4462
- for (let j = 0; j < 7; j++) {
4463
- if (i === 0 || i === 6 || j === 0 || j === 6 || i >= 2 && i <= 4 && j >= 2 && j <= 4) {
4464
- matrix[y + i][x + j] = true;
4465
- }
4466
- }
4467
- }
4468
- };
4469
- addFinderPattern(0, 0);
4470
- addFinderPattern(14, 0);
4471
- addFinderPattern(0, 14);
4472
- let hash = 0;
4473
- for (let i = 0; i < data.length; i++) {
4474
- hash = (hash << 5) - hash + data.charCodeAt(i);
4475
- hash = hash & hash;
4476
- }
4477
- for (let i = 8; i < 13; i++) {
4478
- for (let j = 8; j < 13; j++) {
4479
- matrix[i][j] = (hash >> (i * 21 + j) % 32 & 1) === 1;
4480
- }
4481
- }
4482
- return matrix;
4483
- }
4484
- function QRCode({ data, size = 200, isDark = true }) {
4485
- const matrix = generateQRMatrix(data);
4486
- const cellSize = size / matrix.length;
4487
- return /* @__PURE__ */ jsxs("svg", { width: size, height: size, viewBox: `0 0 ${size} ${size}`, children: [
4488
- /* @__PURE__ */ jsx("rect", { width: size, height: size, fill: isDark ? "#ffffff" : "#ffffff", rx: "8" }),
4489
- matrix.map(
4490
- (row, y) => row.map(
4491
- (cell, x) => cell ? /* @__PURE__ */ jsx(
4492
- "rect",
4493
- {
4494
- x: x * cellSize,
4495
- y: y * cellSize,
4496
- width: cellSize,
4497
- height: cellSize,
4498
- fill: isDark ? "#111827" : "#111827"
4499
- },
4500
- `${x}-${y}`
4501
- ) : null
4502
- )
4503
- )
4504
- ] });
4505
- }
4506
- var containerStyle6 = {
4507
- display: "flex",
4508
- flexDirection: "column",
4509
- alignItems: "center",
4510
- gap: "20px",
4511
- padding: "24px",
4512
- backgroundColor: "#1f2937",
4513
- borderRadius: "16px",
4514
- border: "1px solid #374151"
4515
- };
4516
- var addressStyle = {
4517
- display: "flex",
4518
- alignItems: "center",
4519
- gap: "8px",
4520
- padding: "12px 16px",
4521
- backgroundColor: "#374151",
4522
- borderRadius: "12px",
4523
- maxWidth: "100%"
4524
- };
4525
- var buttonStyle5 = {
4526
- padding: "8px 16px",
4527
- backgroundColor: "#10b981",
4528
- color: "#ffffff",
4529
- border: "none",
4530
- borderRadius: "8px",
4531
- cursor: "pointer",
4532
- fontSize: "14px",
4533
- fontWeight: 500
4534
- };
4535
- var CHAIN_INFO2 = {
4536
- 1: { name: "Ethereum", icon: "\u27E0" },
4537
- 8453: { name: "Base", icon: "\u{1F535}" },
4538
- 137: { name: "Polygon", icon: "\u{1F7E3}" },
4539
- 42161: { name: "Arbitrum", icon: "\u{1F537}" },
4540
- 10: { name: "Optimism", icon: "\u{1F534}" }
4541
- };
4542
- function OneReceiveWidget({
4543
- chains = [base, ethereum, polygon, arbitrum],
4544
- defaultChain = base,
4545
- showChainSelector = true,
4546
- showCopyButton = true,
4547
- showQRCode = true,
4548
- theme = "dark",
4549
- className,
4550
- style,
4551
- qrSize = 200,
4552
- onCopy,
4553
- onChainChange
4554
- }) {
4555
- const account = useActiveAccount();
4556
- const [selectedChain, setSelectedChain] = useState(defaultChain);
4557
- const [copied, setCopied] = useState(false);
4558
- const address = account?.address || "";
4559
- const isDark = theme === "dark";
4560
- const handleCopy = async () => {
4561
- if (!address) return;
4562
- try {
4563
- await navigator.clipboard.writeText(address);
4564
- setCopied(true);
4565
- onCopy?.(address);
4566
- setTimeout(() => setCopied(false), 2e3);
4567
- } catch (err) {
4568
- console.error("Failed to copy:", err);
4569
- }
4570
- };
4571
- const handleChainChange = (chain) => {
4572
- setSelectedChain(chain);
4573
- onChainChange?.(chain);
4574
- };
4575
- if (!account) {
4576
- return /* @__PURE__ */ jsx("div", { className, style: { ...style, textAlign: "center", padding: "24px", color: isDark ? "#9ca3af" : "#6b7280" }, children: "Connect your wallet to receive funds" });
4577
- }
4578
- return /* @__PURE__ */ jsxs(
4579
- "div",
4580
- {
4581
- className,
4582
- style: {
4583
- ...containerStyle6,
4584
- backgroundColor: isDark ? "#1f2937" : "#ffffff",
4585
- border: `1px solid ${isDark ? "#374151" : "#e5e7eb"}`,
4586
- ...style
4587
- },
4588
- children: [
4589
- /* @__PURE__ */ jsx("h3", { style: { margin: 0, color: isDark ? "#ffffff" : "#111827", fontSize: "18px", fontWeight: 600 }, children: "Receive" }),
4590
- showChainSelector && chains.length > 1 && /* @__PURE__ */ jsx("div", { style: { display: "flex", gap: "8px", flexWrap: "wrap", justifyContent: "center" }, children: chains.map((chain) => /* @__PURE__ */ jsxs(
4591
- "button",
4592
- {
4593
- onClick: () => handleChainChange(chain),
4594
- style: {
4595
- padding: "8px 12px",
4596
- backgroundColor: selectedChain.id === chain.id ? "#10b981" : isDark ? "#374151" : "#e5e7eb",
4597
- border: "none",
4598
- borderRadius: "8px",
4599
- color: selectedChain.id === chain.id ? "#ffffff" : isDark ? "#9ca3af" : "#6b7280",
4600
- cursor: "pointer",
4601
- fontSize: "12px"
4602
- },
4603
- children: [
4604
- CHAIN_INFO2[chain.id]?.icon,
4605
- " ",
4606
- CHAIN_INFO2[chain.id]?.name
4607
- ]
4608
- },
4609
- chain.id
4610
- )) }),
4611
- showQRCode && /* @__PURE__ */ jsx("div", { style: { padding: "16px", backgroundColor: "#ffffff", borderRadius: "12px" }, children: /* @__PURE__ */ jsx(QRCode, { data: address, size: qrSize, isDark }) }),
4612
- /* @__PURE__ */ jsx("div", { style: { ...addressStyle, backgroundColor: isDark ? "#374151" : "#f3f4f6", width: "100%" }, children: /* @__PURE__ */ jsx("span", { style: {
4613
- color: isDark ? "#ffffff" : "#111827",
4614
- fontSize: "14px",
4615
- fontFamily: "monospace",
4616
- flex: 1,
4617
- overflow: "hidden",
4618
- textOverflow: "ellipsis"
4619
- }, children: address }) }),
4620
- showCopyButton && /* @__PURE__ */ jsx(
4621
- "button",
4622
- {
4623
- onClick: handleCopy,
4624
- style: {
4625
- ...buttonStyle5,
4626
- backgroundColor: copied ? "#059669" : "#10b981",
4627
- width: "100%"
4628
- },
4629
- children: copied ? "\u2713 Copied!" : "Copy Address"
4630
- }
4631
- ),
4632
- /* @__PURE__ */ jsxs("p", { style: {
4633
- margin: 0,
4634
- color: isDark ? "#9ca3af" : "#6b7280",
4635
- fontSize: "12px",
4636
- textAlign: "center"
4637
- }, children: [
4638
- "Only send ",
4639
- CHAIN_INFO2[selectedChain.id]?.name || "compatible",
4640
- " assets to this address"
4641
- ] })
4642
- ]
4643
- }
4644
- );
4645
- }
4646
- function useWalletBalance2(walletAddress, options = {}) {
4647
- const {
4648
- chains,
4649
- autoRefresh = false,
4650
- refreshInterval = 6e4,
4651
- // 1 minute
4652
- engineUrl,
4653
- clientId
4654
- } = options;
4655
- const [balance, setBalance] = useState(null);
4656
- const [isLoading, setIsLoading] = useState(false);
4657
- const [error, setError] = useState(null);
4658
- const engineRef = useRef(createOneEngineClient({
4659
- baseUrl: engineUrl,
4660
- clientId
4661
- }));
4662
- const fetchBalance = useCallback(async () => {
4663
- if (!walletAddress) {
4664
- setBalance(null);
4665
- return;
4666
- }
4667
- setIsLoading(true);
4668
- setError(null);
4669
- try {
4670
- const result = await engineRef.current.getWalletBalance(walletAddress, chains);
4671
- if (result.success && result.data) {
4672
- setBalance(result.data);
4673
- } else {
4674
- setError(result.error?.message || "Failed to fetch balance");
4675
- }
4676
- } catch (err) {
4677
- setError(err instanceof Error ? err.message : "Failed to fetch balance");
4678
- } finally {
4679
- setIsLoading(false);
4680
- }
4681
- }, [walletAddress, chains]);
4682
- useEffect(() => {
4683
- fetchBalance();
4684
- }, [fetchBalance]);
4685
- useEffect(() => {
4686
- if (!autoRefresh || !walletAddress) return;
4687
- const interval = setInterval(fetchBalance, refreshInterval);
4688
- return () => clearInterval(interval);
4689
- }, [autoRefresh, refreshInterval, fetchBalance, walletAddress]);
4690
- return {
4691
- balance,
4692
- tokens: balance?.tokens || [],
4693
- totalUsd: balance?.totalUsd || 0,
4694
- change24h: balance?.change24h || 0,
4695
- changePercent24h: balance?.changePercent24h || 0,
4696
- isLoading,
4697
- error,
4698
- refetch: fetchBalance
4699
- };
4700
- }
4701
- function useTokenPrice(symbol, options = {}) {
4702
- const { autoRefresh = false, refreshInterval = 3e4, engineUrl, clientId } = options;
4703
- const [price, setPrice] = useState(null);
4704
- const [isLoading, setIsLoading] = useState(false);
4705
- const [error, setError] = useState(null);
4706
- const engineRef = useRef(createOneEngineClient({
4707
- baseUrl: engineUrl,
4708
- clientId
4709
- }));
4710
- const fetchPrice = useCallback(async () => {
4711
- if (!symbol) return;
4712
- setIsLoading(true);
4713
- setError(null);
4714
- try {
4715
- const result = await engineRef.current.getTokenPrices([symbol]);
4716
- if (result.success && result.data && result.data[symbol]) {
4717
- const priceData = result.data[symbol];
4718
- setPrice({
4719
- symbol,
4720
- price: priceData.price,
4721
- change24h: priceData.change24h,
4722
- changePercent24h: priceData.change24h,
4723
- // Same as change24h for percentage
4724
- marketCap: priceData.marketCap,
4725
- volume24h: 0,
4726
- // Not provided by engine
4727
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4728
- });
4729
- } else {
4730
- setError(result.error?.message || "Failed to fetch price");
4731
- }
4732
- } catch (err) {
4733
- setError(err instanceof Error ? err.message : "Failed to fetch price");
4734
- } finally {
4735
- setIsLoading(false);
4736
- }
4737
- }, [symbol]);
4738
- useEffect(() => {
4739
- fetchPrice();
4740
- }, [fetchPrice]);
4741
- useEffect(() => {
4742
- if (!autoRefresh) return;
4743
- const interval = setInterval(fetchPrice, refreshInterval);
4744
- return () => clearInterval(interval);
4745
- }, [autoRefresh, refreshInterval, fetchPrice]);
4746
- return {
4747
- price,
4748
- isLoading,
4749
- error,
4750
- refetch: fetchPrice
4751
- };
4752
- }
4753
- function useTokenPrices(symbols, options = {}) {
4754
- const { autoRefresh = false, refreshInterval = 3e4, engineUrl, clientId } = options;
4755
- const [prices, setPrices] = useState({});
4756
- const [isLoading, setIsLoading] = useState(false);
4757
- const [error, setError] = useState(null);
4758
- const engineRef = useRef(createOneEngineClient({
4759
- baseUrl: engineUrl,
4760
- clientId
4761
- }));
4762
- const fetchPrices = useCallback(async () => {
4763
- if (symbols.length === 0) return;
4764
- setIsLoading(true);
4765
- setError(null);
4766
- try {
4767
- const result = await engineRef.current.getTokenPrices(symbols);
4768
- if (result.success && result.data) {
4769
- const priceMap = {};
4770
- for (const sym of symbols) {
4771
- if (result.data[sym]) {
4772
- priceMap[sym] = {
4773
- symbol: sym,
4774
- price: result.data[sym].price,
4775
- change24h: result.data[sym].change24h,
4776
- changePercent24h: result.data[sym].change24h,
4777
- marketCap: result.data[sym].marketCap,
4778
- volume24h: 0,
4779
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4780
- };
4781
- }
4782
- }
4783
- setPrices(priceMap);
4784
- } else {
4785
- setError(result.error?.message || "Failed to fetch prices");
4786
- }
4787
- } catch (err) {
4788
- setError(err instanceof Error ? err.message : "Failed to fetch prices");
4789
- } finally {
4790
- setIsLoading(false);
4791
- }
4792
- }, [symbols]);
4793
- useEffect(() => {
4794
- fetchPrices();
4795
- }, [fetchPrices]);
4796
- useEffect(() => {
4797
- if (!autoRefresh) return;
4798
- const interval = setInterval(fetchPrices, refreshInterval);
4799
- return () => clearInterval(interval);
4800
- }, [autoRefresh, refreshInterval, fetchPrices]);
4801
- return {
4802
- prices,
4803
- isLoading,
4804
- error,
4805
- refetch: fetchPrices
4806
- };
4807
- }
4808
-
4809
- // src/utils/index.ts
4810
- function shortenAddress(address, chars = 4) {
4811
- if (!address) return "";
4812
- return `${address.slice(0, chars + 2)}...${address.slice(-chars)}`;
4813
- }
4814
- function isValidAddress(address) {
4815
- return /^0x[a-fA-F0-9]{40}$/.test(address);
4816
- }
4817
- function checksumAddress(address) {
4818
- return address.toLowerCase();
4819
- }
4820
- function formatNumber(value, options = {}) {
4821
- const { decimals = 2, compact = false, currency, locale = "en-US" } = options;
4822
- if (currency) {
4823
- return new Intl.NumberFormat(locale, {
4824
- style: "currency",
4825
- currency,
4826
- minimumFractionDigits: decimals,
4827
- maximumFractionDigits: decimals,
4828
- notation: compact ? "compact" : "standard"
4829
- }).format(value);
4830
- }
4831
- return new Intl.NumberFormat(locale, {
4832
- minimumFractionDigits: decimals,
4833
- maximumFractionDigits: decimals,
4834
- notation: compact ? "compact" : "standard"
4835
- }).format(value);
4836
- }
4837
- function formatUSD2(value, compact = false) {
4838
- return formatNumber(value, { currency: "USD", compact });
4839
- }
4840
- function formatPercent(value, decimals = 2) {
4841
- const sign = value >= 0 ? "+" : "";
4842
- return `${sign}${value.toFixed(decimals)}%`;
4843
- }
4844
- function formatTokenAmount(amount, decimals = 6) {
4845
- if (amount === 0) return "0";
4846
- if (amount < 1e-6) return "<0.000001";
4847
- if (amount < 1) return amount.toFixed(decimals);
4848
- if (amount < 1e3) return amount.toFixed(4);
4849
- if (amount < 1e6) return formatNumber(amount, { decimals: 2 });
4850
- return formatNumber(amount, { decimals: 2, compact: true });
4851
- }
4852
- function formatDate(date, options = {
4853
- year: "numeric",
4854
- month: "short",
4855
- day: "numeric"
4856
- }) {
4857
- const d = typeof date === "string" ? new Date(date) : date;
4858
- return d.toLocaleDateString("en-US", options);
4859
- }
4860
- function formatDateTime(date) {
4861
- const d = typeof date === "string" ? new Date(date) : date;
4862
- return d.toLocaleString("en-US", {
4863
- year: "numeric",
4864
- month: "short",
4865
- day: "numeric",
4866
- hour: "2-digit",
4867
- minute: "2-digit"
4868
- });
4869
- }
4870
- function formatRelativeTime(date) {
4871
- const d = typeof date === "string" ? new Date(date) : date;
4872
- const now = /* @__PURE__ */ new Date();
4873
- const diffMs = now.getTime() - d.getTime();
4874
- const diffSec = Math.floor(diffMs / 1e3);
4875
- const diffMin = Math.floor(diffSec / 60);
4876
- const diffHour = Math.floor(diffMin / 60);
4877
- const diffDay = Math.floor(diffHour / 24);
4878
- if (diffSec < 60) return "just now";
4879
- if (diffMin < 60) return `${diffMin}m ago`;
4880
- if (diffHour < 24) return `${diffHour}h ago`;
4881
- if (diffDay < 7) return `${diffDay}d ago`;
4882
- return formatDate(d);
4883
- }
4884
- function isValidEmail(email) {
4885
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
4886
- return emailRegex.test(email);
4887
- }
4888
- function isValidPhone(phone) {
4889
- const phoneRegex = /^\+?[1-9]\d{1,14}$/;
4890
- return phoneRegex.test(phone.replace(/[\s-()]/g, ""));
4891
- }
4892
- function capitalize(str) {
4893
- return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
4894
- }
4895
- function truncate(str, length) {
4896
- if (str.length <= length) return str;
4897
- return `${str.slice(0, length)}...`;
4898
- }
4899
- function slugify(str) {
4900
- return str.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
4901
- }
4902
- function sleep(ms) {
4903
- return new Promise((resolve) => setTimeout(resolve, ms));
4904
- }
4905
- async function retry(fn, options = {}) {
4906
- const { maxAttempts = 3, delay = 1e3, backoff = 2 } = options;
4907
- let lastError;
4908
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
4909
- try {
4910
- return await fn();
4911
- } catch (error) {
4912
- lastError = error instanceof Error ? error : new Error(String(error));
4913
- if (attempt < maxAttempts) {
4914
- await sleep(delay * Math.pow(backoff, attempt - 1));
4915
- }
4916
- }
4917
- }
4918
- throw lastError;
4919
- }
4920
- function omit(obj, keys) {
4921
- const result = { ...obj };
4922
- for (const key of keys) {
4923
- delete result[key];
4924
- }
4925
- return result;
4926
- }
4927
- function pick(obj, keys) {
4928
- const result = {};
4929
- for (const key of keys) {
4930
- if (key in obj) {
4931
- result[key] = obj[key];
4932
- }
4933
- }
4934
- return result;
4935
- }
4936
- var OneSDKError = class extends Error {
4937
- constructor(message, code, details) {
4938
- super(message);
4939
- this.name = "OneSDKError";
4940
- this.code = code;
4941
- this.details = details;
4942
- }
4943
- };
4944
- function isOneSDKError(error) {
4945
- return error instanceof OneSDKError;
4946
- }
4947
-
4948
- export { CHAIN_CONFIGS, CHAIN_IDS, COINGECKO_IDS, DEFAULT_CHAIN_ID, OneApproveButton, OneBalanceDisplay, OneBuyBTCWidget, OneBuyETHWidget, OneBuyUSDCWidget, OneBuyUSDTWidget, OneConnectButton, OneConnectButtonFull, OneConnectButtonSimple, OneContext, OneCrossChainSwap, OneCryptoOnlyPayWidget, OneDirectPayWidget, OneEngineClient, OneFiatOnlyPayWidget, OneFundWalletWidget, OneNFTGallery, OneOfframpWidget, OneOnrampWidget, OnePayWidget, OneProvider, OneReceiveWidget, OneSDKError, OneSameChainSwap, OneSellETHWidget, OneSellUSDCWidget, OneSellUSDTWidget, OneSendETHButton, OneSendETHWidget, OneSendUSDCWidget, OneSendWidget, OneSwapWidget, OneThirdwebProvider, OneTransactionButton, OneWalletBalance, PriceService, SUPPORTED_CHAINS, SupabaseService, TOKEN_NAMES, capitalize, checksumAddress, createOneEngineClient, createSupabaseClient, fetchChains, formatDate, formatDateTime, formatNumber, formatPercent, formatRelativeTime, formatTokenAmount, formatUSD2 as formatUSD, getChainById, getChainByName, getChainConfig, getChains, getConfig, getEngineUrl, getRecommendedChains, getSmartWalletChains, initOneSDK, isInitialized, isOneSDKError, isValidAddress, isValidEmail, isValidPhone, omit, pick, priceService, retry, shortenAddress, sleep, slugify, truncate, useOne, useOneAuth, useOneEngine, useOneOnramp, useOneSwap, useOneTrading, useOneWallet, useThirdwebClient, useTokenPrice, useTokenPrices, useWalletBalance2 as useWalletBalance };
4949
- //# sourceMappingURL=index.mjs.map
4950
- //# sourceMappingURL=index.mjs.map