coinley-checkout 0.4.1 → 0.4.2

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.
@@ -163,42 +163,8 @@ const TOKEN_CONFIG = {
163
163
  }
164
164
  }
165
165
  };
166
- const toHex = (num) => {
167
- return "0x" + Math.floor(parseFloat(num) * Math.pow(10, 18)).toString(16);
168
- };
169
- const calculateTokenAmount = (amount, decimals) => {
170
- console.log("calculateTokenAmount called with:", { amount, decimals });
171
- const tokenDecimals = parseInt(decimals) || 18;
172
- const amountNum = parseFloat(amount);
173
- if (isNaN(amountNum) || amountNum <= 0) {
174
- throw new Error(`Invalid amount: ${amount}`);
175
- }
176
- const multiplier = Math.pow(10, tokenDecimals);
177
- const amountInSmallestUnit = Math.floor(amountNum * multiplier);
178
- const hexAmount = "0x" + amountInSmallestUnit.toString(16);
179
- console.log("Amount calculation:", {
180
- originalAmount: amount,
181
- decimals: tokenDecimals,
182
- multiplier,
183
- calculatedAmount: amountInSmallestUnit,
184
- hexAmount
185
- });
186
- return hexAmount;
187
- };
188
- const getTokenConfig = (currency, network) => {
189
- console.log("getTokenConfig called with:", { currency, network });
190
- const tokenConfig = TOKEN_CONFIG[currency];
191
- if (!tokenConfig) {
192
- throw new Error(`Unsupported currency: ${currency}`);
193
- }
194
- const networkConfig = tokenConfig[network];
195
- if (!networkConfig) {
196
- throw new Error(`Currency ${currency} not supported on network ${network}`);
197
- }
198
- console.log("Token config found:", networkConfig);
199
- return networkConfig;
200
- };
201
166
  const detectWallets = () => {
167
+ var _a;
202
168
  const wallets = {
203
169
  [WALLET_TYPES.METAMASK]: false,
204
170
  [WALLET_TYPES.TRUST_WALLET]: false,
@@ -210,77 +176,54 @@ const detectWallets = () => {
210
176
  }
211
177
  try {
212
178
  console.log("=== ENHANCED WALLET DETECTION DEBUG ===");
179
+ const allProviders = [];
213
180
  if (window.ethereum) {
214
- if (window.ethereum.isMetaMask) {
181
+ allProviders.push(window.ethereum);
182
+ console.log("Found window.ethereum provider");
183
+ }
184
+ if (((_a = window.ethereum) == null ? void 0 : _a.providers) && Array.isArray(window.ethereum.providers)) {
185
+ window.ethereum.providers.forEach((provider) => {
186
+ allProviders.push(provider);
187
+ console.log("Found provider in ethereum.providers array");
188
+ });
189
+ }
190
+ for (const provider of allProviders) {
191
+ if (provider.isMetaMask) {
215
192
  wallets[WALLET_TYPES.METAMASK] = true;
216
- console.log("✅ MetaMask detected via direct isMetaMask");
217
- }
218
- if (window.ethereum.providers && Array.isArray(window.ethereum.providers)) {
219
- const metamaskProvider = window.ethereum.providers.find((p2) => p2.isMetaMask);
220
- if (metamaskProvider) {
221
- wallets[WALLET_TYPES.METAMASK] = true;
222
- console.log("✅ MetaMask detected via providers array");
223
- }
193
+ console.log("✅ MetaMask detected via provider", provider);
194
+ break;
224
195
  }
225
196
  }
226
- if (window.ethereum) {
227
- if (window.ethereum.isTrust || window.ethereum.isTrustWallet) {
197
+ for (const provider of allProviders) {
198
+ if (provider.isTrust || provider.isTrustWallet) {
228
199
  wallets[WALLET_TYPES.TRUST_WALLET] = true;
229
- console.log("✅ Trust Wallet detected via direct property");
230
- }
231
- if (window.ethereum.providers && Array.isArray(window.ethereum.providers)) {
232
- const trustProvider = window.ethereum.providers.find(
233
- (p2) => p2.isTrust || p2.isTrustWallet || p2.constructor && p2.constructor.name === "TrustWallet"
234
- );
235
- if (trustProvider) {
236
- wallets[WALLET_TYPES.TRUST_WALLET] = true;
237
- console.log("✅ Trust Wallet detected via providers array");
238
- }
200
+ console.log("✅ Trust Wallet detected via provider", provider);
201
+ break;
239
202
  }
240
- if (navigator.userAgent && navigator.userAgent.includes("Trust")) {
203
+ }
204
+ if (!wallets[WALLET_TYPES.TRUST_WALLET]) {
205
+ if (window.trustwallet || window.trustWallet) {
241
206
  wallets[WALLET_TYPES.TRUST_WALLET] = true;
242
- console.log("✅ Trust Wallet detected via user agent");
207
+ console.log("✅ Trust Wallet detected via trustwallet object");
243
208
  }
244
- if (window.ethereum.isTrustWallet || window.trustwallet) {
209
+ if (navigator.userAgent && navigator.userAgent.toLowerCase().includes("trust")) {
245
210
  wallets[WALLET_TYPES.TRUST_WALLET] = true;
246
- console.log("✅ Trust Wallet detected via specific methods");
211
+ console.log("✅ Trust Wallet detected via user agent");
247
212
  }
248
213
  }
249
214
  if (window.tronWeb && window.tronWeb.defaultAddress) {
250
215
  wallets[WALLET_TYPES.TRONLINK] = true;
251
216
  console.log("✅ TronLink detected via tronWeb");
252
- }
253
- if (window.tronLink) {
217
+ } else if (window.tronLink) {
254
218
  wallets[WALLET_TYPES.TRONLINK] = true;
255
219
  console.log("✅ TronLink detected via tronLink object");
256
- }
257
- if (window.tron) {
220
+ } else if (window.tron) {
258
221
  wallets[WALLET_TYPES.TRONLINK] = true;
259
222
  console.log("✅ TronLink detected via tron object");
260
223
  }
261
- if (window.tronWeb && (window.tronWeb.ready || window.tronWeb.installed)) {
262
- wallets[WALLET_TYPES.TRONLINK] = true;
263
- console.log("✅ TronLink detected via ready/installed properties");
264
- }
265
224
  if (window.algorand) {
266
- if (window.algorand.isLute) {
267
- wallets[WALLET_TYPES.LUTE] = true;
268
- console.log("✅ Lute Wallet detected via algorand.isLute");
269
- } else {
270
- wallets[WALLET_TYPES.LUTE] = true;
271
- console.log("✅ Algorand wallet detected (assuming Lute)");
272
- }
273
- }
274
- if (window.navigator && window.navigator.userAgent) {
275
- const userAgent = window.navigator.userAgent.toLowerCase();
276
- if (userAgent.includes("trustwallet")) {
277
- wallets[WALLET_TYPES.TRUST_WALLET] = true;
278
- console.log("✅ Trust Wallet detected via mobile user agent");
279
- }
280
- if (userAgent.includes("tronlink")) {
281
- wallets[WALLET_TYPES.TRONLINK] = true;
282
- console.log("✅ TronLink detected via mobile user agent");
283
- }
225
+ wallets[WALLET_TYPES.LUTE] = true;
226
+ console.log("✅ Algorand wallet detected");
284
227
  }
285
228
  console.log("Final wallet detection results:", wallets);
286
229
  console.log("=== END ENHANCED WALLET DETECTION DEBUG ===");
@@ -289,6 +232,22 @@ const detectWallets = () => {
289
232
  }
290
233
  return wallets;
291
234
  };
235
+ const detectWalletsWithRetry = (maxRetries = 3, delay2 = 1e3) => __async(void 0, null, function* () {
236
+ let wallets = detectWallets();
237
+ let attempts = 0;
238
+ while (attempts < maxRetries) {
239
+ if (wallets[WALLET_TYPES.METAMASK] && wallets[WALLET_TYPES.TRUST_WALLET] && wallets[WALLET_TYPES.TRONLINK]) {
240
+ break;
241
+ }
242
+ if (attempts > 0) {
243
+ console.log(`Retrying wallet detection (attempt ${attempts + 1}/${maxRetries})...`);
244
+ yield new Promise((resolve) => setTimeout(resolve, delay2));
245
+ }
246
+ wallets = detectWallets();
247
+ attempts++;
248
+ }
249
+ return wallets;
250
+ });
292
251
  const getSupportedWalletsForNetwork = (network) => {
293
252
  const networkConfig = NETWORK_CONFIG[network];
294
253
  if (!networkConfig)
@@ -296,29 +255,136 @@ const getSupportedWalletsForNetwork = (network) => {
296
255
  const availableWallets = detectWallets();
297
256
  return networkConfig.supportedWallets.filter((wallet) => availableWallets[wallet]);
298
257
  };
299
- const connectWallet = (walletType, network) => __async(void 0, null, function* () {
300
- console.log("connectWallet called with:", { walletType, network });
301
- switch (walletType) {
302
- case WALLET_TYPES.METAMASK:
303
- return yield connectMetaMask(network);
304
- case WALLET_TYPES.TRONLINK:
305
- return yield connectTronLink();
306
- case WALLET_TYPES.TRUST_WALLET:
307
- return yield connectTrustWallet(network);
308
- case WALLET_TYPES.LUTE:
309
- return yield connectLute();
310
- default:
311
- throw new Error(`Unsupported wallet type: ${walletType}`);
258
+ const findMetaMaskProvider = () => {
259
+ var _a, _b;
260
+ let provider = null;
261
+ if (((_a = window.ethereum) == null ? void 0 : _a.providers) && Array.isArray(window.ethereum.providers)) {
262
+ provider = window.ethereum.providers.find((p2) => p2.isMetaMask);
263
+ if (provider) {
264
+ console.log("Found MetaMask in providers array");
265
+ return provider;
266
+ }
267
+ }
268
+ if ((_b = window.ethereum) == null ? void 0 : _b.isMetaMask) {
269
+ console.log("Using main ethereum object for MetaMask");
270
+ return window.ethereum;
271
+ }
272
+ if (window.ethereum) {
273
+ console.warn("No MetaMask-specific provider found, using generic ethereum provider");
274
+ return window.ethereum;
275
+ }
276
+ return null;
277
+ };
278
+ const findTrustWalletProvider = () => {
279
+ var _a, _b, _c;
280
+ let provider = null;
281
+ if (((_a = window.ethereum) == null ? void 0 : _a.providers) && Array.isArray(window.ethereum.providers)) {
282
+ provider = window.ethereum.providers.find((p2) => p2.isTrust || p2.isTrustWallet);
283
+ if (provider) {
284
+ console.log("Found Trust Wallet in providers array");
285
+ return provider;
286
+ }
287
+ }
288
+ if (((_b = window.ethereum) == null ? void 0 : _b.isTrust) || ((_c = window.ethereum) == null ? void 0 : _c.isTrustWallet)) {
289
+ console.log("Using main ethereum object for Trust Wallet");
290
+ return window.ethereum;
291
+ }
292
+ if (window.trustwallet) {
293
+ console.log("Using trustwallet object");
294
+ return window.trustwallet;
295
+ }
296
+ if (window.trustWallet) {
297
+ console.log("Using trustWallet object");
298
+ return window.trustWallet;
299
+ }
300
+ if (navigator.userAgent && navigator.userAgent.toLowerCase().includes("trust")) {
301
+ if (window.ethereum) {
302
+ console.log("Using generic ethereum provider for Trust mobile");
303
+ return window.ethereum;
304
+ }
305
+ }
306
+ return null;
307
+ };
308
+ const calculateTokenAmount = (amount, decimals = 18) => {
309
+ console.log("calculateTokenAmount input:", { amount, decimals });
310
+ const tokenAmount = parseFloat(amount);
311
+ const tokenDecimals = parseInt(decimals);
312
+ if (isNaN(tokenAmount) || tokenAmount <= 0) {
313
+ throw new Error(`Invalid amount: ${amount}`);
314
+ }
315
+ if (isNaN(tokenDecimals) || tokenDecimals < 0) {
316
+ throw new Error(`Invalid decimals: ${decimals}`);
312
317
  }
318
+ try {
319
+ const multiplier = Math.pow(10, tokenDecimals);
320
+ const amountInSmallestUnit = Math.floor(tokenAmount * multiplier);
321
+ console.log("Token amount calculation:", {
322
+ tokenAmount,
323
+ tokenDecimals,
324
+ multiplier,
325
+ amountInSmallestUnit
326
+ });
327
+ return amountInSmallestUnit;
328
+ } catch (error) {
329
+ console.error("Error calculating token amount:", error);
330
+ throw new Error(`Failed to calculate token amount: ${error.message}`);
331
+ }
332
+ };
333
+ const getTokenConfig = (currency, network) => {
334
+ console.log("getTokenConfig called with:", { currency, network });
335
+ const tokenConfig = TOKEN_CONFIG[currency];
336
+ if (!tokenConfig) {
337
+ throw new Error(`Unsupported currency: ${currency}`);
338
+ }
339
+ const networkConfig = tokenConfig[network];
340
+ if (!networkConfig) {
341
+ throw new Error(`Currency ${currency} not supported on network ${network}`);
342
+ }
343
+ console.log("Token config found:", networkConfig);
344
+ return networkConfig;
345
+ };
346
+ const connectWallet = (walletType, network, retryCount = 2) => __async(void 0, null, function* () {
347
+ console.log("connectWallet called with:", { walletType, network, retryCount });
348
+ const attemptConnection = (attempts) => __async(void 0, null, function* () {
349
+ try {
350
+ switch (walletType) {
351
+ case WALLET_TYPES.METAMASK:
352
+ return yield connectMetaMask(network);
353
+ case WALLET_TYPES.TRUST_WALLET:
354
+ return yield connectTrustWallet(network);
355
+ case WALLET_TYPES.TRONLINK:
356
+ return yield connectTronLink();
357
+ case WALLET_TYPES.LUTE:
358
+ return yield connectLute();
359
+ default:
360
+ throw new Error(`Unsupported wallet type: ${walletType}`);
361
+ }
362
+ } catch (error) {
363
+ if (error.code === 4001 || error.message && error.message.includes("rejected")) {
364
+ throw error;
365
+ }
366
+ if (attempts > 0) {
367
+ console.log(`Connection attempt failed, retrying... (${attempts} attempts left)`);
368
+ yield new Promise((resolve) => setTimeout(resolve, delay = 1e3));
369
+ return attemptConnection(attempts - 1);
370
+ }
371
+ throw error;
372
+ }
373
+ });
374
+ return attemptConnection(retryCount);
313
375
  });
314
376
  const connectMetaMask = (network) => __async(void 0, null, function* () {
315
377
  console.log("Attempting to connect MetaMask for network:", network);
316
- if (typeof window === "undefined" || !window.ethereum) {
378
+ if (typeof window === "undefined") {
379
+ throw new Error("Browser environment required");
380
+ }
381
+ const provider = findMetaMaskProvider();
382
+ if (!provider) {
317
383
  throw new Error("MetaMask is not installed. Please install MetaMask extension.");
318
384
  }
319
385
  try {
320
386
  console.log("Requesting accounts from MetaMask...");
321
- const accounts = yield window.ethereum.request({
387
+ const accounts = yield provider.request({
322
388
  method: "eth_requestAccounts"
323
389
  });
324
390
  console.log("Accounts received:", accounts);
@@ -328,12 +394,14 @@ const connectMetaMask = (network) => __async(void 0, null, function* () {
328
394
  const networkConfig = NETWORK_CONFIG[network];
329
395
  if (networkConfig && networkConfig.chainId) {
330
396
  console.log("Switching to network:", networkConfig.chainName);
331
- yield switchEVMNetwork(networkConfig);
397
+ yield switchEVMNetwork(networkConfig, provider);
332
398
  }
333
399
  const connection = {
334
400
  address: accounts[0],
335
401
  network,
336
- walletType: WALLET_TYPES.METAMASK
402
+ walletType: WALLET_TYPES.METAMASK,
403
+ provider
404
+ // Save the successful provider for future transactions
337
405
  };
338
406
  console.log("MetaMask connected successfully:", connection);
339
407
  return connection;
@@ -348,6 +416,48 @@ const connectMetaMask = (network) => __async(void 0, null, function* () {
348
416
  throw new Error(`Failed to connect MetaMask: ${error.message}`);
349
417
  }
350
418
  });
419
+ const connectTrustWallet = (network) => __async(void 0, null, function* () {
420
+ console.log("Attempting to connect Trust Wallet for network:", network);
421
+ if (typeof window === "undefined") {
422
+ throw new Error("Browser environment required");
423
+ }
424
+ const provider = findTrustWalletProvider();
425
+ if (!provider) {
426
+ throw new Error("Trust Wallet is not installed or not detected.");
427
+ }
428
+ try {
429
+ console.log("Requesting accounts from Trust Wallet provider");
430
+ const accounts = yield provider.request({
431
+ method: "eth_requestAccounts"
432
+ });
433
+ console.log("Trust Wallet accounts received:", accounts);
434
+ if (!accounts || accounts.length === 0) {
435
+ throw new Error("No accounts found. Please unlock Trust Wallet.");
436
+ }
437
+ try {
438
+ const networkConfig = NETWORK_CONFIG[network];
439
+ if (networkConfig && networkConfig.chainId) {
440
+ console.log("Switching network in Trust Wallet to:", networkConfig.chainName);
441
+ yield switchEVMNetwork(networkConfig, provider);
442
+ }
443
+ } catch (switchError) {
444
+ console.warn("Network switching failed in Trust Wallet (may not be supported):", switchError);
445
+ }
446
+ return {
447
+ address: accounts[0],
448
+ network,
449
+ walletType: WALLET_TYPES.TRUST_WALLET,
450
+ provider
451
+ // Save the successful provider
452
+ };
453
+ } catch (error) {
454
+ console.error("Trust Wallet connection error:", error);
455
+ if (error.code === 4001) {
456
+ throw new Error("User rejected the connection request");
457
+ }
458
+ throw new Error(`Failed to connect Trust Wallet: ${error.message}`);
459
+ }
460
+ });
351
461
  const connectTronLink = () => __async(void 0, null, function* () {
352
462
  var _a;
353
463
  if (typeof window === "undefined" || !window.tronWeb) {
@@ -358,6 +468,7 @@ const connectTronLink = () => __async(void 0, null, function* () {
358
468
  while (!window.tronWeb.ready && attempts < maxAttempts) {
359
469
  yield new Promise((resolve) => setTimeout(resolve, 1e3));
360
470
  attempts++;
471
+ console.log(`Waiting for TronLink to be ready... Attempt ${attempts}`);
361
472
  }
362
473
  if (!window.tronWeb.ready) {
363
474
  throw new Error("TronLink is not ready. Please unlock your wallet.");
@@ -369,38 +480,12 @@ const connectTronLink = () => __async(void 0, null, function* () {
369
480
  return {
370
481
  address,
371
482
  network: NETWORK_TYPES.TRON,
372
- walletType: WALLET_TYPES.TRONLINK
483
+ walletType: WALLET_TYPES.TRONLINK,
484
+ provider: window.tronWeb
373
485
  };
374
486
  });
375
- const connectTrustWallet = (network) => __async(void 0, null, function* () {
376
- if (typeof window === "undefined" || !window.ethereum || !window.ethereum.isTrust) {
377
- throw new Error("Trust Wallet is not installed.");
378
- }
379
- try {
380
- const accounts = yield window.ethereum.request({
381
- method: "eth_requestAccounts"
382
- });
383
- if (!accounts || accounts.length === 0) {
384
- throw new Error("No accounts found. Please unlock Trust Wallet.");
385
- }
386
- const networkConfig = NETWORK_CONFIG[network];
387
- if (networkConfig && networkConfig.chainId) {
388
- yield switchEVMNetwork(networkConfig);
389
- }
390
- return {
391
- address: accounts[0],
392
- network,
393
- walletType: WALLET_TYPES.TRUST_WALLET
394
- };
395
- } catch (error) {
396
- if (error.code === 4001) {
397
- throw new Error("User rejected the connection request");
398
- }
399
- throw new Error(`Failed to connect Trust Wallet: ${error.message}`);
400
- }
401
- });
402
487
  const connectLute = () => __async(void 0, null, function* () {
403
- if (typeof window === "undefined" || !window.algorand || !window.algorand.isLute) {
488
+ if (typeof window === "undefined" || !window.algorand) {
404
489
  throw new Error("Lute wallet is not installed.");
405
490
  }
406
491
  try {
@@ -411,19 +496,20 @@ const connectLute = () => __async(void 0, null, function* () {
411
496
  return {
412
497
  address: accounts[0],
413
498
  network: NETWORK_TYPES.ALGORAND,
414
- walletType: WALLET_TYPES.LUTE
499
+ walletType: WALLET_TYPES.LUTE,
500
+ provider: window.algorand
415
501
  };
416
502
  } catch (error) {
417
503
  throw new Error(`Failed to connect Lute wallet: ${error.message}`);
418
504
  }
419
505
  });
420
- const switchEVMNetwork = (networkConfig) => __async(void 0, null, function* () {
421
- if (typeof window === "undefined" || !window.ethereum) {
422
- throw new Error("Ethereum provider not found");
506
+ const switchEVMNetwork = (networkConfig, provider) => __async(void 0, null, function* () {
507
+ if (!provider) {
508
+ throw new Error("No provider specified for network switching");
423
509
  }
424
510
  try {
425
511
  console.log("Attempting to switch to:", networkConfig.chainName);
426
- yield window.ethereum.request({
512
+ yield provider.request({
427
513
  method: "wallet_switchEthereumChain",
428
514
  params: [{ chainId: networkConfig.chainId }]
429
515
  });
@@ -432,7 +518,7 @@ const switchEVMNetwork = (networkConfig) => __async(void 0, null, function* () {
432
518
  console.error("Network switch error:", switchError);
433
519
  if (switchError.code === 4902) {
434
520
  try {
435
- yield window.ethereum.request({
521
+ yield provider.request({
436
522
  method: "wallet_addEthereumChain",
437
523
  params: [networkConfig]
438
524
  });
@@ -447,21 +533,48 @@ const switchEVMNetwork = (networkConfig) => __async(void 0, null, function* () {
447
533
  }
448
534
  }
449
535
  });
536
+ const encodeERC20TransferData = (toAddress, amount, decimals) => {
537
+ try {
538
+ const methodId = "0xa9059cbb";
539
+ const cleanAddress = toAddress.toLowerCase().replace("0x", "");
540
+ const paddedAddress = cleanAddress.padStart(64, "0");
541
+ const tokenAmount = calculateTokenAmount(amount, decimals);
542
+ const hexAmount = tokenAmount.toString(16).padStart(64, "0");
543
+ const data = `0x${methodId}${paddedAddress}${hexAmount}`;
544
+ console.log("Encoded ERC20 transfer data:", {
545
+ methodId,
546
+ toAddress: cleanAddress,
547
+ amount,
548
+ tokenAmount,
549
+ hexAmount,
550
+ data
551
+ });
552
+ return data;
553
+ } catch (error) {
554
+ console.error("Error encoding ERC20 transfer data:", error);
555
+ throw new Error(`Failed to encode transfer data: ${error.message}`);
556
+ }
557
+ };
450
558
  const sendTransaction = (walletConnection, transactionData) => __async(void 0, null, function* () {
451
- const { walletType, network, address } = walletConnection;
559
+ const { walletType, network, address, provider } = walletConnection;
452
560
  const { to, amount, tokenAddress, tokenDecimals, currency } = transactionData;
453
- console.log("sendTransaction called with:", { walletConnection, transactionData });
561
+ console.log("sendTransaction called with:", {
562
+ walletConnection: { walletType, network, address, hasProvider: !!provider },
563
+ transactionData
564
+ });
454
565
  switch (walletType) {
455
566
  case WALLET_TYPES.METAMASK:
456
567
  case WALLET_TYPES.TRUST_WALLET:
457
- return yield sendEVMTransactionNative(
568
+ return yield sendEVMTransaction(
458
569
  address,
459
570
  to,
460
571
  amount,
461
572
  tokenAddress,
462
573
  tokenDecimals,
463
574
  currency,
464
- network
575
+ network,
576
+ provider
577
+ // Pass the provider that was used for connection
465
578
  );
466
579
  case WALLET_TYPES.TRONLINK:
467
580
  return yield sendTronTransaction(to, amount, tokenAddress, tokenDecimals);
@@ -471,8 +584,8 @@ const sendTransaction = (walletConnection, transactionData) => __async(void 0, n
471
584
  throw new Error(`Unsupported wallet type: ${walletType}`);
472
585
  }
473
586
  });
474
- const sendEVMTransactionNative = (from, to, amount, tokenAddress, tokenDecimals, currency, network) => __async(void 0, null, function* () {
475
- console.log("sendEVMTransactionNative called with:", {
587
+ const sendEVMTransaction = (from, to, amount, tokenAddress, tokenDecimals, currency, network, provider) => __async(void 0, null, function* () {
588
+ console.log("sendEVMTransaction called with:", {
476
589
  from,
477
590
  to,
478
591
  amount,
@@ -481,7 +594,8 @@ const sendEVMTransactionNative = (from, to, amount, tokenAddress, tokenDecimals,
481
594
  currency,
482
595
  network
483
596
  });
484
- if (typeof window === "undefined" || !window.ethereum) {
597
+ const ethProvider = provider || window.ethereum;
598
+ if (!ethProvider) {
485
599
  throw new Error("Ethereum provider not found");
486
600
  }
487
601
  try {
@@ -503,48 +617,40 @@ const sendEVMTransactionNative = (from, to, amount, tokenAddress, tokenDecimals,
503
617
  }
504
618
  }
505
619
  if (actualTokenAddress && actualTokenAddress !== "native") {
506
- console.log("Preparing ERC20 token transfer...");
507
- const decimals = actualDecimals || 18;
508
- const amountHex = calculateTokenAmount(amount, decimals);
509
- const transferMethodId = "0xa9059cbb";
510
- const paddedToAddress = to.replace("0x", "").toLowerCase().padStart(64, "0");
511
- const paddedAmount = amountHex.replace("0x", "").padStart(64, "0");
512
- const data = transferMethodId + paddedToAddress + paddedAmount;
620
+ console.log("Preparing ERC20 token transfer for:", currency);
621
+ const data = encodeERC20TransferData(to, amount, actualDecimals);
513
622
  console.log("ERC20 transaction details:", {
514
- currency,
515
- tokenAddress: actualTokenAddress,
516
- decimals,
517
- amountHex,
518
- transferMethodId,
519
- paddedToAddress,
520
- paddedAmount,
521
- data
623
+ from,
624
+ to: actualTokenAddress,
625
+ data,
626
+ gas: "0x30D40"
627
+ // 200,000 gas
522
628
  });
523
- const txHash = yield window.ethereum.request({
629
+ const txHash = yield ethProvider.request({
524
630
  method: "eth_sendTransaction",
525
631
  params: [{
526
632
  from,
527
633
  to: actualTokenAddress,
528
- // Send to token contract
529
634
  data,
530
- gas: "0x15F90"
531
- // 90000 gas limit for token transfers
635
+ gas: "0x30D40"
636
+ // 200,000 gas
532
637
  }]
533
638
  });
534
639
  console.log("ERC20 transaction successful:", txHash);
535
640
  return txHash;
536
641
  } else {
537
- console.log("Preparing native token transfer...");
538
- const amountHex = toHex(amount);
539
- console.log("Native transaction amount:", { amount, amountHex });
540
- const txHash = yield window.ethereum.request({
642
+ console.log("Preparing native token transfer");
643
+ const amountInWei = calculateTokenAmount(amount, 18);
644
+ const amountHex = "0x" + amountInWei.toString(16);
645
+ console.log("Native transaction amount:", { amount, amountInWei, amountHex });
646
+ const txHash = yield ethProvider.request({
541
647
  method: "eth_sendTransaction",
542
648
  params: [{
543
649
  from,
544
650
  to,
545
651
  value: amountHex,
546
652
  gas: "0x5208"
547
- // 21000 gas limit for simple transfer
653
+ // 21000 gas for simple transfer
548
654
  }]
549
655
  });
550
656
  console.log("Native transaction successful:", txHash);
@@ -558,9 +664,6 @@ const sendEVMTransactionNative = (from, to, amount, tokenAddress, tokenDecimals,
558
664
  if (error.message && error.message.includes("insufficient funds")) {
559
665
  throw new Error("Insufficient balance to complete the transaction");
560
666
  }
561
- if (error.message && error.message.includes("gas")) {
562
- throw new Error("Transaction failed due to gas estimation issues. Please try again.");
563
- }
564
667
  throw new Error(`Transaction failed: ${error.message || "Unknown error"}`);
565
668
  }
566
669
  });
@@ -569,19 +672,24 @@ const sendTronTransaction = (to, amount, tokenAddress, tokenDecimals) => __async
569
672
  throw new Error("TronLink is not ready");
570
673
  }
571
674
  try {
572
- const amountInSun = Math.floor(parseFloat(amount) * Math.pow(10, tokenDecimals || 6));
675
+ const amountInSun = calculateTokenAmount(amount, tokenDecimals || 6);
573
676
  if (tokenAddress && tokenAddress !== "native") {
677
+ console.log("Sending TRC20 token:", { to, amount, tokenAddress, amountInSun });
574
678
  const contract = yield window.tronWeb.contract().at(tokenAddress);
575
679
  const result = yield contract.transfer(to, amountInSun).send({
576
680
  feeLimit: 1e8,
577
681
  callValue: 0
578
682
  });
683
+ console.log("TRC20 transfer result:", result);
579
684
  return result;
580
685
  } else {
686
+ console.log("Sending native TRX:", { to, amount, amountInSun });
581
687
  const result = yield window.tronWeb.trx.sendTransaction(to, amountInSun);
688
+ console.log("TRX transfer result:", result);
582
689
  return result.txid;
583
690
  }
584
691
  } catch (error) {
692
+ console.error("Tron transaction error:", error);
585
693
  throw new Error(`TRON transaction failed: ${error.message}`);
586
694
  }
587
695
  });
@@ -590,17 +698,20 @@ const sendAlgorandTransaction = (from, to, amount) => __async(void 0, null, func
590
698
  throw new Error("Algorand wallet is not available");
591
699
  }
592
700
  try {
593
- const microAlgos = Math.floor(parseFloat(amount) * 1e6);
701
+ const microAlgos = calculateTokenAmount(amount, 6);
594
702
  const txn = {
595
703
  from,
596
704
  to,
597
705
  amount: microAlgos,
598
706
  type: "pay"
599
707
  };
708
+ console.log("Sending Algorand transaction:", txn);
600
709
  const signedTxn = yield window.algorand.signTransaction(txn);
601
710
  const result = yield window.algorand.sendTransaction(signedTxn);
711
+ console.log("Algorand transaction result:", result);
602
712
  return result.txId;
603
713
  } catch (error) {
714
+ console.error("Algorand transaction error:", error);
604
715
  throw new Error(`Algorand transaction failed: ${error.message}`);
605
716
  }
606
717
  });
@@ -613,12 +724,40 @@ const getWalletInstallUrl = (walletType) => {
613
724
  };
614
725
  return urls[walletType] || "";
615
726
  };
727
+ const debugWalletEnvironment = () => {
728
+ var _a;
729
+ console.group("Wallet Environment Debug");
730
+ console.log("User Agent:", navigator.userAgent);
731
+ console.log("Main ethereum object:", window.ethereum);
732
+ if ((_a = window.ethereum) == null ? void 0 : _a.providers) {
733
+ console.log("Providers array:");
734
+ window.ethereum.providers.forEach((p2, i) => {
735
+ var _a2;
736
+ console.log(`Provider ${i}:`, {
737
+ isMetaMask: p2.isMetaMask,
738
+ isTrust: p2.isTrust,
739
+ isTrustWallet: p2.isTrustWallet,
740
+ constructor: (_a2 = p2.constructor) == null ? void 0 : _a2.name
741
+ });
742
+ });
743
+ }
744
+ console.log("TronWeb object:", window.tronWeb);
745
+ console.log("TronLink object:", window.tronLink);
746
+ console.log("Tron object:", window.tron);
747
+ console.log("Algorand object:", window.algorand);
748
+ console.log("Trust wallet objects:", {
749
+ trustwallet: window.trustwallet,
750
+ trustWallet: window.trustWallet
751
+ });
752
+ console.groupEnd();
753
+ return detectWallets();
754
+ };
616
755
  let apiConfig = {
617
756
  apiKey: null,
618
757
  apiSecret: null,
619
758
  apiUrl: "http://localhost:9000",
620
759
  merchantWalletAddresses: {}
621
- // Changed to object for multi-network support
760
+ // Object for multi-network support
622
761
  };
623
762
  const initializeApi = (config) => {
624
763
  apiConfig = __spreadValues(__spreadValues({}, apiConfig), config);
@@ -639,6 +778,9 @@ const createPayment = (paymentData) => __async(void 0, null, function* () {
639
778
  try {
640
779
  console.log("Creating payment with data:", paymentData);
641
780
  console.log("API URL:", `${apiConfig.apiUrl}/api/payments/create`);
781
+ if (!paymentData.amount) {
782
+ throw new Error("Payment amount is required");
783
+ }
642
784
  const enhancedPaymentData = __spreadProps(__spreadValues({}, paymentData), {
643
785
  merchantWalletAddresses: __spreadValues(__spreadValues({}, apiConfig.merchantWalletAddresses), paymentData.merchantWalletAddresses)
644
786
  });
@@ -649,7 +791,12 @@ const createPayment = (paymentData) => __async(void 0, null, function* () {
649
791
  });
650
792
  console.log("Create payment response status:", response.status);
651
793
  if (!response.ok) {
652
- const errorData = yield response.json();
794
+ let errorData;
795
+ try {
796
+ errorData = yield response.json();
797
+ } catch (e) {
798
+ throw new Error(`Failed to create payment: ${response.status} ${response.statusText}`);
799
+ }
653
800
  console.error("Error creating payment:", errorData);
654
801
  throw new Error(errorData.error || `Failed to create payment: ${response.status}`);
655
802
  }
@@ -664,12 +811,20 @@ const createPayment = (paymentData) => __async(void 0, null, function* () {
664
811
  const getPayment = (paymentId) => __async(void 0, null, function* () {
665
812
  try {
666
813
  console.log("Getting payment:", paymentId);
814
+ if (!paymentId) {
815
+ throw new Error("Payment ID is required");
816
+ }
667
817
  const response = yield fetch(`${apiConfig.apiUrl}/api/payments/${paymentId}`, {
668
818
  method: "GET",
669
819
  headers: getHeaders()
670
820
  });
671
821
  if (!response.ok) {
672
- const errorData = yield response.json();
822
+ let errorData;
823
+ try {
824
+ errorData = yield response.json();
825
+ } catch (e) {
826
+ throw new Error(`Failed to get payment: ${response.status} ${response.statusText}`);
827
+ }
673
828
  console.error("Error getting payment:", errorData);
674
829
  throw new Error(errorData.error || `Failed to get payment: ${response.status}`);
675
830
  }
@@ -684,6 +839,12 @@ const getPayment = (paymentId) => __async(void 0, null, function* () {
684
839
  const processPayment = (processData) => __async(void 0, null, function* () {
685
840
  try {
686
841
  console.log("Processing payment with data:", processData);
842
+ if (!processData.paymentId) {
843
+ throw new Error("Payment ID is required");
844
+ }
845
+ if (!processData.transactionHash) {
846
+ throw new Error("Transaction hash is required");
847
+ }
687
848
  console.log("API URL:", `${apiConfig.apiUrl}/api/payments/process`);
688
849
  const response = yield fetch(`${apiConfig.apiUrl}/api/payments/process`, {
689
850
  method: "POST",
@@ -692,7 +853,12 @@ const processPayment = (processData) => __async(void 0, null, function* () {
692
853
  });
693
854
  console.log("Process payment response status:", response.status);
694
855
  if (!response.ok) {
695
- const errorData = yield response.json();
856
+ let errorData;
857
+ try {
858
+ errorData = yield response.json();
859
+ } catch (e) {
860
+ throw new Error(`Failed to process payment: ${response.status} ${response.statusText}`);
861
+ }
696
862
  console.error("Error processing payment:", errorData);
697
863
  throw new Error(errorData.error || `Failed to process payment: ${response.status}`);
698
864
  }
@@ -711,7 +877,12 @@ const getSupportedNetworks = () => __async(void 0, null, function* () {
711
877
  headers: getHeaders()
712
878
  });
713
879
  if (!response.ok) {
714
- const errorData = yield response.json();
880
+ let errorData;
881
+ try {
882
+ errorData = yield response.json();
883
+ } catch (e) {
884
+ throw new Error(`Failed to get networks: ${response.status} ${response.statusText}`);
885
+ }
715
886
  throw new Error(errorData.error || `Failed to get networks: ${response.status}`);
716
887
  }
717
888
  const data = yield response.json();
@@ -728,7 +899,12 @@ const getMerchantProfile = () => __async(void 0, null, function* () {
728
899
  headers: getHeaders()
729
900
  });
730
901
  if (!response.ok) {
731
- const errorData = yield response.json();
902
+ let errorData;
903
+ try {
904
+ errorData = yield response.json();
905
+ } catch (e) {
906
+ throw new Error(`Failed to get merchant profile: ${response.status} ${response.statusText}`);
907
+ }
732
908
  throw new Error(errorData.error || `Failed to get merchant profile: ${response.status}`);
733
909
  }
734
910
  const data = yield response.json();
@@ -749,7 +925,12 @@ const validateWalletAddress = (address, network) => __async(void 0, null, functi
749
925
  body: JSON.stringify({ address, network })
750
926
  });
751
927
  if (!response.ok) {
752
- const errorData = yield response.json();
928
+ let errorData;
929
+ try {
930
+ errorData = yield response.json();
931
+ } catch (e) {
932
+ throw new Error(`Failed to validate address: ${response.status} ${response.statusText}`);
933
+ }
753
934
  throw new Error(errorData.error || `Failed to validate address: ${response.status}`);
754
935
  }
755
936
  const data = yield response.json();
@@ -2464,6 +2645,7 @@ const PaymentMethods = ({ onSelect, selected, theme = "light", supportedNetworks
2464
2645
  const walletNames = {
2465
2646
  [WALLET_TYPES.METAMASK]: "MetaMask",
2466
2647
  [WALLET_TYPES.TRONLINK]: "TronLink",
2648
+ [WALLET_TYPES.TRUST_WALLET]: "Trust Wallet",
2467
2649
  [WALLET_TYPES.LUTE]: "Lute Wallet"
2468
2650
  };
2469
2651
  return isAvailable ? `${walletNames[wallet]} detected - Ready to pay` : `${walletNames[wallet]} required - Please install to continue`;
@@ -2556,7 +2738,8 @@ const CoinleyModal = ({
2556
2738
  availableWallets = {},
2557
2739
  supportedWallets = [],
2558
2740
  step = "select-currency",
2559
- merchantWalletAddresses = {}
2741
+ merchantWalletAddresses = {},
2742
+ debug = false
2560
2743
  }) => {
2561
2744
  const [paymentType, setPaymentType] = useState("wallet");
2562
2745
  const getWalletAddressForNetwork = () => {
@@ -2641,6 +2824,20 @@ const CoinleyModal = ({
2641
2824
  "..."
2642
2825
  ] }) })
2643
2826
  ] }),
2827
+ debug && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mb-2 text-right", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
2828
+ "button",
2829
+ {
2830
+ onClick: () => {
2831
+ console.log("=== DEBUG INFO ===");
2832
+ console.log("Current step:", step);
2833
+ console.log("Payment method:", selectedPaymentMethod);
2834
+ console.log("Wallet connection:", walletConnection);
2835
+ debugWalletEnvironment();
2836
+ },
2837
+ className: "text-xs bg-gray-200 p-1 rounded",
2838
+ children: "Debug"
2839
+ }
2840
+ ) }),
2644
2841
  step === "select-currency" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
2645
2842
  /* @__PURE__ */ jsxRuntimeExports.jsx(
2646
2843
  PaymentMethods,
@@ -2793,6 +2990,7 @@ const CoinleyModal = ({
2793
2990
  ] }) }, walletType)) })
2794
2991
  ] })
2795
2992
  ),
2993
+ error && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 rounded-lg bg-red-50 mb-4 text-red-600 text-sm", children: error }),
2796
2994
  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
2797
2995
  /* @__PURE__ */ jsxRuntimeExports.jsx(
2798
2996
  "button",
@@ -2937,7 +3135,8 @@ const CoinleyCheckout = forwardRef(({
2937
3135
  handleClose();
2938
3136
  },
2939
3137
  getPayment: () => payment,
2940
- getWalletConnection: () => walletConnection
3138
+ getWalletConnection: () => walletConnection,
3139
+ debugWallets: () => debugWalletEnvironment()
2941
3140
  }));
2942
3141
  const log = (message, data) => {
2943
3142
  if (effectiveDebug) {
@@ -2946,9 +3145,12 @@ const CoinleyCheckout = forwardRef(({
2946
3145
  };
2947
3146
  useEffect(() => {
2948
3147
  if (typeof window !== "undefined") {
2949
- const wallets = detectWallets();
2950
- setAvailableWallets(wallets);
2951
- log("Available wallets detected:", wallets);
3148
+ const detectWalletsAsync = () => __async(void 0, null, function* () {
3149
+ const wallets = yield detectWalletsWithRetry(3, 1e3);
3150
+ setAvailableWallets(wallets);
3151
+ log("Available wallets detected:", wallets);
3152
+ });
3153
+ detectWalletsAsync();
2952
3154
  }
2953
3155
  }, [effectiveDebug]);
2954
3156
  const handleOpen = (paymentDetails) => __async(void 0, null, function* () {
@@ -3008,6 +3210,8 @@ const CoinleyCheckout = forwardRef(({
3008
3210
  if (step === "confirm") {
3009
3211
  setStep("select-currency");
3010
3212
  setWalletConnection(null);
3213
+ } else if (step === "error") {
3214
+ setStep("confirm");
3011
3215
  }
3012
3216
  };
3013
3217
  const handleConnectWallet = (walletType) => __async(void 0, null, function* () {
@@ -3025,7 +3229,7 @@ const CoinleyCheckout = forwardRef(({
3025
3229
  console.log("5. Attempting to connect wallet...");
3026
3230
  setError(null);
3027
3231
  log("Connecting wallet:", { walletType, network: selectedPaymentMethod.network });
3028
- const connection = yield connectWallet(walletType, selectedPaymentMethod.network);
3232
+ const connection = yield connectWallet(walletType, selectedPaymentMethod.network, 2);
3029
3233
  setWalletConnection(connection);
3030
3234
  setError(null);
3031
3235
  console.log("6. Connection successful:", connection);
@@ -3050,6 +3254,7 @@ const CoinleyCheckout = forwardRef(({
3050
3254
  log("Starting payment process...");
3051
3255
  setPaymentStatus("loading");
3052
3256
  setTransactionHash(null);
3257
+ setStep("processing");
3053
3258
  try {
3054
3259
  let txHash;
3055
3260
  if (testMode) {
@@ -3065,7 +3270,9 @@ const CoinleyCheckout = forwardRef(({
3065
3270
  to: merchantAddress,
3066
3271
  amount: payment.amount,
3067
3272
  tokenAddress: (_a = selectedPaymentMethod.tokenConfig) == null ? void 0 : _a.address,
3068
- tokenDecimals: (_b = selectedPaymentMethod.tokenConfig) == null ? void 0 : _b.decimals
3273
+ tokenDecimals: (_b = selectedPaymentMethod.tokenConfig) == null ? void 0 : _b.decimals,
3274
+ currency: selectedPaymentMethod.currency,
3275
+ network: selectedPaymentMethod.network
3069
3276
  });
3070
3277
  }
3071
3278
  log("Transaction hash:", txHash);
@@ -3125,7 +3332,8 @@ const CoinleyCheckout = forwardRef(({
3125
3332
  availableWallets,
3126
3333
  supportedWallets: getSupportedWallets(),
3127
3334
  step,
3128
- merchantWalletAddresses
3335
+ merchantWalletAddresses,
3336
+ debug: effectiveDebug
3129
3337
  }
3130
3338
  ) });
3131
3339
  });