coinley-checkout 0.4.6 → 0.4.9

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.
@@ -2236,7 +2236,7 @@ const names = [
2236
2236
  "finney",
2237
2237
  "ether"
2238
2238
  ];
2239
- function parseUnits$2(value, unit) {
2239
+ function parseUnits$1(value, unit) {
2240
2240
  assertArgument(typeof value === "string", "value must be a string", "value", value);
2241
2241
  let decimals = 18;
2242
2242
  if (typeof unit === "string") {
@@ -2248,8 +2248,8 @@ function parseUnits$2(value, unit) {
2248
2248
  }
2249
2249
  return FixedNumber.fromString(value, { decimals, width: 512 }).value;
2250
2250
  }
2251
- function parseEther$1(ether) {
2252
- return parseUnits$2(ether, 18);
2251
+ function parseEther(ether) {
2252
+ return parseUnits$1(ether, 18);
2253
2253
  }
2254
2254
  const WordSize = 32;
2255
2255
  const Padding = new Uint8Array(WordSize);
@@ -15107,7 +15107,7 @@ _name = new WeakMap();
15107
15107
  _chainId2 = new WeakMap();
15108
15108
  _plugins = new WeakMap();
15109
15109
  let Network = _Network;
15110
- function parseUnits$1(_value2, decimals) {
15110
+ function parseUnits(_value2, decimals) {
15111
15111
  const value = String(_value2);
15112
15112
  if (!value.match(/^[0-9.]+$/)) {
15113
15113
  throw new Error(`invalid gwei value: ${_value2}`);
@@ -15144,8 +15144,8 @@ function getGasStationPlugin(url) {
15144
15144
  const payload = response.bodyJson.standard;
15145
15145
  const feeData = {
15146
15146
  gasPrice: _feeData.gasPrice,
15147
- maxFeePerGas: parseUnits$1(payload.maxFee, 9),
15148
- maxPriorityFeePerGas: parseUnits$1(payload.maxPriorityFee, 9)
15147
+ maxFeePerGas: parseUnits(payload.maxFee, 9),
15148
+ maxPriorityFeePerGas: parseUnits(payload.maxPriorityFee, 9)
15149
15149
  };
15150
15150
  return feeData;
15151
15151
  } catch (error) {
@@ -18491,42 +18491,6 @@ const debugWalletEnvironment = () => {
18491
18491
  const wallets = detectWallets();
18492
18492
  console.log("Detected wallets:", wallets);
18493
18493
  };
18494
- const parseEther = (value) => {
18495
- try {
18496
- if (parseEther$1) {
18497
- return parseEther$1(value);
18498
- }
18499
- if (void 0)
18500
- ;
18501
- const amount = parseFloat(value) * Math.pow(10, 18);
18502
- return {
18503
- toString: () => amount.toLocaleString("fullwide", { useGrouping: false })
18504
- };
18505
- } catch (error) {
18506
- const amount = parseFloat(value) * Math.pow(10, 18);
18507
- return {
18508
- toString: () => amount.toLocaleString("fullwide", { useGrouping: false })
18509
- };
18510
- }
18511
- };
18512
- const parseUnits = (value, decimals) => {
18513
- try {
18514
- if (parseUnits$2) {
18515
- return parseUnits$2(value, decimals);
18516
- }
18517
- if (void 0)
18518
- ;
18519
- const amount = parseFloat(value) * Math.pow(10, decimals);
18520
- return {
18521
- toString: () => amount.toLocaleString("fullwide", { useGrouping: false })
18522
- };
18523
- } catch (error) {
18524
- const amount = parseFloat(value) * Math.pow(10, decimals);
18525
- return {
18526
- toString: () => amount.toLocaleString("fullwide", { useGrouping: false })
18527
- };
18528
- }
18529
- };
18530
18494
  const connectMetamaskWallet = () => __async(void 0, null, function* () {
18531
18495
  console.log("Connecting to MetaMask wallet...");
18532
18496
  if (!window.ethereum || !window.ethereum.isMetaMask) {
@@ -18534,106 +18498,33 @@ const connectMetamaskWallet = () => __async(void 0, null, function* () {
18534
18498
  throw new Error("MetaMask not detected. Please install MetaMask extension.");
18535
18499
  }
18536
18500
  try {
18537
- let provider;
18538
- try {
18539
- provider = new BrowserProvider(window.ethereum);
18540
- const accounts = yield provider.send("eth_requestAccounts", []);
18541
- if (!accounts || accounts.length === 0) {
18542
- throw new Error("No accounts found");
18543
- }
18544
- const address = accounts[0];
18545
- const network = yield provider.getNetwork();
18546
- const chainId = Number(network.chainId);
18547
- let networkType;
18548
- switch (chainId) {
18549
- case 1:
18550
- networkType = NETWORK_TYPES.ETHEREUM;
18551
- break;
18552
- case 56:
18553
- networkType = NETWORK_TYPES.BSC;
18554
- break;
18555
- default:
18556
- networkType = `unknown-${chainId}`;
18557
- }
18558
- return {
18559
- walletType: WALLET_TYPES.METAMASK,
18560
- address,
18561
- provider,
18562
- network: networkType,
18563
- isConnected: true,
18564
- chainId
18565
- };
18566
- } catch (err) {
18567
- console.log("Trying fallback ethers provider pattern");
18568
- if (window.ethereum.request) {
18569
- const accounts = yield window.ethereum.request({ method: "eth_requestAccounts" });
18570
- if (!accounts || accounts.length === 0) {
18571
- throw new Error("No accounts found");
18572
- }
18573
- const address = accounts[0];
18574
- const chainIdHex = yield window.ethereum.request({ method: "eth_chainId" });
18575
- const chainId = parseInt(chainIdHex, 16);
18576
- let networkType;
18577
- switch (chainId) {
18578
- case 1:
18579
- networkType = NETWORK_TYPES.ETHEREUM;
18580
- break;
18581
- case 56:
18582
- networkType = NETWORK_TYPES.BSC;
18583
- break;
18584
- default:
18585
- networkType = `unknown-${chainId}`;
18586
- }
18587
- const simpleProvider = {
18588
- getSigner: () => ({
18589
- getAddress: () => __async(void 0, null, function* () {
18590
- return address;
18591
- }),
18592
- sendTransaction: (tx) => __async(void 0, null, function* () {
18593
- const txHash = yield window.ethereum.request({
18594
- method: "eth_sendTransaction",
18595
- params: [{
18596
- from: address,
18597
- to: tx.to,
18598
- value: tx.value ? tx.value.toString() : "0x0",
18599
- gasLimit: tx.gasLimit ? tx.gasLimit.toString() : void 0,
18600
- data: tx.data
18601
- }]
18602
- });
18603
- return { hash: txHash };
18604
- })
18605
- }),
18606
- estimateGas: (tx) => __async(void 0, null, function* () {
18607
- const gasHex = yield window.ethereum.request({
18608
- method: "eth_estimateGas",
18609
- params: [{
18610
- from: address,
18611
- to: tx.to,
18612
- value: tx.value ? tx.value : "0x0"
18613
- }]
18614
- });
18615
- return {
18616
- toString: () => parseInt(gasHex, 16).toString(),
18617
- mul: (n2) => ({
18618
- div: (d) => ({
18619
- toString: () => Math.floor(parseInt(gasHex, 16) * n2 / d).toString()
18620
- })
18621
- })
18622
- };
18623
- })
18624
- };
18625
- return {
18626
- walletType: WALLET_TYPES.METAMASK,
18627
- address,
18628
- provider: simpleProvider,
18629
- network: networkType,
18630
- isConnected: true,
18631
- chainId
18632
- };
18633
- } else {
18634
- throw new Error("Unsupported wallet interface");
18635
- }
18501
+ const accounts = yield window.ethereum.request({ method: "eth_requestAccounts" });
18502
+ if (!accounts || accounts.length === 0) {
18503
+ throw new Error("No accounts found");
18504
+ }
18505
+ const address = accounts[0];
18506
+ const chainIdHex = yield window.ethereum.request({ method: "eth_chainId" });
18507
+ const chainId = parseInt(chainIdHex, 16);
18508
+ let networkType;
18509
+ switch (chainId) {
18510
+ case 1:
18511
+ networkType = NETWORK_TYPES.ETHEREUM;
18512
+ break;
18513
+ case 56:
18514
+ networkType = NETWORK_TYPES.BSC;
18515
+ break;
18516
+ default:
18517
+ networkType = `unknown-${chainId}`;
18636
18518
  }
18519
+ const web3Provider = new BrowserProvider(window.ethereum);
18520
+ return {
18521
+ walletType: WALLET_TYPES.METAMASK,
18522
+ address,
18523
+ provider: web3Provider,
18524
+ network: networkType,
18525
+ isConnected: true,
18526
+ chainId
18527
+ };
18637
18528
  } catch (error) {
18638
18529
  console.error("Error connecting to MetaMask:", error);
18639
18530
  throw error;
@@ -18646,74 +18537,33 @@ const connectTrustWallet = () => __async(void 0, null, function* () {
18646
18537
  throw new Error("Trust Wallet not detected. Please install Trust Wallet.");
18647
18538
  }
18648
18539
  try {
18649
- if (window.ethereum.request) {
18650
- const accounts = yield window.ethereum.request({ method: "eth_requestAccounts" });
18651
- if (!accounts || accounts.length === 0) {
18652
- throw new Error("No accounts found");
18653
- }
18654
- const address = accounts[0];
18655
- const chainIdHex = yield window.ethereum.request({ method: "eth_chainId" });
18656
- const chainId = parseInt(chainIdHex, 16);
18657
- let networkType;
18658
- switch (chainId) {
18659
- case 1:
18660
- networkType = NETWORK_TYPES.ETHEREUM;
18661
- break;
18662
- case 56:
18663
- networkType = NETWORK_TYPES.BSC;
18664
- break;
18665
- default:
18666
- networkType = `unknown-${chainId}`;
18667
- }
18668
- const simpleProvider = {
18669
- getSigner: () => ({
18670
- getAddress: () => __async(void 0, null, function* () {
18671
- return address;
18672
- }),
18673
- sendTransaction: (tx) => __async(void 0, null, function* () {
18674
- const txHash = yield window.ethereum.request({
18675
- method: "eth_sendTransaction",
18676
- params: [{
18677
- from: address,
18678
- to: tx.to,
18679
- value: tx.value ? tx.value.toString() : "0x0",
18680
- gasLimit: tx.gasLimit ? tx.gasLimit.toString() : void 0,
18681
- data: tx.data
18682
- }]
18683
- });
18684
- return { hash: txHash };
18685
- })
18686
- }),
18687
- estimateGas: (tx) => __async(void 0, null, function* () {
18688
- const gasHex = yield window.ethereum.request({
18689
- method: "eth_estimateGas",
18690
- params: [{
18691
- from: address,
18692
- to: tx.to,
18693
- value: tx.value ? tx.value : "0x0"
18694
- }]
18695
- });
18696
- return {
18697
- toString: () => parseInt(gasHex, 16).toString(),
18698
- mul: (n2) => ({
18699
- div: (d) => ({
18700
- toString: () => Math.floor(parseInt(gasHex, 16) * n2 / d).toString()
18701
- })
18702
- })
18703
- };
18704
- })
18705
- };
18706
- return {
18707
- walletType: WALLET_TYPES.TRUST_WALLET,
18708
- address,
18709
- provider: simpleProvider,
18710
- network: networkType,
18711
- isConnected: true,
18712
- chainId
18713
- };
18714
- } else {
18715
- throw new Error("Unsupported wallet interface");
18540
+ const accounts = yield window.ethereum.request({ method: "eth_requestAccounts" });
18541
+ if (!accounts || accounts.length === 0) {
18542
+ throw new Error("No accounts found");
18543
+ }
18544
+ const address = accounts[0];
18545
+ const chainIdHex = yield window.ethereum.request({ method: "eth_chainId" });
18546
+ const chainId = parseInt(chainIdHex, 16);
18547
+ let networkType;
18548
+ switch (chainId) {
18549
+ case 1:
18550
+ networkType = NETWORK_TYPES.ETHEREUM;
18551
+ break;
18552
+ case 56:
18553
+ networkType = NETWORK_TYPES.BSC;
18554
+ break;
18555
+ default:
18556
+ networkType = `unknown-${chainId}`;
18716
18557
  }
18558
+ const web3Provider = new BrowserProvider(window.ethereum);
18559
+ return {
18560
+ walletType: WALLET_TYPES.TRUST_WALLET,
18561
+ address,
18562
+ provider: web3Provider,
18563
+ network: networkType,
18564
+ isConnected: true,
18565
+ chainId
18566
+ };
18717
18567
  } catch (error) {
18718
18568
  console.error("Error connecting to Trust Wallet:", error);
18719
18569
  throw error;
@@ -18818,7 +18668,7 @@ const sendNativeTransaction = (walletConnection, toAddress, amount) => __async(v
18818
18668
  case WALLET_TYPES.METAMASK:
18819
18669
  case WALLET_TYPES.TRUST_WALLET:
18820
18670
  const provider = walletConnection.provider;
18821
- const signer = provider.getSigner();
18671
+ const signer = yield provider.getSigner();
18822
18672
  const amountInEther = amount.toString();
18823
18673
  const amountWei = parseEther(amountInEther);
18824
18674
  console.log("Sending ETH/BNB:", {
@@ -18827,12 +18677,11 @@ const sendNativeTransaction = (walletConnection, toAddress, amount) => __async(v
18827
18677
  });
18828
18678
  const gasEstimate = yield provider.estimateGas({
18829
18679
  to: toAddress,
18830
- value: amountWei
18680
+ value: amountWei,
18681
+ from: yield signer.getAddress()
18831
18682
  });
18832
18683
  console.log("Gas estimate:", gasEstimate.toString());
18833
- const gasLimit = typeof gasEstimate.mul === "function" ? gasEstimate.mul(110).div(100) : {
18834
- toString: () => Math.floor(parseInt(gasEstimate.toString()) * 1.1).toString()
18835
- };
18684
+ const gasLimit = gasEstimate * BigInt(110) / BigInt(100);
18836
18685
  console.log("Using gas limit:", gasLimit.toString());
18837
18686
  transaction = yield signer.sendTransaction({
18838
18687
  to: toAddress,
@@ -18879,6 +18728,25 @@ const sendNativeTransaction = (walletConnection, toAddress, amount) => __async(v
18879
18728
  throw error;
18880
18729
  }
18881
18730
  });
18731
+ const sendTransaction = (walletConnection, transactionDetails) => __async(void 0, null, function* () {
18732
+ var _a2;
18733
+ console.log("Sending transaction with:", transactionDetails);
18734
+ if (!walletConnection) {
18735
+ throw new Error("Wallet not connected");
18736
+ }
18737
+ const { to, amount, tokenAddress, currency, network } = transactionDetails;
18738
+ if (!to) {
18739
+ throw new Error("Recipient address not provided");
18740
+ }
18741
+ const tokenConfig = (_a2 = TOKEN_CONFIG[currency]) == null ? void 0 : _a2[network];
18742
+ if (tokenConfig && tokenConfig.isNative) {
18743
+ return sendNativeTransaction(walletConnection, to, amount);
18744
+ } else if (tokenConfig) {
18745
+ return sendTokenTransaction(walletConnection, tokenConfig, to, amount);
18746
+ } else {
18747
+ return sendNativeTransaction(walletConnection, to, amount);
18748
+ }
18749
+ });
18882
18750
  const sendTokenTransaction = (walletConnection, tokenConfig, toAddress, amount) => __async(void 0, null, function* () {
18883
18751
  console.log("Sending token transaction with:", { tokenConfig, toAddress, amount });
18884
18752
  if (!walletConnection || !walletConnection.provider) {
@@ -18910,11 +18778,11 @@ const sendERC20Transaction = (walletConnection, tokenConfig, toAddress, amount)
18910
18778
  throw new Error("Wallet not connected");
18911
18779
  }
18912
18780
  const provider = walletConnection.provider;
18913
- const signer = provider.getSigner();
18781
+ const signer = yield provider.getSigner();
18914
18782
  const { contractAddress, decimals, symbol } = tokenConfig;
18915
18783
  const tokenAmount = parseFloat(amount);
18916
18784
  const tokenDecimals = parseInt(decimals);
18917
- const tokenUnits = parseUnits(tokenAmount.toString(), tokenDecimals);
18785
+ const tokenUnits = parseUnits$1(tokenAmount.toString(), tokenDecimals);
18918
18786
  console.log(`Sending ${tokenAmount} ${symbol} (${tokenUnits.toString()} base units) to ${toAddress}`);
18919
18787
  try {
18920
18788
  const tokenContract = new Contract(
@@ -18923,9 +18791,10 @@ const sendERC20Transaction = (walletConnection, tokenConfig, toAddress, amount)
18923
18791
  signer
18924
18792
  );
18925
18793
  try {
18926
- const gasEstimate = yield tokenContract.estimateGas.transfer(toAddress, tokenUnits);
18794
+ const gasEstimate = yield tokenContract.transfer.estimateGas(toAddress, tokenUnits);
18927
18795
  console.log("Gas estimate:", gasEstimate.toString());
18928
- const gasLimit = symbol === "USDC" ? typeof gasEstimate.mul === "function" ? gasEstimate.mul(120).div(100) : { toString: () => Math.floor(parseInt(gasEstimate.toString()) * 1.2).toString() } : typeof gasEstimate.mul === "function" ? gasEstimate.mul(110).div(100) : { toString: () => Math.floor(parseInt(gasEstimate.toString()) * 1.1).toString() };
18796
+ const gasMultiplier = symbol === "USDC" ? BigInt(120) : BigInt(110);
18797
+ const gasLimit = gasEstimate * gasMultiplier / BigInt(100);
18929
18798
  console.log("Using gas limit:", gasLimit.toString());
18930
18799
  const transaction = yield tokenContract.transfer(toAddress, tokenUnits, {
18931
18800
  gasLimit
@@ -18937,7 +18806,8 @@ const sendERC20Transaction = (walletConnection, tokenConfig, toAddress, amount)
18937
18806
  if (symbol === "USDC") {
18938
18807
  console.log("Trying USDC transaction with fixed gas limit");
18939
18808
  const transaction = yield tokenContract.transfer(toAddress, tokenUnits, {
18940
- gasLimit: 15e4
18809
+ gasLimit: BigInt(15e4)
18810
+ // Higher fixed gas limit for USDC
18941
18811
  });
18942
18812
  console.log("Transaction sent with fixed gas limit:", transaction);
18943
18813
  return transaction.hash;
@@ -19034,86 +18904,91 @@ const sendAlgorandAssetTransaction = (walletConnection, tokenConfig, toAddress,
19034
18904
  }
19035
18905
  }
19036
18906
  });
19037
- const sendTransaction = (walletConnection, transactionParams) => __async(void 0, null, function* () {
19038
- console.log("sendTransaction called with:", transactionParams);
19039
- if (!walletConnection) {
19040
- throw new Error("Wallet not connected");
19041
- }
19042
- const { to, toAddress, amount, tokenAddress, tokenConfig, currency, network } = transactionParams;
19043
- const recipientAddress = to || toAddress;
19044
- if (!recipientAddress) {
19045
- throw new Error("Recipient address not provided");
19046
- }
19047
- if (!tokenAddress && !tokenConfig) {
19048
- return sendNativeTransaction(walletConnection, recipientAddress, amount);
19049
- }
19050
- let tokenConfiguration = tokenConfig;
19051
- if (!tokenConfiguration && tokenAddress) {
19052
- tokenConfiguration = {
19053
- contractAddress: tokenAddress,
19054
- decimals: 18,
19055
- symbol: currency || "TOKEN"
19056
- };
19057
- }
19058
- if (!tokenConfiguration) {
19059
- throw new Error("Token configuration not provided");
19060
- }
19061
- return sendTokenTransaction(walletConnection, tokenConfiguration, recipientAddress, amount);
19062
- });
19063
18907
  let apiConfig = {
19064
18908
  apiKey: null,
19065
18909
  apiSecret: null,
19066
18910
  apiUrl: "https://coinleyserver-production.up.railway.app",
19067
- merchantWalletAddresses: {}
19068
- // This will be populated dynamically
18911
+ merchantWalletAddresses: {},
18912
+ authToken: null
19069
18913
  };
19070
- const initializeApi = (config) => {
18914
+ const initializeApi = (config) => __async(void 0, null, function* () {
19071
18915
  apiConfig = __spreadValues(__spreadValues({}, apiConfig), config);
19072
18916
  console.log("API initialized with:", {
19073
18917
  apiUrl: apiConfig.apiUrl,
19074
18918
  apiKey: apiConfig.apiKey ? `${apiConfig.apiKey.substring(0, 6)}...` : null,
19075
18919
  hasWalletAddresses: Object.keys(apiConfig.merchantWalletAddresses || {}).length > 0
19076
18920
  });
19077
- };
19078
- const setMerchantWalletAddresses = (walletAddresses) => {
19079
- apiConfig.merchantWalletAddresses = __spreadValues({}, walletAddresses);
19080
- console.log("Updated merchant wallet addresses:", apiConfig.merchantWalletAddresses);
19081
- };
18921
+ try {
18922
+ yield authenticateAndFetchWallets();
18923
+ } catch (error) {
18924
+ console.error("Failed to fetch merchant wallets during initialization:", error);
18925
+ }
18926
+ });
18927
+ const authenticateAndFetchWallets = () => __async(void 0, null, function* () {
18928
+ try {
18929
+ console.log("Authenticating and fetching merchant wallets...");
18930
+ const tempToken = btoa(`${apiConfig.apiKey}:${apiConfig.apiSecret}`);
18931
+ const response = yield fetch(`${apiConfig.apiUrl}/api/merchants/dashboard`, {
18932
+ method: "GET",
18933
+ headers: {
18934
+ "Content-Type": "application/json",
18935
+ "Authorization": `Bearer ${tempToken}`,
18936
+ "x-api-key": apiConfig.apiKey,
18937
+ "x-api-secret": apiConfig.apiSecret
18938
+ }
18939
+ });
18940
+ if (response.ok) {
18941
+ const data = yield response.json();
18942
+ console.log("Merchant dashboard data received:", data);
18943
+ if (data.merchant) {
18944
+ const walletAddresses = {};
18945
+ if (data.merchant.walletAddress) {
18946
+ walletAddresses.ethereum = data.merchant.walletAddress;
18947
+ }
18948
+ if (data.merchant.solWalletAddress) {
18949
+ walletAddresses.solana = data.merchant.solWalletAddress;
18950
+ }
18951
+ if (data.merchant.merchantWallets) {
18952
+ Object.assign(walletAddresses, data.merchant.merchantWallets);
18953
+ }
18954
+ apiConfig.merchantWalletAddresses = walletAddresses;
18955
+ console.log("Merchant wallet addresses retrieved:", walletAddresses);
18956
+ return walletAddresses;
18957
+ }
18958
+ } else {
18959
+ console.error("Failed to fetch merchant dashboard:", response.status);
18960
+ }
18961
+ } catch (error) {
18962
+ console.error("Error fetching merchant wallets:", error);
18963
+ }
18964
+ return {};
18965
+ });
18966
+ const getMerchantWallets = () => __async(void 0, null, function* () {
18967
+ if (Object.keys(apiConfig.merchantWalletAddresses).length === 0) {
18968
+ yield authenticateAndFetchWallets();
18969
+ }
18970
+ return apiConfig.merchantWalletAddresses;
18971
+ });
19082
18972
  const getHeaders = () => {
19083
18973
  return {
19084
18974
  "Content-Type": "application/json",
19085
18975
  "x-api-key": apiConfig.apiKey,
19086
- "x-api-secret": apiConfig.apiSecret
18976
+ "x-api-secret": apiConfig.apiSecret,
18977
+ "Authorization": apiConfig.authToken ? `Bearer ${apiConfig.authToken}` : void 0
19087
18978
  };
19088
18979
  };
19089
18980
  const createPayment = (paymentData) => __async(void 0, null, function* () {
19090
- var _a2;
19091
18981
  try {
19092
18982
  console.log("Creating payment with data:", paymentData);
19093
- console.log("API URL:", `${apiConfig.apiUrl}/api/payments/create`);
19094
18983
  if (!paymentData.amount) {
19095
18984
  throw new Error("Payment amount is required");
19096
18985
  }
18986
+ const merchantWallets = yield getMerchantWallets();
18987
+ console.log("Using merchant wallets:", merchantWallets);
19097
18988
  const enhancedPaymentData = __spreadProps(__spreadValues({}, paymentData), {
19098
- // Primary recipient address (highest priority)
19099
- recipientAddress: paymentData.recipientAddress || paymentData.toAddress || paymentData.walletAddress,
19100
- // Merchant wallet addresses (for network switching)
19101
- merchantWalletAddresses: __spreadValues(__spreadValues({}, apiConfig.merchantWalletAddresses), paymentData.merchantWalletAddresses),
19102
- // Legacy support
19103
- walletAddress: paymentData.walletAddress || paymentData.recipientAddress || paymentData.toAddress,
19104
- // Alternative naming
19105
- toAddress: paymentData.toAddress || paymentData.recipientAddress || paymentData.walletAddress
19106
- });
19107
- const network = enhancedPaymentData.network || "ethereum";
19108
- const recipientAddress = enhancedPaymentData.recipientAddress || ((_a2 = enhancedPaymentData.merchantWalletAddresses) == null ? void 0 : _a2[network]);
19109
- if (!recipientAddress) {
19110
- throw new Error(`No recipient address provided for network: ${network}. Please configure a wallet address.`);
19111
- }
19112
- console.log("Enhanced payment data:", {
19113
- network,
19114
- recipientAddress,
19115
- merchantWalletAddresses: enhancedPaymentData.merchantWalletAddresses
18989
+ merchantWalletAddresses: __spreadValues(__spreadValues({}, merchantWallets), paymentData.merchantWalletAddresses)
19116
18990
  });
18991
+ console.log("Enhanced payment data:", enhancedPaymentData);
19117
18992
  const response = yield fetch(`${apiConfig.apiUrl}/api/payments/create`, {
19118
18993
  method: "POST",
19119
18994
  headers: getHeaders(),
@@ -19131,10 +19006,7 @@ const createPayment = (paymentData) => __async(void 0, null, function* () {
19131
19006
  throw new Error(errorData.error || `Failed to create payment: ${response.status}`);
19132
19007
  }
19133
19008
  const data = yield response.json();
19134
- console.log("Create payment response data:", data);
19135
- if (data.merchantConfig && data.merchantConfig.walletAddresses) {
19136
- setMerchantWalletAddresses(data.merchantConfig.walletAddresses);
19137
- }
19009
+ console.log("Payment created successfully:", data);
19138
19010
  return data;
19139
19011
  } catch (error) {
19140
19012
  console.error("Create payment error:", error);
@@ -19178,17 +19050,10 @@ const processPayment = (processData) => __async(void 0, null, function* () {
19178
19050
  if (!processData.transactionHash) {
19179
19051
  throw new Error("Transaction hash is required");
19180
19052
  }
19181
- const enhancedProcessData = __spreadProps(__spreadValues({}, processData), {
19182
- // Include timestamp
19183
- processedAt: (/* @__PURE__ */ new Date()).toISOString(),
19184
- // Include source information
19185
- source: "coinley_checkout"
19186
- });
19187
- console.log("API URL:", `${apiConfig.apiUrl}/api/payments/process`);
19188
19053
  const response = yield fetch(`${apiConfig.apiUrl}/api/payments/process`, {
19189
19054
  method: "POST",
19190
19055
  headers: getHeaders(),
19191
- body: JSON.stringify(enhancedProcessData)
19056
+ body: JSON.stringify(processData)
19192
19057
  });
19193
19058
  console.log("Process payment response status:", response.status);
19194
19059
  if (!response.ok) {
@@ -19209,73 +19074,51 @@ const processPayment = (processData) => __async(void 0, null, function* () {
19209
19074
  throw error;
19210
19075
  }
19211
19076
  });
19212
- const getMerchantWallets = (merchantToken) => __async(void 0, null, function* () {
19077
+ const getSupportedNetworks = () => __async(void 0, null, function* () {
19213
19078
  try {
19214
- const response = yield fetch(`${apiConfig.apiUrl}/api/merchants/wallets`, {
19079
+ const response = yield fetch(`${apiConfig.apiUrl}/api/networks`, {
19215
19080
  method: "GET",
19216
- headers: {
19217
- "Content-Type": "application/json",
19218
- "Authorization": `Bearer ${merchantToken}`
19219
- }
19081
+ headers: getHeaders()
19220
19082
  });
19221
19083
  if (!response.ok) {
19222
19084
  let errorData;
19223
19085
  try {
19224
19086
  errorData = yield response.json();
19225
19087
  } catch (e) {
19226
- throw new Error(`Failed to get merchant wallets: ${response.status} ${response.statusText}`);
19088
+ throw new Error(`Failed to get networks: ${response.status} ${response.statusText}`);
19227
19089
  }
19228
- throw new Error(errorData.error || `Failed to get merchant wallets: ${response.status}`);
19090
+ throw new Error(errorData.error || `Failed to get networks: ${response.status}`);
19229
19091
  }
19230
19092
  const data = yield response.json();
19231
- if (data.merchantWallets) {
19232
- setMerchantWalletAddresses(data.merchantWallets);
19233
- }
19234
19093
  return data;
19235
19094
  } catch (error) {
19236
- console.error("Get merchant wallets error:", error);
19095
+ console.error("Get supported networks error:", error);
19237
19096
  throw error;
19238
19097
  }
19239
19098
  });
19240
- const getSupportedNetworks = () => __async(void 0, null, function* () {
19099
+ const validateWalletAddress = (address, network) => __async(void 0, null, function* () {
19241
19100
  try {
19242
- const response = yield fetch(`${apiConfig.apiUrl}/api/networks`, {
19243
- method: "GET",
19244
- headers: getHeaders()
19101
+ const response = yield fetch(`${apiConfig.apiUrl}/api/wallets/validate`, {
19102
+ method: "POST",
19103
+ headers: getHeaders(),
19104
+ body: JSON.stringify({ address, network })
19245
19105
  });
19246
19106
  if (!response.ok) {
19247
19107
  let errorData;
19248
19108
  try {
19249
19109
  errorData = yield response.json();
19250
19110
  } catch (e) {
19251
- throw new Error(`Failed to get networks: ${response.status} ${response.statusText}`);
19111
+ throw new Error(`Failed to validate address: ${response.status} ${response.statusText}`);
19252
19112
  }
19253
- throw new Error(errorData.error || `Failed to get networks: ${response.status}`);
19113
+ throw new Error(errorData.error || `Failed to validate address: ${response.status}`);
19254
19114
  }
19255
19115
  const data = yield response.json();
19256
19116
  return data;
19257
19117
  } catch (error) {
19258
- console.error("Get supported networks error:", error);
19118
+ console.error("Validate wallet address error:", error);
19259
19119
  throw error;
19260
19120
  }
19261
19121
  });
19262
- const validateWalletAddress = (address, network) => {
19263
- if (!address || typeof address !== "string")
19264
- return false;
19265
- switch (network.toLowerCase()) {
19266
- case "ethereum":
19267
- case "bsc":
19268
- return /^0x[a-fA-F0-9]{40}$/.test(address);
19269
- case "tron":
19270
- return /^T[a-zA-Z0-9]{33}$/.test(address);
19271
- case "algorand":
19272
- return /^[A-Z2-7]{58}$/.test(address);
19273
- case "solana":
19274
- return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);
19275
- default:
19276
- return address.length > 10;
19277
- }
19278
- };
19279
19122
  const generateMockTransactionHash = (network = "ethereum") => {
19280
19123
  const prefixes = {
19281
19124
  ethereum: "0x",
@@ -19287,37 +19130,6 @@ const generateMockTransactionHash = (network = "ethereum") => {
19287
19130
  const hash2 = Array.from({ length: 64 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
19288
19131
  return `${prefix}${hash2}`;
19289
19132
  };
19290
- const getMerchantProfile = () => __async(void 0, null, function* () {
19291
- try {
19292
- const response = yield fetch(`${apiConfig.apiUrl}/api/merchants/profile`, {
19293
- method: "GET",
19294
- headers: getHeaders()
19295
- });
19296
- if (!response.ok) {
19297
- let errorData;
19298
- try {
19299
- errorData = yield response.json();
19300
- } catch (e) {
19301
- throw new Error(`Failed to get merchant profile: ${response.status} ${response.statusText}`);
19302
- }
19303
- throw new Error(errorData.error || `Failed to get merchant profile: ${response.status}`);
19304
- }
19305
- const data = yield response.json();
19306
- if (data.merchant && data.merchant.walletAddresses) {
19307
- apiConfig.merchantWalletAddresses = __spreadValues(__spreadValues({}, apiConfig.merchantWalletAddresses), data.merchant.walletAddresses);
19308
- }
19309
- return data;
19310
- } catch (error) {
19311
- console.error("Get merchant profile error:", error);
19312
- throw error;
19313
- }
19314
- });
19315
- const fetchMerchantWalletAddresses = (merchantToken) => __async(void 0, null, function* () {
19316
- return getMerchantWallets(merchantToken);
19317
- });
19318
- const getApiConfig = () => {
19319
- return __spreadValues({}, apiConfig);
19320
- };
19321
19133
  var jsxRuntime = { exports: {} };
19322
19134
  var reactJsxRuntime_production_min = {};
19323
19135
  /**
@@ -19369,45 +19181,55 @@ const CoinleyProvider = ({
19369
19181
  apiSecret,
19370
19182
  apiUrl = "https://coinleyserver-production.up.railway.app",
19371
19183
  merchantWalletAddress = null,
19372
- // New prop for merchant wallet address
19184
+ // Legacy prop for backward compatibility
19373
19185
  merchantSolWalletAddress = null,
19374
- // New prop for Solana wallet address
19186
+ // Legacy prop for backward compatibility
19375
19187
  debug = false,
19376
19188
  children
19377
19189
  }) => {
19378
19190
  const [isInitialized, setIsInitialized] = useState(false);
19379
19191
  const [error, setError] = useState(null);
19380
19192
  const [paymentData, setPaymentData] = useState(null);
19193
+ const [merchantWallets, setMerchantWallets] = useState({});
19381
19194
  useEffect(() => {
19382
19195
  if (!apiKey || !apiSecret) {
19383
19196
  setError("API key and secret are required");
19384
19197
  return;
19385
19198
  }
19386
- try {
19387
- initializeApi({
19388
- apiKey,
19389
- apiSecret,
19390
- apiUrl,
19391
- merchantWalletAddress,
19392
- // Pass wallet address to API service
19393
- merchantSolWalletAddress
19394
- });
19395
- setIsInitialized(true);
19396
- if (debug) {
19397
- console.log("Coinley SDK initialized with:", {
19199
+ const initializeSDK = () => __async(void 0, null, function* () {
19200
+ try {
19201
+ yield initializeApi({
19398
19202
  apiKey,
19203
+ apiSecret,
19399
19204
  apiUrl,
19400
- merchantWalletAddress: merchantWalletAddress ? `${merchantWalletAddress.substring(0, 6)}...${merchantWalletAddress.substring(merchantWalletAddress.length - 4)}` : "Not provided",
19401
- merchantSolWalletAddress: merchantSolWalletAddress ? `${merchantSolWalletAddress.substring(0, 6)}...${merchantSolWalletAddress.substring(merchantSolWalletAddress.length - 4)}` : "Not provided"
19205
+ debug
19402
19206
  });
19207
+ const wallets = yield getMerchantWallets();
19208
+ const allWallets = __spreadValues(__spreadValues(__spreadValues({}, wallets), merchantWalletAddress && { ethereum: merchantWalletAddress }), merchantSolWalletAddress && { solana: merchantSolWalletAddress });
19209
+ setMerchantWallets(allWallets);
19210
+ setIsInitialized(true);
19211
+ if (debug) {
19212
+ console.log("Coinley SDK initialized successfully with wallets:", allWallets);
19213
+ }
19214
+ } catch (err) {
19215
+ setError(err.message);
19216
+ if (debug) {
19217
+ console.error("Coinley SDK initialization error:", err);
19218
+ }
19403
19219
  }
19220
+ });
19221
+ initializeSDK();
19222
+ }, [apiKey, apiSecret, apiUrl, merchantWalletAddress, merchantSolWalletAddress, debug]);
19223
+ const refreshMerchantWallets = () => __async(void 0, null, function* () {
19224
+ try {
19225
+ const wallets = yield getMerchantWallets();
19226
+ setMerchantWallets(wallets);
19227
+ return wallets;
19404
19228
  } catch (err) {
19405
- setError(err.message);
19406
- if (debug) {
19407
- console.error("Coinley SDK initialization error:", err);
19408
- }
19229
+ console.error("Failed to refresh merchant wallets:", err);
19230
+ return merchantWallets;
19409
19231
  }
19410
- }, [apiKey, apiSecret, apiUrl, merchantWalletAddress, merchantSolWalletAddress, debug]);
19232
+ });
19411
19233
  const storePaymentData = (data) => {
19412
19234
  setPaymentData(data);
19413
19235
  return data;
@@ -19417,12 +19239,17 @@ const CoinleyProvider = ({
19417
19239
  apiSecret,
19418
19240
  apiUrl,
19419
19241
  merchantWalletAddress,
19242
+ // Legacy
19420
19243
  merchantSolWalletAddress,
19244
+ // Legacy
19245
+ merchantWallets,
19246
+ // New: All merchant wallets
19421
19247
  isInitialized,
19422
19248
  error,
19423
19249
  debug,
19424
19250
  paymentData,
19425
- storePaymentData
19251
+ storePaymentData,
19252
+ refreshMerchantWallets
19426
19253
  };
19427
19254
  return /* @__PURE__ */ jsxRuntimeExports.jsx(CoinleyContext.Provider, { value, children });
19428
19255
  };
@@ -21464,6 +21291,7 @@ const CoinleyCheckout = forwardRef(({
21464
21291
  customerEmail,
21465
21292
  merchantName = "Merchant",
21466
21293
  merchantWalletAddresses = {},
21294
+ // This will be overridden by backend data
21467
21295
  onSuccess,
21468
21296
  onError,
21469
21297
  onClose,
@@ -21486,31 +21314,34 @@ const CoinleyCheckout = forwardRef(({
21486
21314
  const [walletConnection, setWalletConnection] = useState(null);
21487
21315
  const [availableWallets, setAvailableWallets] = useState({});
21488
21316
  const [step, setStep] = useState("select-currency");
21489
- const [merchantWallets, setMerchantWallets] = useState({});
21490
- const [isLoadingWallets, setIsLoadingWallets] = useState(false);
21317
+ const [actualMerchantWallets, setActualMerchantWallets] = useState({});
21491
21318
  const effectiveApiKey = apiKey || (coinleyContext == null ? void 0 : coinleyContext.apiKey);
21492
21319
  const effectiveApiSecret = apiSecret || (coinleyContext == null ? void 0 : coinleyContext.apiSecret);
21493
21320
  apiUrl || (coinleyContext == null ? void 0 : coinleyContext.apiUrl);
21494
21321
  const effectiveTheme = theme || contextTheme;
21495
21322
  const effectiveDebug = debug || (coinleyContext == null ? void 0 : coinleyContext.debug);
21496
21323
  const effectiveSupportedNetworks = supportedNetworks.length > 0 ? supportedNetworks : [NETWORK_TYPES.ETHEREUM, NETWORK_TYPES.BSC, NETWORK_TYPES.TRON, NETWORK_TYPES.ALGORAND];
21497
- useImperativeHandle(ref, () => ({
21498
- open: (paymentDetails) => {
21499
- handleOpen(paymentDetails);
21500
- },
21501
- close: () => {
21502
- handleClose();
21503
- },
21504
- getPayment: () => payment,
21505
- getWalletConnection: () => walletConnection,
21506
- getMerchantWallets: () => merchantWallets,
21507
- debugWallets: () => debugWalletEnvironment()
21508
- }));
21509
21324
  const log = (message, data) => {
21510
21325
  if (effectiveDebug) {
21511
21326
  console.log(`[Coinley SDK] ${message}`, data);
21512
21327
  }
21513
21328
  };
21329
+ useEffect(() => {
21330
+ const fetchMerchantWallets = () => __async(void 0, null, function* () {
21331
+ try {
21332
+ log("Fetching merchant wallet addresses from backend...");
21333
+ const wallets = yield getMerchantWallets();
21334
+ setActualMerchantWallets(wallets);
21335
+ log("Merchant wallets fetched successfully:", wallets);
21336
+ } catch (error2) {
21337
+ console.error("Failed to fetch merchant wallets:", error2);
21338
+ setActualMerchantWallets(merchantWalletAddresses);
21339
+ }
21340
+ });
21341
+ if (effectiveApiKey && effectiveApiSecret) {
21342
+ fetchMerchantWallets();
21343
+ }
21344
+ }, [effectiveApiKey, effectiveApiSecret, merchantWalletAddresses]);
21514
21345
  useEffect(() => {
21515
21346
  if (typeof window !== "undefined") {
21516
21347
  const detectWalletsAsync = () => __async(void 0, null, function* () {
@@ -21521,44 +21352,18 @@ const CoinleyCheckout = forwardRef(({
21521
21352
  detectWalletsAsync();
21522
21353
  }
21523
21354
  }, [effectiveDebug]);
21524
- useEffect(() => {
21525
- const loadMerchantWallets = () => __async(void 0, null, function* () {
21526
- if (!effectiveApiKey || !effectiveApiSecret) {
21527
- log("No API credentials available for wallet address fetching");
21528
- return;
21529
- }
21530
- setIsLoadingWallets(true);
21531
- try {
21532
- const apiConfig2 = getApiConfig();
21533
- if (apiConfig2.merchantWalletAddresses && Object.keys(apiConfig2.merchantWalletAddresses).length > 0) {
21534
- setMerchantWallets(apiConfig2.merchantWalletAddresses);
21535
- log("Loaded wallet addresses from API config:", apiConfig2.merchantWalletAddresses);
21536
- } else {
21537
- const walletAddresses = yield fetchMerchantWalletAddresses();
21538
- if (walletAddresses && Object.keys(walletAddresses).length > 0) {
21539
- setMerchantWallets(walletAddresses);
21540
- log("Fetched wallet addresses from API:", walletAddresses);
21541
- } else {
21542
- log("No wallet addresses found in API response");
21543
- }
21544
- }
21545
- if (merchantWalletAddresses && Object.keys(merchantWalletAddresses).length > 0) {
21546
- setMerchantWallets((prev) => __spreadValues(__spreadValues({}, prev), merchantWalletAddresses));
21547
- log("Added manual wallet addresses:", merchantWalletAddresses);
21548
- }
21549
- } catch (error2) {
21550
- log("Error loading merchant wallet addresses:", error2);
21551
- console.warn("Could not load merchant wallet addresses:", error2.message);
21552
- if (merchantWalletAddresses && Object.keys(merchantWalletAddresses).length > 0) {
21553
- setMerchantWallets(merchantWalletAddresses);
21554
- log("Using fallback manual wallet addresses:", merchantWalletAddresses);
21555
- }
21556
- } finally {
21557
- setIsLoadingWallets(false);
21558
- }
21559
- });
21560
- loadMerchantWallets();
21561
- }, [effectiveApiKey, effectiveApiSecret, merchantWalletAddresses, effectiveDebug]);
21355
+ useImperativeHandle(ref, () => ({
21356
+ open: (paymentDetails) => {
21357
+ handleOpen(paymentDetails);
21358
+ },
21359
+ close: () => {
21360
+ handleClose();
21361
+ },
21362
+ getPayment: () => payment,
21363
+ getWalletConnection: () => walletConnection,
21364
+ debugWallets: () => debugWalletEnvironment(),
21365
+ getMerchantWallets: () => actualMerchantWallets
21366
+ }));
21562
21367
  const handleOpen = (paymentDetails) => __async(void 0, null, function* () {
21563
21368
  if (!paymentDetails || !paymentDetails.amount) {
21564
21369
  setError("Payment amount is required");
@@ -21571,26 +21376,13 @@ const CoinleyCheckout = forwardRef(({
21571
21376
  setStep("select-currency");
21572
21377
  try {
21573
21378
  log("Creating payment with details:", paymentDetails);
21574
- let finalWalletAddresses = __spreadValues({}, merchantWallets);
21575
- if (Object.keys(finalWalletAddresses).length === 0) {
21576
- log("No wallet addresses available, attempting to fetch...");
21577
- try {
21578
- const fetchedWallets = yield fetchMerchantWalletAddresses();
21579
- if (fetchedWallets) {
21580
- finalWalletAddresses = fetchedWallets;
21581
- setMerchantWallets(fetchedWallets);
21582
- }
21583
- } catch (fetchError) {
21584
- log("Failed to fetch wallet addresses:", fetchError);
21585
- }
21586
- }
21587
- if (paymentDetails.merchantWalletAddresses) {
21588
- finalWalletAddresses = __spreadValues(__spreadValues({}, finalWalletAddresses), paymentDetails.merchantWalletAddresses);
21379
+ let walletAddresses = actualMerchantWallets;
21380
+ if (Object.keys(walletAddresses).length === 0) {
21381
+ log("No wallet addresses found, fetching from backend...");
21382
+ walletAddresses = yield getMerchantWallets();
21383
+ setActualMerchantWallets(walletAddresses);
21589
21384
  }
21590
- if (merchantWalletAddresses) {
21591
- finalWalletAddresses = __spreadValues(__spreadValues({}, finalWalletAddresses), merchantWalletAddresses);
21592
- }
21593
- log("Final wallet addresses for payment:", finalWalletAddresses);
21385
+ log("Using wallet addresses:", walletAddresses);
21594
21386
  const paymentResponse = yield createPayment({
21595
21387
  amount: paymentDetails.amount,
21596
21388
  currency: paymentDetails.currency || "USDT",
@@ -21598,24 +21390,15 @@ const CoinleyCheckout = forwardRef(({
21598
21390
  customerEmail: paymentDetails.customerEmail || customerEmail,
21599
21391
  callbackUrl: paymentDetails.callbackUrl,
21600
21392
  metadata: __spreadProps(__spreadValues({}, paymentDetails.metadata), {
21601
- sdkVersion: "1.0.0",
21602
- merchantWallets: finalWalletAddresses
21393
+ merchantWalletAddresses: walletAddresses
21603
21394
  }),
21604
- merchantWalletAddresses: finalWalletAddresses
21395
+ merchantWalletAddresses: walletAddresses
21605
21396
  });
21606
21397
  log("Payment created:", paymentResponse);
21607
- if (paymentResponse.payment) {
21608
- setPayment(paymentResponse.payment);
21609
- if (paymentResponse.merchantConfig && paymentResponse.merchantConfig.walletAddresses) {
21610
- setMerchantWallets((prev) => __spreadValues(__spreadValues({}, prev), paymentResponse.merchantConfig.walletAddresses));
21611
- log("Updated wallet addresses from payment response:", paymentResponse.merchantConfig.walletAddresses);
21612
- }
21613
- setPaymentStatus("idle");
21614
- setError(null);
21615
- } else {
21616
- throw new Error("Invalid payment response structure");
21617
- }
21618
- log("Payment created and state updated successfully");
21398
+ setPayment(paymentResponse.payment);
21399
+ setPaymentStatus("idle");
21400
+ setError(null);
21401
+ log("Payment created and state updated");
21619
21402
  } catch (err) {
21620
21403
  log("Error creating payment:", err);
21621
21404
  setError(err.message || "Failed to create payment");
@@ -21630,67 +21413,60 @@ const CoinleyCheckout = forwardRef(({
21630
21413
  setWalletConnection(null);
21631
21414
  setSelectedPaymentMethod(null);
21632
21415
  setStep("select-currency");
21633
- setError(null);
21634
21416
  if (onClose)
21635
21417
  onClose();
21636
21418
  };
21637
21419
  const handlePaymentMethodSelect = (paymentMethod) => {
21420
+ console.log("=== PAYMENT METHOD SELECTION DEBUG ===");
21421
+ console.log("1. Payment method selected:", paymentMethod);
21422
+ console.log("2. Current step before:", step);
21638
21423
  log("Payment method selected:", paymentMethod);
21639
21424
  setSelectedPaymentMethod(paymentMethod);
21640
21425
  setStep("confirm");
21426
+ console.log("3. Step should now be: confirm");
21427
+ console.log("=== END PAYMENT METHOD SELECTION DEBUG ===");
21641
21428
  };
21642
21429
  const handleBack = () => {
21643
21430
  if (step === "confirm") {
21644
21431
  setStep("select-currency");
21645
21432
  setWalletConnection(null);
21646
- setError(null);
21647
21433
  } else if (step === "error") {
21648
21434
  setStep("confirm");
21649
- setError(null);
21650
21435
  }
21651
21436
  };
21652
21437
  const handleConnectWallet = (walletType) => __async(void 0, null, function* () {
21438
+ console.log("=== WALLET CONNECTION DEBUG ===");
21439
+ console.log("1. Wallet type requested:", walletType);
21440
+ console.log("2. Selected payment method:", selectedPaymentMethod);
21441
+ console.log("3. Available wallets:", availableWallets);
21442
+ console.log("4. Current step:", step);
21653
21443
  if (!selectedPaymentMethod) {
21444
+ console.error("No payment method selected");
21654
21445
  setError("Please select a payment method first");
21655
21446
  return;
21656
21447
  }
21657
21448
  try {
21449
+ console.log("5. Attempting to connect wallet...");
21658
21450
  setError(null);
21659
21451
  log("Connecting wallet:", { walletType, network: selectedPaymentMethod.network });
21660
21452
  const connection = yield connectWallet(walletType, selectedPaymentMethod.network, 2);
21661
21453
  setWalletConnection(connection);
21662
21454
  setError(null);
21455
+ console.log("6. Connection successful:", connection);
21663
21456
  log("Wallet connected successfully:", connection);
21664
21457
  } catch (err) {
21458
+ console.error("7. Connection failed:", err);
21665
21459
  log("Wallet connection error:", err);
21666
21460
  setError(err.message || "Failed to connect wallet");
21667
21461
  }
21462
+ console.log("=== END WALLET CONNECTION DEBUG ===");
21668
21463
  });
21669
- const getRecipientAddress = () => {
21670
- if (!selectedPaymentMethod)
21671
- return null;
21672
- const network = selectedPaymentMethod.network;
21673
- if (payment && payment.recipientWallet) {
21674
- return payment.recipientWallet;
21675
- }
21676
- if (merchantWallets[network]) {
21677
- return merchantWallets[network];
21678
- }
21679
- if (merchantWalletAddresses[network]) {
21680
- return merchantWalletAddresses[network];
21681
- }
21682
- return null;
21683
- };
21684
21464
  const handlePayment = () => __async(void 0, null, function* () {
21465
+ var _a2, _b;
21685
21466
  if (!payment || !selectedPaymentMethod) {
21686
21467
  setError("Missing payment information");
21687
21468
  return;
21688
21469
  }
21689
- const recipientAddress = getRecipientAddress();
21690
- if (!recipientAddress && !testMode) {
21691
- setError(`No recipient wallet address configured for ${selectedPaymentMethod.network} network`);
21692
- return;
21693
- }
21694
21470
  if (!walletConnection && !testMode) {
21695
21471
  setError("Please connect your wallet first");
21696
21472
  return;
@@ -21705,20 +21481,23 @@ const CoinleyCheckout = forwardRef(({
21705
21481
  log("Test mode: Generating mock transaction...");
21706
21482
  txHash = `test_${Date.now().toString(16)}_${Math.random().toString(16).substring(2, 10)}`;
21707
21483
  } else {
21708
- log("Sending transaction through wallet...", {
21709
- recipientAddress,
21710
- amount: payment.totalAmount || payment.amount,
21711
- network: selectedPaymentMethod.network
21712
- });
21713
- const tokenConfig = payment.token || selectedPaymentMethod.tokenConfig;
21484
+ let merchantAddress;
21485
+ if (payment.recipientWallet) {
21486
+ merchantAddress = payment.recipientWallet;
21487
+ } else if (actualMerchantWallets[selectedPaymentMethod.network]) {
21488
+ merchantAddress = actualMerchantWallets[selectedPaymentMethod.network];
21489
+ } else {
21490
+ throw new Error(`No merchant wallet address found for ${selectedPaymentMethod.network} network`);
21491
+ }
21492
+ log("Using merchant address for payment:", merchantAddress);
21493
+ log("Sending transaction through wallet...");
21714
21494
  txHash = yield sendTransaction(walletConnection, {
21715
- to: recipientAddress,
21495
+ to: merchantAddress,
21716
21496
  amount: payment.totalAmount || payment.amount,
21717
- tokenAddress: tokenConfig == null ? void 0 : tokenConfig.contractAddress,
21718
- tokenDecimals: tokenConfig == null ? void 0 : tokenConfig.decimals,
21497
+ tokenAddress: (_a2 = selectedPaymentMethod.tokenConfig) == null ? void 0 : _a2.address,
21498
+ tokenDecimals: (_b = selectedPaymentMethod.tokenConfig) == null ? void 0 : _b.decimals,
21719
21499
  currency: selectedPaymentMethod.currency,
21720
- network: selectedPaymentMethod.network,
21721
- tokenConfig
21500
+ network: selectedPaymentMethod.network
21722
21501
  });
21723
21502
  }
21724
21503
  log("Transaction hash:", txHash);
@@ -21739,27 +21518,16 @@ const CoinleyCheckout = forwardRef(({
21739
21518
  onSuccess(payment.id, txHash, {
21740
21519
  network: selectedPaymentMethod.network,
21741
21520
  currency: selectedPaymentMethod.currency,
21742
- amount: payment.totalAmount || payment.amount,
21743
- recipientAddress
21521
+ amount: payment.totalAmount || payment.amount
21744
21522
  });
21745
21523
  }
21746
21524
  } catch (err) {
21747
21525
  log("Payment error:", err);
21748
- let errorMessage = err.message || "Failed to process payment";
21749
- if (errorMessage.includes("User rejected") || errorMessage.includes("user rejected")) {
21750
- errorMessage = "Transaction was rejected by user";
21751
- } else if (errorMessage.includes("insufficient funds")) {
21752
- errorMessage = "Insufficient funds in wallet";
21753
- } else if (errorMessage.includes("network")) {
21754
- errorMessage = "Network error. Please check your connection and try again";
21755
- } else if (errorMessage.includes("recipient") || errorMessage.includes("address")) {
21756
- errorMessage = "Invalid recipient address. Please contact support";
21757
- }
21758
- setError(errorMessage);
21526
+ setError(err.message || "Failed to process payment");
21759
21527
  setPaymentStatus("error");
21760
21528
  setStep("error");
21761
21529
  if (onError)
21762
- onError(new Error(errorMessage));
21530
+ onError(err);
21763
21531
  }
21764
21532
  });
21765
21533
  const getSupportedWallets = () => {
@@ -21767,12 +21535,6 @@ const CoinleyCheckout = forwardRef(({
21767
21535
  return [];
21768
21536
  return getSupportedWalletsForNetwork(selectedPaymentMethod.network);
21769
21537
  };
21770
- if (isLoadingWallets) {
21771
- return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/50", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white p-6 rounded-lg shadow-xl", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center space-x-3", children: [
21772
- /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "animate-spin rounded-full h-6 w-6 border-2 border-blue-500 border-t-transparent" }),
21773
- /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-700", children: "Loading payment gateway..." })
21774
- ] }) }) });
21775
- }
21776
21538
  return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: isOpen && /* @__PURE__ */ jsxRuntimeExports.jsx(
21777
21539
  CoinleyModal,
21778
21540
  {
@@ -21795,8 +21557,7 @@ const CoinleyCheckout = forwardRef(({
21795
21557
  availableWallets,
21796
21558
  supportedWallets: getSupportedWallets(),
21797
21559
  step,
21798
- merchantWalletAddresses: merchantWallets,
21799
- recipientAddress: getRecipientAddress(),
21560
+ merchantWalletAddresses: actualMerchantWallets,
21800
21561
  debug: effectiveDebug
21801
21562
  }
21802
21563
  ) });
@@ -21826,7 +21587,7 @@ export {
21826
21587
  createPayment,
21827
21588
  detectWallets,
21828
21589
  generateMockTransactionHash,
21829
- getMerchantProfile,
21590
+ getMerchantWallets,
21830
21591
  getPayment,
21831
21592
  getSupportedNetworks,
21832
21593
  getSupportedWalletsForNetwork,