coinley-checkout 0.4.5 → 0.4.8

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.
@@ -1206,9 +1206,6 @@ function parseUnits(value, unit) {
1206
1206
  }
1207
1207
  return FixedNumber.fromString(value, { decimals, width: 512 }).value;
1208
1208
  }
1209
- function parseEther(ether) {
1210
- return parseUnits(ether, 18);
1211
- }
1212
1209
  const WordSize = 32;
1213
1210
  const Padding = new Uint8Array(WordSize);
1214
1211
  const passProperties$1 = ["then"];
@@ -7780,46 +7777,6 @@ const TOKEN_CONFIG = {
7780
7777
  symbol: "ALGO",
7781
7778
  isNative: true
7782
7779
  }
7783
- },
7784
- DAI: {
7785
- ethereum: {
7786
- contractAddress: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
7787
- decimals: 18,
7788
- symbol: "DAI"
7789
- }
7790
- },
7791
- FRAX: {
7792
- ethereum: {
7793
- contractAddress: "0x853d955aCEf822Db058eb8505911ED77F175b99e",
7794
- decimals: 18,
7795
- symbol: "FRAX"
7796
- },
7797
- bsc: {
7798
- contractAddress: "0x90C97F71E18723b0Cf0dfa30ee176Ab653E89F40",
7799
- decimals: 18,
7800
- symbol: "FRAX"
7801
- }
7802
- },
7803
- PYUSD: {
7804
- ethereum: {
7805
- contractAddress: "0x6c3ea9036406852006290770BEdFcAbA0e23A0e8",
7806
- decimals: 6,
7807
- symbol: "PYUSD"
7808
- }
7809
- },
7810
- BUSD: {
7811
- bsc: {
7812
- contractAddress: "0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56",
7813
- decimals: 18,
7814
- symbol: "BUSD"
7815
- }
7816
- },
7817
- USDJ: {
7818
- tron: {
7819
- contractAddress: "TMwFHYXLJaRUPeW6421aqXL4ZEzPRFGkGT",
7820
- decimals: 18,
7821
- symbol: "USDJ"
7822
- }
7823
7780
  }
7824
7781
  };
7825
7782
  const NETWORK_WALLET_MAP = {
@@ -7839,7 +7796,7 @@ const getWalletInstallUrl = (walletType) => {
7839
7796
  };
7840
7797
  const detectWallets = () => {
7841
7798
  const availableWallets = {
7842
- [WALLET_TYPES.METAMASK]: typeof window !== "undefined" && window.ethereum !== void 0 && window.ethereum.isMetaMask === true,
7799
+ [WALLET_TYPES.METAMASK]: typeof window !== "undefined" && window.ethereum !== void 0,
7843
7800
  [WALLET_TYPES.TRONLINK]: typeof window !== "undefined" && window.tronWeb !== void 0,
7844
7801
  [WALLET_TYPES.TRUST_WALLET]: typeof window !== "undefined" && window.ethereum !== void 0 && window.ethereum.isTrust === true,
7845
7802
  [WALLET_TYPES.LUTE]: typeof window !== "undefined" && window.lute !== void 0
@@ -7881,17 +7838,27 @@ const debugWalletEnvironment = () => {
7881
7838
  const wallets = detectWallets();
7882
7839
  console.log("Detected wallets:", wallets);
7883
7840
  };
7841
+ const createEthersValue = (amount, decimals) => {
7842
+ try {
7843
+ return parseUnits(amount.toString(), decimals);
7844
+ } catch (error) {
7845
+ const value = parseFloat(amount) * Math.pow(10, decimals);
7846
+ return {
7847
+ toString: () => value.toLocaleString("fullwide", { useGrouping: false }),
7848
+ toBigInt: () => BigInt(Math.floor(value))
7849
+ };
7850
+ }
7851
+ };
7884
7852
  const connectMetamaskWallet = () => __async(void 0, null, function* () {
7885
7853
  console.log("Connecting to MetaMask wallet...");
7886
7854
  if (!window.ethereum || !window.ethereum.isMetaMask) {
7855
+ console.error("MetaMask not found.");
7887
7856
  throw new Error("MetaMask not detected. Please install MetaMask extension.");
7888
7857
  }
7889
7858
  try {
7890
- const accounts = yield window.ethereum.request({
7891
- method: "eth_requestAccounts"
7892
- });
7859
+ const accounts = yield window.ethereum.request({ method: "eth_requestAccounts" });
7893
7860
  if (!accounts || accounts.length === 0) {
7894
- throw new Error("No accounts found. Please unlock MetaMask.");
7861
+ throw new Error("No accounts found");
7895
7862
  }
7896
7863
  const address = accounts[0];
7897
7864
  const chainIdHex = yield window.ethereum.request({ method: "eth_chainId" });
@@ -7907,8 +7874,7 @@ const connectMetamaskWallet = () => __async(void 0, null, function* () {
7907
7874
  default:
7908
7875
  networkType = `unknown-${chainId}`;
7909
7876
  }
7910
- const providerWrapper = {
7911
- request: (params) => window.ethereum.request(params),
7877
+ const simpleProvider = {
7912
7878
  getSigner: () => ({
7913
7879
  getAddress: () => __async(void 0, null, function* () {
7914
7880
  return address;
@@ -7919,9 +7885,9 @@ const connectMetamaskWallet = () => __async(void 0, null, function* () {
7919
7885
  params: [{
7920
7886
  from: address,
7921
7887
  to: tx.to,
7922
- value: tx.value ? typeof tx.value === "string" ? tx.value : tx.value.toString() : "0x0",
7923
- gasLimit: tx.gasLimit ? typeof tx.gasLimit === "string" ? tx.gasLimit : tx.gasLimit.toString() : void 0,
7924
- data: tx.data || "0x"
7888
+ value: tx.value ? tx.value.toString() : "0x0",
7889
+ gasLimit: tx.gasLimit ? tx.gasLimit.toString() : void 0,
7890
+ data: tx.data
7925
7891
  }]
7926
7892
  });
7927
7893
  return { hash: txHash };
@@ -7933,82 +7899,43 @@ const connectMetamaskWallet = () => __async(void 0, null, function* () {
7933
7899
  params: [{
7934
7900
  from: address,
7935
7901
  to: tx.to,
7936
- value: tx.value ? typeof tx.value === "string" ? tx.value : tx.value.toString() : "0x0",
7937
- data: tx.data || "0x"
7902
+ value: tx.value ? tx.value.toString() : "0x0"
7938
7903
  }]
7939
7904
  });
7940
- const gasLimit = parseInt(gasHex, 16);
7905
+ const gasValue = parseInt(gasHex, 16);
7941
7906
  return {
7942
- toString: () => gasLimit.toString(),
7907
+ toString: () => gasValue.toString(),
7943
7908
  mul: (n2) => ({
7944
7909
  div: (d) => ({
7945
- toString: () => Math.floor(gasLimit * n2 / d).toString()
7910
+ toString: () => Math.floor(gasValue * n2 / d).toString()
7946
7911
  })
7947
7912
  })
7948
7913
  };
7949
7914
  })
7950
7915
  };
7951
- console.log("MetaMask connected successfully:", { address, chainId, networkType });
7952
7916
  return {
7953
7917
  walletType: WALLET_TYPES.METAMASK,
7954
7918
  address,
7955
- provider: providerWrapper,
7919
+ provider: simpleProvider,
7956
7920
  network: networkType,
7957
7921
  isConnected: true,
7958
7922
  chainId
7959
7923
  };
7960
7924
  } catch (error) {
7961
- console.error("MetaMask connection error:", error);
7962
- throw error;
7963
- }
7964
- });
7965
- const connectTronlinkWallet = () => __async(void 0, null, function* () {
7966
- console.log("Connecting to TronLink wallet...");
7967
- if (!window.tronWeb) {
7968
- throw new Error("TronLink not detected. Please install TronLink extension.");
7969
- }
7970
- const waitForTronWeb = (maxAttempts = 10, interval = 500) => __async(void 0, null, function* () {
7971
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
7972
- if (window.tronWeb && window.tronWeb.ready) {
7973
- return window.tronWeb;
7974
- }
7975
- console.log(`Waiting for TronWeb to be ready... Attempt ${attempt + 1}/${maxAttempts}`);
7976
- yield new Promise((resolve) => setTimeout(resolve, interval));
7977
- }
7978
- throw new Error("TronWeb took too long to be ready");
7979
- });
7980
- try {
7981
- const tronWeb = yield waitForTronWeb();
7982
- if (!tronWeb.defaultAddress || !tronWeb.defaultAddress.base58) {
7983
- try {
7984
- yield window.tronWeb.request({ method: "tron_requestAccounts" });
7985
- } catch (permissionError) {
7986
- throw new Error("Please unlock TronLink and approve connection");
7987
- }
7988
- }
7989
- const address = tronWeb.defaultAddress.base58;
7990
- console.log("TronLink connected successfully:", address);
7991
- return {
7992
- walletType: WALLET_TYPES.TRONLINK,
7993
- address,
7994
- provider: tronWeb,
7995
- network: NETWORK_TYPES.TRON,
7996
- isConnected: true
7997
- };
7998
- } catch (error) {
7999
- console.error("TronLink connection error:", error);
7925
+ console.error("Error connecting to MetaMask:", error);
8000
7926
  throw error;
8001
7927
  }
8002
7928
  });
8003
7929
  const connectTrustWallet = () => __async(void 0, null, function* () {
8004
7930
  console.log("Connecting to Trust Wallet...");
8005
7931
  if (!window.ethereum || !window.ethereum.isTrust) {
7932
+ console.error("Trust Wallet not found.");
8006
7933
  throw new Error("Trust Wallet not detected. Please install Trust Wallet.");
8007
7934
  }
8008
7935
  try {
8009
7936
  const accounts = yield window.ethereum.request({ method: "eth_requestAccounts" });
8010
7937
  if (!accounts || accounts.length === 0) {
8011
- throw new Error("No accounts found. Please unlock Trust Wallet.");
7938
+ throw new Error("No accounts found");
8012
7939
  }
8013
7940
  const address = accounts[0];
8014
7941
  const chainIdHex = yield window.ethereum.request({ method: "eth_chainId" });
@@ -8024,8 +7951,7 @@ const connectTrustWallet = () => __async(void 0, null, function* () {
8024
7951
  default:
8025
7952
  networkType = `unknown-${chainId}`;
8026
7953
  }
8027
- const providerWrapper = {
8028
- request: (params) => window.ethereum.request(params),
7954
+ const simpleProvider = {
8029
7955
  getSigner: () => ({
8030
7956
  getAddress: () => __async(void 0, null, function* () {
8031
7957
  return address;
@@ -8036,9 +7962,9 @@ const connectTrustWallet = () => __async(void 0, null, function* () {
8036
7962
  params: [{
8037
7963
  from: address,
8038
7964
  to: tx.to,
8039
- value: tx.value ? typeof tx.value === "string" ? tx.value : tx.value.toString() : "0x0",
8040
- gasLimit: tx.gasLimit ? typeof tx.gasLimit === "string" ? tx.gasLimit : tx.gasLimit.toString() : void 0,
8041
- data: tx.data || "0x"
7965
+ value: tx.value ? tx.value.toString() : "0x0",
7966
+ gasLimit: tx.gasLimit ? tx.gasLimit.toString() : void 0,
7967
+ data: tx.data
8042
7968
  }]
8043
7969
  });
8044
7970
  return { hash: txHash };
@@ -8050,16 +7976,15 @@ const connectTrustWallet = () => __async(void 0, null, function* () {
8050
7976
  params: [{
8051
7977
  from: address,
8052
7978
  to: tx.to,
8053
- value: tx.value ? typeof tx.value === "string" ? tx.value : tx.value.toString() : "0x0",
8054
- data: tx.data || "0x"
7979
+ value: tx.value ? tx.value.toString() : "0x0"
8055
7980
  }]
8056
7981
  });
8057
- const gasLimit = parseInt(gasHex, 16);
7982
+ const gasValue = parseInt(gasHex, 16);
8058
7983
  return {
8059
- toString: () => gasLimit.toString(),
7984
+ toString: () => gasValue.toString(),
8060
7985
  mul: (n2) => ({
8061
7986
  div: (d) => ({
8062
- toString: () => Math.floor(gasLimit * n2 / d).toString()
7987
+ toString: () => Math.floor(gasValue * n2 / d).toString()
8063
7988
  })
8064
7989
  })
8065
7990
  };
@@ -8068,19 +7993,60 @@ const connectTrustWallet = () => __async(void 0, null, function* () {
8068
7993
  return {
8069
7994
  walletType: WALLET_TYPES.TRUST_WALLET,
8070
7995
  address,
8071
- provider: providerWrapper,
7996
+ provider: simpleProvider,
8072
7997
  network: networkType,
8073
7998
  isConnected: true,
8074
7999
  chainId
8075
8000
  };
8076
8001
  } catch (error) {
8077
- console.error("Trust Wallet connection error:", error);
8002
+ console.error("Error connecting to Trust Wallet:", error);
8003
+ throw error;
8004
+ }
8005
+ });
8006
+ const connectTronlinkWallet = () => __async(void 0, null, function* () {
8007
+ console.log("Connecting to TronLink wallet...");
8008
+ if (!window.tronWeb) {
8009
+ console.error("TronWeb not found. Is TronLink installed?");
8010
+ throw new Error("TronLink not detected. Please install TronLink extension.");
8011
+ }
8012
+ const waitForTronWeb = (maxAttempts = 10, interval = 500) => __async(void 0, null, function* () {
8013
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
8014
+ if (window.tronWeb && window.tronWeb.ready) {
8015
+ return window.tronWeb;
8016
+ }
8017
+ console.log(`Waiting for TronWeb to be ready... Attempt ${attempt + 1}/${maxAttempts}`);
8018
+ yield new Promise((resolve) => setTimeout(resolve, interval));
8019
+ }
8020
+ throw new Error("TronWeb took too long to be ready");
8021
+ });
8022
+ try {
8023
+ const tronWeb = yield waitForTronWeb();
8024
+ if (!tronWeb.defaultAddress || !tronWeb.defaultAddress.base58) {
8025
+ try {
8026
+ yield window.tronWeb.request({ method: "tron_requestAccounts" });
8027
+ } catch (permissionError) {
8028
+ console.error("Failed to get permission from TronLink:", permissionError);
8029
+ throw new Error("Please unlock TronLink and approve connection");
8030
+ }
8031
+ }
8032
+ const address = tronWeb.defaultAddress.base58;
8033
+ console.log("Connected to TronLink wallet:", address);
8034
+ return {
8035
+ walletType: WALLET_TYPES.TRONLINK,
8036
+ address,
8037
+ provider: tronWeb,
8038
+ network: NETWORK_TYPES.TRON,
8039
+ isConnected: true
8040
+ };
8041
+ } catch (error) {
8042
+ console.error("Error connecting to TronLink:", error);
8078
8043
  throw error;
8079
8044
  }
8080
8045
  });
8081
8046
  const connectLuteWallet = () => __async(void 0, null, function* () {
8082
8047
  console.log("Connecting to Lute wallet...");
8083
8048
  if (!window.lute) {
8049
+ console.error("Lute not found.");
8084
8050
  throw new Error("Lute not detected. Please install Lute extension.");
8085
8051
  }
8086
8052
  try {
@@ -8088,7 +8054,7 @@ const connectLuteWallet = () => __async(void 0, null, function* () {
8088
8054
  if (!address) {
8089
8055
  throw new Error("No address returned. Please unlock Lute wallet.");
8090
8056
  }
8091
- console.log("Lute wallet connected successfully:", address);
8057
+ console.log("Connected to Lute wallet:", address);
8092
8058
  return {
8093
8059
  walletType: WALLET_TYPES.LUTE,
8094
8060
  address,
@@ -8097,66 +8063,39 @@ const connectLuteWallet = () => __async(void 0, null, function* () {
8097
8063
  isConnected: true
8098
8064
  };
8099
8065
  } catch (error) {
8100
- console.error("Lute wallet connection error:", error);
8066
+ console.error("Error connecting to Lute wallet:", error);
8101
8067
  throw error;
8102
8068
  }
8103
8069
  });
8104
- const connectWallet = (walletType, network, retries = 1) => __async(void 0, null, function* () {
8105
- console.log("Connecting to wallet:", { walletType, network });
8106
- for (let attempt = 0; attempt < retries; attempt++) {
8107
- try {
8108
- switch (walletType) {
8109
- case WALLET_TYPES.METAMASK:
8110
- return yield connectMetamaskWallet();
8111
- case WALLET_TYPES.TRONLINK:
8112
- return yield connectTronlinkWallet();
8113
- case WALLET_TYPES.TRUST_WALLET:
8114
- return yield connectTrustWallet();
8115
- case WALLET_TYPES.LUTE:
8116
- return yield connectLuteWallet();
8117
- default:
8118
- throw new Error(`Unsupported wallet type: ${walletType}`);
8119
- }
8120
- } catch (error) {
8121
- console.log(`Wallet connection attempt ${attempt + 1} failed:`, error.message);
8122
- if (attempt === retries - 1) {
8123
- throw error;
8124
- }
8125
- yield new Promise((resolve) => setTimeout(resolve, 1e3));
8126
- }
8070
+ const connectWallet = (walletType) => __async(void 0, null, function* () {
8071
+ console.log("Connecting to wallet:", walletType);
8072
+ switch (walletType) {
8073
+ case WALLET_TYPES.METAMASK:
8074
+ return connectMetamaskWallet();
8075
+ case WALLET_TYPES.TRONLINK:
8076
+ return connectTronlinkWallet();
8077
+ case WALLET_TYPES.TRUST_WALLET:
8078
+ return connectTrustWallet();
8079
+ case WALLET_TYPES.LUTE:
8080
+ return connectLuteWallet();
8081
+ default:
8082
+ throw new Error(`Unsupported wallet type: ${walletType}`);
8127
8083
  }
8128
8084
  });
8129
8085
  const getSupportedWalletsForNetwork = (network) => {
8130
8086
  return NETWORK_WALLET_MAP[network] || [];
8131
8087
  };
8132
- const sendTransaction = (walletConnection, transactionParams) => __async(void 0, null, function* () {
8133
- console.log("Sending transaction:", { walletConnection, transactionParams });
8134
- if (!walletConnection) {
8088
+ const sendNativeTransaction = (walletConnection, toAddress, amount) => __async(void 0, null, function* () {
8089
+ console.log("Sending native transaction:", { toAddress, amount });
8090
+ if (!walletConnection || !walletConnection.provider) {
8135
8091
  throw new Error("Wallet not connected");
8136
8092
  }
8137
- const { to, amount, tokenAddress, tokenDecimals, currency, network, tokenConfig } = transactionParams;
8138
- if (!to) {
8093
+ if (!toAddress) {
8139
8094
  throw new Error("Recipient address not provided");
8140
8095
  }
8141
8096
  if (!amount || isNaN(parseFloat(amount)) || parseFloat(amount) <= 0) {
8142
8097
  throw new Error("Invalid amount");
8143
8098
  }
8144
- const isNativeToken = !tokenAddress || tokenAddress === null;
8145
- if (isNativeToken) {
8146
- return sendNativeTransaction(walletConnection, to, amount);
8147
- } else {
8148
- return sendTokenTransaction(walletConnection, {
8149
- contractAddress: tokenAddress,
8150
- decimals: tokenDecimals,
8151
- symbol: currency
8152
- }, to, amount);
8153
- }
8154
- });
8155
- const sendNativeTransaction = (walletConnection, toAddress, amount) => __async(void 0, null, function* () {
8156
- console.log("Sending native transaction:", { toAddress, amount });
8157
- if (!walletConnection || !walletConnection.provider) {
8158
- throw new Error("Wallet not connected");
8159
- }
8160
8099
  try {
8161
8100
  let transaction;
8162
8101
  switch (walletConnection.walletType) {
@@ -8164,12 +8103,21 @@ const sendNativeTransaction = (walletConnection, toAddress, amount) => __async(v
8164
8103
  case WALLET_TYPES.TRUST_WALLET:
8165
8104
  const provider = walletConnection.provider;
8166
8105
  const signer = provider.getSigner();
8167
- const amountWei = parseEther ? parseEther(amount.toString()) : (void 0).parseEther(amount.toString());
8106
+ const amountInEther = amount.toString();
8107
+ const amountWei = createEthersValue(amountInEther, 18);
8108
+ console.log("Sending ETH/BNB:", {
8109
+ to: toAddress,
8110
+ value: amountWei.toString()
8111
+ });
8168
8112
  const gasEstimate = yield provider.estimateGas({
8169
8113
  to: toAddress,
8170
8114
  value: amountWei
8171
8115
  });
8172
- const gasLimit = typeof gasEstimate.mul === "function" ? gasEstimate.mul(110).div(100) : { toString: () => Math.floor(parseInt(gasEstimate.toString()) * 1.1).toString() };
8116
+ console.log("Gas estimate:", gasEstimate.toString());
8117
+ const gasLimit = {
8118
+ toString: () => Math.floor(parseInt(gasEstimate.toString()) * 1.1).toString()
8119
+ };
8120
+ console.log("Using gas limit:", gasLimit.toString());
8173
8121
  transaction = yield signer.sendTransaction({
8174
8122
  to: toAddress,
8175
8123
  value: amountWei,
@@ -8182,11 +8130,22 @@ const sendNativeTransaction = (walletConnection, toAddress, amount) => __async(v
8182
8130
  throw new Error("TronWeb not initialized");
8183
8131
  }
8184
8132
  const amountSun = tronWeb.toSun(amount.toString());
8185
- transaction = yield tronWeb.trx.sendTransaction(toAddress, amountSun);
8133
+ console.log("Sending TRX:", {
8134
+ to: toAddress,
8135
+ value: amountSun
8136
+ });
8137
+ transaction = yield tronWeb.trx.sendTransaction(
8138
+ toAddress,
8139
+ amountSun
8140
+ );
8186
8141
  break;
8187
8142
  case WALLET_TYPES.LUTE:
8188
8143
  const lute = walletConnection.provider;
8189
8144
  const microAlgos = Math.floor(parseFloat(amount) * 1e6);
8145
+ console.log("Sending Algos:", {
8146
+ to: toAddress,
8147
+ amount: microAlgos
8148
+ });
8190
8149
  transaction = yield lute.sendPayment({
8191
8150
  recipient: toAddress,
8192
8151
  amount: microAlgos
@@ -8195,22 +8154,50 @@ const sendNativeTransaction = (walletConnection, toAddress, amount) => __async(v
8195
8154
  default:
8196
8155
  throw new Error(`Unsupported wallet type: ${walletConnection.walletType}`);
8197
8156
  }
8157
+ console.log("Transaction sent:", transaction);
8198
8158
  const hash = transaction.hash || transaction.txID || transaction.txId || transaction;
8199
- console.log("Native transaction sent:", hash);
8159
+ console.log("Transaction hash:", hash);
8200
8160
  return hash;
8201
8161
  } catch (error) {
8202
8162
  console.error("Native transaction error:", error);
8203
8163
  throw error;
8204
8164
  }
8205
8165
  });
8166
+ const sendTransaction = (walletConnection, transactionDetails) => __async(void 0, null, function* () {
8167
+ var _a2;
8168
+ console.log("Sending transaction with:", transactionDetails);
8169
+ if (!walletConnection) {
8170
+ throw new Error("Wallet not connected");
8171
+ }
8172
+ const { to, amount, tokenAddress, currency, network } = transactionDetails;
8173
+ if (!to) {
8174
+ throw new Error("Recipient address not provided");
8175
+ }
8176
+ const tokenConfig = (_a2 = TOKEN_CONFIG[currency]) == null ? void 0 : _a2[network];
8177
+ if (tokenConfig && tokenConfig.isNative) {
8178
+ return sendNativeTransaction(walletConnection, to, amount);
8179
+ } else if (tokenConfig) {
8180
+ return sendTokenTransaction(walletConnection, tokenConfig, to, amount);
8181
+ } else {
8182
+ return sendNativeTransaction(walletConnection, to, amount);
8183
+ }
8184
+ });
8206
8185
  const sendTokenTransaction = (walletConnection, tokenConfig, toAddress, amount) => __async(void 0, null, function* () {
8207
- console.log("Sending token transaction:", { tokenConfig, toAddress, amount });
8186
+ console.log("Sending token transaction with:", { tokenConfig, toAddress, amount });
8208
8187
  if (!walletConnection || !walletConnection.provider) {
8209
8188
  throw new Error("Wallet not connected");
8210
8189
  }
8211
- if (!tokenConfig || !tokenConfig.contractAddress) {
8212
- throw new Error("Token configuration missing");
8190
+ if (!tokenConfig) {
8191
+ throw new Error("Token configuration not provided");
8213
8192
  }
8193
+ if (!toAddress) {
8194
+ throw new Error("Recipient address not provided");
8195
+ }
8196
+ if (!amount || isNaN(parseFloat(amount)) || parseFloat(amount) <= 0) {
8197
+ throw new Error("Invalid amount");
8198
+ }
8199
+ const { contractAddress, decimals, symbol } = tokenConfig;
8200
+ console.log(`Token: ${symbol}, Decimals: ${decimals}, Contract: ${contractAddress}`);
8214
8201
  switch (walletConnection.walletType) {
8215
8202
  case WALLET_TYPES.TRONLINK:
8216
8203
  return sendTRC20Transaction(walletConnection, tokenConfig, toAddress, amount);
@@ -8221,21 +8208,16 @@ const sendTokenTransaction = (walletConnection, tokenConfig, toAddress, amount)
8221
8208
  }
8222
8209
  });
8223
8210
  const sendERC20Transaction = (walletConnection, tokenConfig, toAddress, amount) => __async(void 0, null, function* () {
8224
- console.log("Sending ERC20/BEP20 transaction:", { tokenConfig, toAddress, amount });
8211
+ console.log("Sending ERC20/BEP20 transaction with:", { tokenConfig, toAddress, amount });
8212
+ if (!walletConnection || !walletConnection.provider) {
8213
+ throw new Error("Wallet not connected");
8214
+ }
8225
8215
  const provider = walletConnection.provider;
8226
8216
  const signer = provider.getSigner();
8227
8217
  const { contractAddress, decimals, symbol } = tokenConfig;
8228
8218
  const tokenAmount = parseFloat(amount);
8229
8219
  const tokenDecimals = parseInt(decimals);
8230
- let tokenUnits;
8231
- try {
8232
- tokenUnits = parseUnits ? parseUnits(tokenAmount.toString(), tokenDecimals) : (void 0).parseUnits(tokenAmount.toString(), tokenDecimals);
8233
- } catch (err) {
8234
- const value = tokenAmount * Math.pow(10, tokenDecimals);
8235
- tokenUnits = {
8236
- toString: () => value.toLocaleString("fullwide", { useGrouping: false })
8237
- };
8238
- }
8220
+ const tokenUnits = createEthersValue(tokenAmount.toString(), tokenDecimals);
8239
8221
  console.log(`Sending ${tokenAmount} ${symbol} (${tokenUnits.toString()} base units) to ${toAddress}`);
8240
8222
  try {
8241
8223
  const tokenContract = new Contract(
@@ -8243,13 +8225,28 @@ const sendERC20Transaction = (walletConnection, tokenConfig, toAddress, amount)
8243
8225
  ["function transfer(address to, uint256 amount) returns (bool)"],
8244
8226
  signer
8245
8227
  );
8246
- const gasMultiplier = symbol === "USDC" ? 1.5 : 1.2;
8247
- const transaction = yield tokenContract.transfer(toAddress, tokenUnits, {
8248
- gasLimit: Math.floor(2e5 * gasMultiplier)
8249
- // Fixed gas limit with multiplier
8250
- });
8251
- console.log("ERC20 transaction sent:", transaction);
8252
- return transaction.hash;
8228
+ try {
8229
+ const gasEstimate = yield tokenContract.transfer.estimateGas(toAddress, tokenUnits);
8230
+ console.log("Gas estimate:", gasEstimate.toString());
8231
+ const gasLimit = symbol === "USDC" ? Math.floor(parseInt(gasEstimate.toString()) * 1.2).toString() : Math.floor(parseInt(gasEstimate.toString()) * 1.1).toString();
8232
+ console.log("Using gas limit:", gasLimit);
8233
+ const transaction = yield tokenContract.transfer(toAddress, tokenUnits, {
8234
+ gasLimit
8235
+ });
8236
+ console.log("Transaction sent:", transaction);
8237
+ return transaction.hash;
8238
+ } catch (gasError) {
8239
+ console.error("Gas estimation failed:", gasError);
8240
+ if (symbol === "USDC") {
8241
+ console.log("Trying USDC transaction with fixed gas limit");
8242
+ const transaction = yield tokenContract.transfer(toAddress, tokenUnits, {
8243
+ gasLimit: 15e4
8244
+ });
8245
+ console.log("Transaction sent with fixed gas limit:", transaction);
8246
+ return transaction.hash;
8247
+ }
8248
+ throw new Error(`Transaction would likely fail: ${gasError.message}`);
8249
+ }
8253
8250
  } catch (error) {
8254
8251
  console.error("ERC20 transaction error:", error);
8255
8252
  if (error.message && error.message.includes("user rejected")) {
@@ -8262,16 +8259,23 @@ const sendERC20Transaction = (walletConnection, tokenConfig, toAddress, amount)
8262
8259
  }
8263
8260
  });
8264
8261
  const sendTRC20Transaction = (walletConnection, tokenConfig, toAddress, amount) => __async(void 0, null, function* () {
8265
- console.log("Sending TRC20 transaction:", { tokenConfig, toAddress, amount });
8262
+ console.log("Sending TRC20 transaction with:", { tokenConfig, toAddress, amount });
8263
+ if (!walletConnection || !walletConnection.provider) {
8264
+ throw new Error("Tron wallet not connected");
8265
+ }
8266
8266
  const tronWeb = walletConnection.provider;
8267
8267
  if (!tronWeb || !tronWeb.ready) {
8268
8268
  throw new Error("TronWeb not initialized");
8269
8269
  }
8270
+ if (!tokenConfig || !tokenConfig.contractAddress) {
8271
+ throw new Error("Invalid token configuration");
8272
+ }
8270
8273
  const { contractAddress, decimals, symbol } = tokenConfig;
8271
8274
  const tokenAmount = parseFloat(amount);
8272
8275
  const tokenDecimals = parseInt(decimals);
8273
- const amountWithDecimals = Math.floor(tokenAmount * Math.pow(10, tokenDecimals));
8274
- console.log(`Sending ${tokenAmount} ${symbol} (${amountWithDecimals} base units) to ${toAddress}`);
8276
+ const amountWithDecimals = tokenAmount * Math.pow(10, tokenDecimals);
8277
+ const amountString = amountWithDecimals.toString();
8278
+ console.log(`Sending ${tokenAmount} ${symbol} (${amountString} base units) to ${toAddress}`);
8275
8279
  try {
8276
8280
  const contract = yield tronWeb.contract().at(contractAddress);
8277
8281
  if (!contract.transfer) {
@@ -8279,10 +8283,9 @@ const sendTRC20Transaction = (walletConnection, tokenConfig, toAddress, amount)
8279
8283
  }
8280
8284
  const transaction = yield contract.transfer(
8281
8285
  toAddress,
8282
- amountWithDecimals.toString()
8286
+ amountString
8283
8287
  ).send({
8284
8288
  feeLimit: 1e8,
8285
- // 100 TRX fee limit
8286
8289
  callValue: 0,
8287
8290
  shouldPollResponse: false
8288
8291
  });
@@ -8294,14 +8297,22 @@ const sendTRC20Transaction = (walletConnection, tokenConfig, toAddress, amount)
8294
8297
  throw new Error("Transaction rejected by user");
8295
8298
  } else if (error.message && error.message.includes("bandwidth")) {
8296
8299
  throw new Error("Insufficient energy or bandwidth. Make sure you have enough TRX for fees.");
8300
+ } else if (error.message && error.message.includes("balance")) {
8301
+ throw new Error("Insufficient token balance for transfer");
8297
8302
  } else {
8298
8303
  throw new Error(`Transaction failed: ${error.message || "Unknown error"}`);
8299
8304
  }
8300
8305
  }
8301
8306
  });
8302
8307
  const sendAlgorandAssetTransaction = (walletConnection, tokenConfig, toAddress, amount) => __async(void 0, null, function* () {
8303
- console.log("Sending Algorand asset transaction:", { tokenConfig, toAddress, amount });
8308
+ console.log("Sending Algorand asset transaction with:", { tokenConfig, toAddress, amount });
8309
+ if (!walletConnection || !walletConnection.provider) {
8310
+ throw new Error("Algorand wallet not connected");
8311
+ }
8304
8312
  const lute = walletConnection.provider;
8313
+ if (!tokenConfig || !tokenConfig.assetId) {
8314
+ throw new Error("Invalid token configuration - missing assetId");
8315
+ }
8305
8316
  const { assetId, decimals, symbol } = tokenConfig;
8306
8317
  const tokenAmount = parseFloat(amount);
8307
8318
  const tokenDecimals = parseInt(decimals);
@@ -8319,6 +8330,8 @@ const sendAlgorandAssetTransaction = (walletConnection, tokenConfig, toAddress,
8319
8330
  console.error("Algorand asset transaction error:", error);
8320
8331
  if (error.message && error.message.includes("rejected")) {
8321
8332
  throw new Error("Transaction rejected by user");
8333
+ } else if (error.message && error.message.includes("balance")) {
8334
+ throw new Error("Insufficient asset balance");
8322
8335
  } else {
8323
8336
  throw error;
8324
8337
  }
@@ -8328,78 +8341,87 @@ let apiConfig = {
8328
8341
  apiKey: null,
8329
8342
  apiSecret: null,
8330
8343
  apiUrl: "https://coinleyserver-production.up.railway.app",
8331
- merchantWalletAddresses: {}
8344
+ merchantWalletAddresses: {},
8345
+ authToken: null
8332
8346
  };
8333
- const initializeApi = (config) => {
8347
+ const initializeApi = (config) => __async(void 0, null, function* () {
8334
8348
  apiConfig = __spreadValues(__spreadValues({}, apiConfig), config);
8335
8349
  console.log("API initialized with:", {
8336
8350
  apiUrl: apiConfig.apiUrl,
8337
8351
  apiKey: apiConfig.apiKey ? `${apiConfig.apiKey.substring(0, 6)}...` : null,
8338
8352
  hasWalletAddresses: Object.keys(apiConfig.merchantWalletAddresses || {}).length > 0
8339
8353
  });
8340
- if (apiConfig.apiKey && apiConfig.apiSecret) {
8341
- fetchMerchantWalletAddresses().then((wallets) => {
8342
- if (wallets) {
8343
- apiConfig.merchantWalletAddresses = __spreadValues(__spreadValues({}, apiConfig.merchantWalletAddresses), wallets);
8344
- console.log("Auto-fetched merchant wallet addresses:", wallets);
8345
- }
8346
- }).catch((err) => {
8347
- console.warn("Could not auto-fetch merchant wallet addresses:", err.message);
8348
- });
8354
+ try {
8355
+ yield authenticateAndFetchWallets();
8356
+ } catch (error) {
8357
+ console.error("Failed to fetch merchant wallets during initialization:", error);
8349
8358
  }
8350
- };
8351
- const getHeaders = () => {
8352
- return {
8353
- "Content-Type": "application/json",
8354
- "x-api-key": apiConfig.apiKey,
8355
- "x-api-secret": apiConfig.apiSecret
8356
- };
8357
- };
8358
- const fetchMerchantWalletAddresses = () => __async(void 0, null, function* () {
8359
+ });
8360
+ const authenticateAndFetchWallets = () => __async(void 0, null, function* () {
8359
8361
  try {
8360
- const response = yield fetch(`${apiConfig.apiUrl}/api/merchants/wallets`, {
8362
+ console.log("Authenticating and fetching merchant wallets...");
8363
+ const tempToken = btoa(`${apiConfig.apiKey}:${apiConfig.apiSecret}`);
8364
+ const response = yield fetch(`${apiConfig.apiUrl}/api/merchants/dashboard`, {
8361
8365
  method: "GET",
8362
- headers: getHeaders()
8366
+ headers: {
8367
+ "Content-Type": "application/json",
8368
+ "Authorization": `Bearer ${tempToken}`,
8369
+ "x-api-key": apiConfig.apiKey,
8370
+ "x-api-secret": apiConfig.apiSecret
8371
+ }
8363
8372
  });
8364
- if (!response.ok) {
8365
- throw new Error(`Failed to fetch wallet addresses: ${response.status}`);
8366
- }
8367
- const data = yield response.json();
8368
- const walletAddresses = {};
8369
- if (data.success && data.wallets) {
8370
- data.wallets.forEach((wallet) => {
8371
- if (wallet.walletAddress && wallet.networkShortName) {
8372
- walletAddresses[wallet.networkShortName] = wallet.walletAddress;
8373
+ if (response.ok) {
8374
+ const data = yield response.json();
8375
+ console.log("Merchant dashboard data received:", data);
8376
+ if (data.merchant) {
8377
+ const walletAddresses = {};
8378
+ if (data.merchant.walletAddress) {
8379
+ walletAddresses.ethereum = data.merchant.walletAddress;
8373
8380
  }
8374
- });
8381
+ if (data.merchant.solWalletAddress) {
8382
+ walletAddresses.solana = data.merchant.solWalletAddress;
8383
+ }
8384
+ if (data.merchant.merchantWallets) {
8385
+ Object.assign(walletAddresses, data.merchant.merchantWallets);
8386
+ }
8387
+ apiConfig.merchantWalletAddresses = walletAddresses;
8388
+ console.log("Merchant wallet addresses retrieved:", walletAddresses);
8389
+ return walletAddresses;
8390
+ }
8391
+ } else {
8392
+ console.error("Failed to fetch merchant dashboard:", response.status);
8375
8393
  }
8376
- return walletAddresses;
8377
8394
  } catch (error) {
8378
- console.error("Error fetching merchant wallet addresses:", error);
8379
- throw error;
8395
+ console.error("Error fetching merchant wallets:", error);
8396
+ }
8397
+ return {};
8398
+ });
8399
+ const getMerchantWallets = () => __async(void 0, null, function* () {
8400
+ if (Object.keys(apiConfig.merchantWalletAddresses).length === 0) {
8401
+ yield authenticateAndFetchWallets();
8380
8402
  }
8403
+ return apiConfig.merchantWalletAddresses;
8381
8404
  });
8405
+ const getHeaders = () => {
8406
+ return {
8407
+ "Content-Type": "application/json",
8408
+ "x-api-key": apiConfig.apiKey,
8409
+ "x-api-secret": apiConfig.apiSecret,
8410
+ "Authorization": apiConfig.authToken ? `Bearer ${apiConfig.authToken}` : void 0
8411
+ };
8412
+ };
8382
8413
  const createPayment = (paymentData) => __async(void 0, null, function* () {
8383
8414
  try {
8384
8415
  console.log("Creating payment with data:", paymentData);
8385
8416
  if (!paymentData.amount) {
8386
8417
  throw new Error("Payment amount is required");
8387
8418
  }
8388
- let merchantWallets = apiConfig.merchantWalletAddresses || {};
8389
- if (Object.keys(merchantWallets).length === 0) {
8390
- try {
8391
- merchantWallets = yield fetchMerchantWalletAddresses();
8392
- apiConfig.merchantWalletAddresses = merchantWallets;
8393
- } catch (fetchError) {
8394
- console.warn("Could not fetch merchant wallet addresses:", fetchError.message);
8395
- }
8396
- }
8419
+ const merchantWallets = yield getMerchantWallets();
8420
+ console.log("Using merchant wallets:", merchantWallets);
8397
8421
  const enhancedPaymentData = __spreadProps(__spreadValues({}, paymentData), {
8398
8422
  merchantWalletAddresses: __spreadValues(__spreadValues({}, merchantWallets), paymentData.merchantWalletAddresses)
8399
8423
  });
8400
- console.log("Enhanced payment data:", __spreadProps(__spreadValues({}, enhancedPaymentData), {
8401
- merchantWalletAddresses: enhancedPaymentData.merchantWalletAddresses
8402
- }));
8424
+ console.log("Enhanced payment data:", enhancedPaymentData);
8403
8425
  const response = yield fetch(`${apiConfig.apiUrl}/api/payments/create`, {
8404
8426
  method: "POST",
8405
8427
  headers: getHeaders(),
@@ -8417,10 +8439,7 @@ const createPayment = (paymentData) => __async(void 0, null, function* () {
8417
8439
  throw new Error(errorData.error || `Failed to create payment: ${response.status}`);
8418
8440
  }
8419
8441
  const data = yield response.json();
8420
- console.log("Create payment response data:", data);
8421
- if (data.merchantConfig && data.merchantConfig.walletAddresses) {
8422
- apiConfig.merchantWalletAddresses = __spreadValues(__spreadValues({}, apiConfig.merchantWalletAddresses), data.merchantConfig.walletAddresses);
8423
- }
8442
+ console.log("Payment created successfully:", data);
8424
8443
  return data;
8425
8444
  } catch (error) {
8426
8445
  console.error("Create payment error:", error);
@@ -8449,9 +8468,6 @@ const getPayment = (paymentId) => __async(void 0, null, function* () {
8449
8468
  }
8450
8469
  const data = yield response.json();
8451
8470
  console.log("Get payment response:", data);
8452
- if (data.payment && data.payment.merchantWallets) {
8453
- apiConfig.merchantWalletAddresses = __spreadValues(__spreadValues({}, apiConfig.merchantWalletAddresses), data.payment.merchantWallets);
8454
- }
8455
8471
  return data;
8456
8472
  } catch (error) {
8457
8473
  console.error("Get payment error:", error);
@@ -8513,41 +8529,6 @@ const getSupportedNetworks = () => __async(void 0, null, function* () {
8513
8529
  throw error;
8514
8530
  }
8515
8531
  });
8516
- const getMerchantProfile = () => __async(void 0, null, function* () {
8517
- try {
8518
- const response = yield fetch(`${apiConfig.apiUrl}/api/merchants/dashboard`, {
8519
- method: "GET",
8520
- headers: getHeaders()
8521
- });
8522
- if (!response.ok) {
8523
- let errorData;
8524
- try {
8525
- errorData = yield response.json();
8526
- } catch (e) {
8527
- throw new Error(`Failed to get merchant profile: ${response.status} ${response.statusText}`);
8528
- }
8529
- throw new Error(errorData.error || `Failed to get merchant profile: ${response.status}`);
8530
- }
8531
- const data = yield response.json();
8532
- if (data.merchant) {
8533
- const walletAddresses = {};
8534
- if (data.merchant.walletAddress) {
8535
- walletAddresses.ethereum = data.merchant.walletAddress;
8536
- }
8537
- if (data.merchant.solWalletAddress) {
8538
- walletAddresses.solana = data.merchant.solWalletAddress;
8539
- }
8540
- if (data.merchant.merchantWallets) {
8541
- Object.assign(walletAddresses, data.merchant.merchantWallets);
8542
- }
8543
- apiConfig.merchantWalletAddresses = __spreadValues(__spreadValues({}, apiConfig.merchantWalletAddresses), walletAddresses);
8544
- }
8545
- return data;
8546
- } catch (error) {
8547
- console.error("Get merchant profile error:", error);
8548
- throw error;
8549
- }
8550
- });
8551
8532
  const validateWalletAddress = (address, network) => __async(void 0, null, function* () {
8552
8533
  try {
8553
8534
  const response = yield fetch(`${apiConfig.apiUrl}/api/wallets/validate`, {
@@ -8571,12 +8552,6 @@ const validateWalletAddress = (address, network) => __async(void 0, null, functi
8571
8552
  throw error;
8572
8553
  }
8573
8554
  });
8574
- const getApiConfig = () => {
8575
- return __spreadProps(__spreadValues({}, apiConfig), {
8576
- // Return a copy to prevent external modification
8577
- merchantWalletAddresses: __spreadValues({}, apiConfig.merchantWalletAddresses)
8578
- });
8579
- };
8580
8555
  const generateMockTransactionHash = (network = "ethereum") => {
8581
8556
  const prefixes = {
8582
8557
  ethereum: "0x",
@@ -8639,45 +8614,55 @@ const CoinleyProvider = ({
8639
8614
  apiSecret,
8640
8615
  apiUrl = "https://coinleyserver-production.up.railway.app",
8641
8616
  merchantWalletAddress = null,
8642
- // New prop for merchant wallet address
8617
+ // Legacy prop for backward compatibility
8643
8618
  merchantSolWalletAddress = null,
8644
- // New prop for Solana wallet address
8619
+ // Legacy prop for backward compatibility
8645
8620
  debug = false,
8646
8621
  children
8647
8622
  }) => {
8648
8623
  const [isInitialized, setIsInitialized] = useState(false);
8649
8624
  const [error, setError] = useState(null);
8650
8625
  const [paymentData, setPaymentData] = useState(null);
8626
+ const [merchantWallets, setMerchantWallets] = useState({});
8651
8627
  useEffect(() => {
8652
8628
  if (!apiKey || !apiSecret) {
8653
8629
  setError("API key and secret are required");
8654
8630
  return;
8655
8631
  }
8656
- try {
8657
- initializeApi({
8658
- apiKey,
8659
- apiSecret,
8660
- apiUrl,
8661
- merchantWalletAddress,
8662
- // Pass wallet address to API service
8663
- merchantSolWalletAddress
8664
- });
8665
- setIsInitialized(true);
8666
- if (debug) {
8667
- console.log("Coinley SDK initialized with:", {
8632
+ const initializeSDK = () => __async(void 0, null, function* () {
8633
+ try {
8634
+ yield initializeApi({
8668
8635
  apiKey,
8636
+ apiSecret,
8669
8637
  apiUrl,
8670
- merchantWalletAddress: merchantWalletAddress ? `${merchantWalletAddress.substring(0, 6)}...${merchantWalletAddress.substring(merchantWalletAddress.length - 4)}` : "Not provided",
8671
- merchantSolWalletAddress: merchantSolWalletAddress ? `${merchantSolWalletAddress.substring(0, 6)}...${merchantSolWalletAddress.substring(merchantSolWalletAddress.length - 4)}` : "Not provided"
8638
+ debug
8672
8639
  });
8640
+ const wallets = yield getMerchantWallets();
8641
+ const allWallets = __spreadValues(__spreadValues(__spreadValues({}, wallets), merchantWalletAddress && { ethereum: merchantWalletAddress }), merchantSolWalletAddress && { solana: merchantSolWalletAddress });
8642
+ setMerchantWallets(allWallets);
8643
+ setIsInitialized(true);
8644
+ if (debug) {
8645
+ console.log("Coinley SDK initialized successfully with wallets:", allWallets);
8646
+ }
8647
+ } catch (err) {
8648
+ setError(err.message);
8649
+ if (debug) {
8650
+ console.error("Coinley SDK initialization error:", err);
8651
+ }
8673
8652
  }
8653
+ });
8654
+ initializeSDK();
8655
+ }, [apiKey, apiSecret, apiUrl, merchantWalletAddress, merchantSolWalletAddress, debug]);
8656
+ const refreshMerchantWallets = () => __async(void 0, null, function* () {
8657
+ try {
8658
+ const wallets = yield getMerchantWallets();
8659
+ setMerchantWallets(wallets);
8660
+ return wallets;
8674
8661
  } catch (err) {
8675
- setError(err.message);
8676
- if (debug) {
8677
- console.error("Coinley SDK initialization error:", err);
8678
- }
8662
+ console.error("Failed to refresh merchant wallets:", err);
8663
+ return merchantWallets;
8679
8664
  }
8680
- }, [apiKey, apiSecret, apiUrl, merchantWalletAddress, merchantSolWalletAddress, debug]);
8665
+ });
8681
8666
  const storePaymentData = (data) => {
8682
8667
  setPaymentData(data);
8683
8668
  return data;
@@ -8687,12 +8672,17 @@ const CoinleyProvider = ({
8687
8672
  apiSecret,
8688
8673
  apiUrl,
8689
8674
  merchantWalletAddress,
8675
+ // Legacy
8690
8676
  merchantSolWalletAddress,
8677
+ // Legacy
8678
+ merchantWallets,
8679
+ // New: All merchant wallets
8691
8680
  isInitialized,
8692
8681
  error,
8693
8682
  debug,
8694
8683
  paymentData,
8695
- storePaymentData
8684
+ storePaymentData,
8685
+ refreshMerchantWallets
8696
8686
  };
8697
8687
  return /* @__PURE__ */ jsxRuntimeExports.jsx(CoinleyContext.Provider, { value, children });
8698
8688
  };
@@ -10734,6 +10724,7 @@ const CoinleyCheckout = forwardRef(({
10734
10724
  customerEmail,
10735
10725
  merchantName = "Merchant",
10736
10726
  merchantWalletAddresses = {},
10727
+ // This will be overridden by backend data
10737
10728
  onSuccess,
10738
10729
  onError,
10739
10730
  onClose,
@@ -10756,31 +10747,34 @@ const CoinleyCheckout = forwardRef(({
10756
10747
  const [walletConnection, setWalletConnection] = useState(null);
10757
10748
  const [availableWallets, setAvailableWallets] = useState({});
10758
10749
  const [step, setStep] = useState("select-currency");
10759
- const [merchantWallets, setMerchantWallets] = useState({});
10760
- const [isLoadingWallets, setIsLoadingWallets] = useState(false);
10750
+ const [actualMerchantWallets, setActualMerchantWallets] = useState({});
10761
10751
  const effectiveApiKey = apiKey || (coinleyContext == null ? void 0 : coinleyContext.apiKey);
10762
10752
  const effectiveApiSecret = apiSecret || (coinleyContext == null ? void 0 : coinleyContext.apiSecret);
10763
10753
  apiUrl || (coinleyContext == null ? void 0 : coinleyContext.apiUrl);
10764
10754
  const effectiveTheme = theme || contextTheme;
10765
10755
  const effectiveDebug = debug || (coinleyContext == null ? void 0 : coinleyContext.debug);
10766
10756
  const effectiveSupportedNetworks = supportedNetworks.length > 0 ? supportedNetworks : [NETWORK_TYPES.ETHEREUM, NETWORK_TYPES.BSC, NETWORK_TYPES.TRON, NETWORK_TYPES.ALGORAND];
10767
- useImperativeHandle(ref, () => ({
10768
- open: (paymentDetails) => {
10769
- handleOpen(paymentDetails);
10770
- },
10771
- close: () => {
10772
- handleClose();
10773
- },
10774
- getPayment: () => payment,
10775
- getWalletConnection: () => walletConnection,
10776
- getMerchantWallets: () => merchantWallets,
10777
- debugWallets: () => debugWalletEnvironment()
10778
- }));
10779
10757
  const log = (message, data) => {
10780
10758
  if (effectiveDebug) {
10781
10759
  console.log(`[Coinley SDK] ${message}`, data);
10782
10760
  }
10783
10761
  };
10762
+ useEffect(() => {
10763
+ const fetchMerchantWallets = () => __async(void 0, null, function* () {
10764
+ try {
10765
+ log("Fetching merchant wallet addresses from backend...");
10766
+ const wallets = yield getMerchantWallets();
10767
+ setActualMerchantWallets(wallets);
10768
+ log("Merchant wallets fetched successfully:", wallets);
10769
+ } catch (error2) {
10770
+ console.error("Failed to fetch merchant wallets:", error2);
10771
+ setActualMerchantWallets(merchantWalletAddresses);
10772
+ }
10773
+ });
10774
+ if (effectiveApiKey && effectiveApiSecret) {
10775
+ fetchMerchantWallets();
10776
+ }
10777
+ }, [effectiveApiKey, effectiveApiSecret, merchantWalletAddresses]);
10784
10778
  useEffect(() => {
10785
10779
  if (typeof window !== "undefined") {
10786
10780
  const detectWalletsAsync = () => __async(void 0, null, function* () {
@@ -10791,44 +10785,18 @@ const CoinleyCheckout = forwardRef(({
10791
10785
  detectWalletsAsync();
10792
10786
  }
10793
10787
  }, [effectiveDebug]);
10794
- useEffect(() => {
10795
- const loadMerchantWallets = () => __async(void 0, null, function* () {
10796
- if (!effectiveApiKey || !effectiveApiSecret) {
10797
- log("No API credentials available for wallet address fetching");
10798
- return;
10799
- }
10800
- setIsLoadingWallets(true);
10801
- try {
10802
- const apiConfig2 = getApiConfig();
10803
- if (apiConfig2.merchantWalletAddresses && Object.keys(apiConfig2.merchantWalletAddresses).length > 0) {
10804
- setMerchantWallets(apiConfig2.merchantWalletAddresses);
10805
- log("Loaded wallet addresses from API config:", apiConfig2.merchantWalletAddresses);
10806
- } else {
10807
- const walletAddresses = yield fetchMerchantWalletAddresses();
10808
- if (walletAddresses && Object.keys(walletAddresses).length > 0) {
10809
- setMerchantWallets(walletAddresses);
10810
- log("Fetched wallet addresses from API:", walletAddresses);
10811
- } else {
10812
- log("No wallet addresses found in API response");
10813
- }
10814
- }
10815
- if (merchantWalletAddresses && Object.keys(merchantWalletAddresses).length > 0) {
10816
- setMerchantWallets((prev) => __spreadValues(__spreadValues({}, prev), merchantWalletAddresses));
10817
- log("Added manual wallet addresses:", merchantWalletAddresses);
10818
- }
10819
- } catch (error2) {
10820
- log("Error loading merchant wallet addresses:", error2);
10821
- console.warn("Could not load merchant wallet addresses:", error2.message);
10822
- if (merchantWalletAddresses && Object.keys(merchantWalletAddresses).length > 0) {
10823
- setMerchantWallets(merchantWalletAddresses);
10824
- log("Using fallback manual wallet addresses:", merchantWalletAddresses);
10825
- }
10826
- } finally {
10827
- setIsLoadingWallets(false);
10828
- }
10829
- });
10830
- loadMerchantWallets();
10831
- }, [effectiveApiKey, effectiveApiSecret, merchantWalletAddresses, effectiveDebug]);
10788
+ useImperativeHandle(ref, () => ({
10789
+ open: (paymentDetails) => {
10790
+ handleOpen(paymentDetails);
10791
+ },
10792
+ close: () => {
10793
+ handleClose();
10794
+ },
10795
+ getPayment: () => payment,
10796
+ getWalletConnection: () => walletConnection,
10797
+ debugWallets: () => debugWalletEnvironment(),
10798
+ getMerchantWallets: () => actualMerchantWallets
10799
+ }));
10832
10800
  const handleOpen = (paymentDetails) => __async(void 0, null, function* () {
10833
10801
  if (!paymentDetails || !paymentDetails.amount) {
10834
10802
  setError("Payment amount is required");
@@ -10841,26 +10809,13 @@ const CoinleyCheckout = forwardRef(({
10841
10809
  setStep("select-currency");
10842
10810
  try {
10843
10811
  log("Creating payment with details:", paymentDetails);
10844
- let finalWalletAddresses = __spreadValues({}, merchantWallets);
10845
- if (Object.keys(finalWalletAddresses).length === 0) {
10846
- log("No wallet addresses available, attempting to fetch...");
10847
- try {
10848
- const fetchedWallets = yield fetchMerchantWalletAddresses();
10849
- if (fetchedWallets) {
10850
- finalWalletAddresses = fetchedWallets;
10851
- setMerchantWallets(fetchedWallets);
10852
- }
10853
- } catch (fetchError) {
10854
- log("Failed to fetch wallet addresses:", fetchError);
10855
- }
10856
- }
10857
- if (paymentDetails.merchantWalletAddresses) {
10858
- finalWalletAddresses = __spreadValues(__spreadValues({}, finalWalletAddresses), paymentDetails.merchantWalletAddresses);
10859
- }
10860
- if (merchantWalletAddresses) {
10861
- finalWalletAddresses = __spreadValues(__spreadValues({}, finalWalletAddresses), merchantWalletAddresses);
10812
+ let walletAddresses = actualMerchantWallets;
10813
+ if (Object.keys(walletAddresses).length === 0) {
10814
+ log("No wallet addresses found, fetching from backend...");
10815
+ walletAddresses = yield getMerchantWallets();
10816
+ setActualMerchantWallets(walletAddresses);
10862
10817
  }
10863
- log("Final wallet addresses for payment:", finalWalletAddresses);
10818
+ log("Using wallet addresses:", walletAddresses);
10864
10819
  const paymentResponse = yield createPayment({
10865
10820
  amount: paymentDetails.amount,
10866
10821
  currency: paymentDetails.currency || "USDT",
@@ -10868,24 +10823,15 @@ const CoinleyCheckout = forwardRef(({
10868
10823
  customerEmail: paymentDetails.customerEmail || customerEmail,
10869
10824
  callbackUrl: paymentDetails.callbackUrl,
10870
10825
  metadata: __spreadProps(__spreadValues({}, paymentDetails.metadata), {
10871
- sdkVersion: "1.0.0",
10872
- merchantWallets: finalWalletAddresses
10826
+ merchantWalletAddresses: walletAddresses
10873
10827
  }),
10874
- merchantWalletAddresses: finalWalletAddresses
10828
+ merchantWalletAddresses: walletAddresses
10875
10829
  });
10876
10830
  log("Payment created:", paymentResponse);
10877
- if (paymentResponse.payment) {
10878
- setPayment(paymentResponse.payment);
10879
- if (paymentResponse.merchantConfig && paymentResponse.merchantConfig.walletAddresses) {
10880
- setMerchantWallets((prev) => __spreadValues(__spreadValues({}, prev), paymentResponse.merchantConfig.walletAddresses));
10881
- log("Updated wallet addresses from payment response:", paymentResponse.merchantConfig.walletAddresses);
10882
- }
10883
- setPaymentStatus("idle");
10884
- setError(null);
10885
- } else {
10886
- throw new Error("Invalid payment response structure");
10887
- }
10888
- log("Payment created and state updated successfully");
10831
+ setPayment(paymentResponse.payment);
10832
+ setPaymentStatus("idle");
10833
+ setError(null);
10834
+ log("Payment created and state updated");
10889
10835
  } catch (err) {
10890
10836
  log("Error creating payment:", err);
10891
10837
  setError(err.message || "Failed to create payment");
@@ -10900,67 +10846,60 @@ const CoinleyCheckout = forwardRef(({
10900
10846
  setWalletConnection(null);
10901
10847
  setSelectedPaymentMethod(null);
10902
10848
  setStep("select-currency");
10903
- setError(null);
10904
10849
  if (onClose)
10905
10850
  onClose();
10906
10851
  };
10907
10852
  const handlePaymentMethodSelect = (paymentMethod) => {
10853
+ console.log("=== PAYMENT METHOD SELECTION DEBUG ===");
10854
+ console.log("1. Payment method selected:", paymentMethod);
10855
+ console.log("2. Current step before:", step);
10908
10856
  log("Payment method selected:", paymentMethod);
10909
10857
  setSelectedPaymentMethod(paymentMethod);
10910
10858
  setStep("confirm");
10859
+ console.log("3. Step should now be: confirm");
10860
+ console.log("=== END PAYMENT METHOD SELECTION DEBUG ===");
10911
10861
  };
10912
10862
  const handleBack = () => {
10913
10863
  if (step === "confirm") {
10914
10864
  setStep("select-currency");
10915
10865
  setWalletConnection(null);
10916
- setError(null);
10917
10866
  } else if (step === "error") {
10918
10867
  setStep("confirm");
10919
- setError(null);
10920
10868
  }
10921
10869
  };
10922
10870
  const handleConnectWallet = (walletType) => __async(void 0, null, function* () {
10871
+ console.log("=== WALLET CONNECTION DEBUG ===");
10872
+ console.log("1. Wallet type requested:", walletType);
10873
+ console.log("2. Selected payment method:", selectedPaymentMethod);
10874
+ console.log("3. Available wallets:", availableWallets);
10875
+ console.log("4. Current step:", step);
10923
10876
  if (!selectedPaymentMethod) {
10877
+ console.error("No payment method selected");
10924
10878
  setError("Please select a payment method first");
10925
10879
  return;
10926
10880
  }
10927
10881
  try {
10882
+ console.log("5. Attempting to connect wallet...");
10928
10883
  setError(null);
10929
10884
  log("Connecting wallet:", { walletType, network: selectedPaymentMethod.network });
10930
10885
  const connection = yield connectWallet(walletType, selectedPaymentMethod.network, 2);
10931
10886
  setWalletConnection(connection);
10932
10887
  setError(null);
10888
+ console.log("6. Connection successful:", connection);
10933
10889
  log("Wallet connected successfully:", connection);
10934
10890
  } catch (err) {
10891
+ console.error("7. Connection failed:", err);
10935
10892
  log("Wallet connection error:", err);
10936
10893
  setError(err.message || "Failed to connect wallet");
10937
10894
  }
10895
+ console.log("=== END WALLET CONNECTION DEBUG ===");
10938
10896
  });
10939
- const getRecipientAddress = () => {
10940
- if (!selectedPaymentMethod)
10941
- return null;
10942
- const network = selectedPaymentMethod.network;
10943
- if (payment && payment.recipientWallet) {
10944
- return payment.recipientWallet;
10945
- }
10946
- if (merchantWallets[network]) {
10947
- return merchantWallets[network];
10948
- }
10949
- if (merchantWalletAddresses[network]) {
10950
- return merchantWalletAddresses[network];
10951
- }
10952
- return null;
10953
- };
10954
10897
  const handlePayment = () => __async(void 0, null, function* () {
10898
+ var _a2, _b;
10955
10899
  if (!payment || !selectedPaymentMethod) {
10956
10900
  setError("Missing payment information");
10957
10901
  return;
10958
10902
  }
10959
- const recipientAddress = getRecipientAddress();
10960
- if (!recipientAddress && !testMode) {
10961
- setError(`No recipient wallet address configured for ${selectedPaymentMethod.network} network`);
10962
- return;
10963
- }
10964
10903
  if (!walletConnection && !testMode) {
10965
10904
  setError("Please connect your wallet first");
10966
10905
  return;
@@ -10975,20 +10914,23 @@ const CoinleyCheckout = forwardRef(({
10975
10914
  log("Test mode: Generating mock transaction...");
10976
10915
  txHash = `test_${Date.now().toString(16)}_${Math.random().toString(16).substring(2, 10)}`;
10977
10916
  } else {
10978
- log("Sending transaction through wallet...", {
10979
- recipientAddress,
10980
- amount: payment.totalAmount || payment.amount,
10981
- network: selectedPaymentMethod.network
10982
- });
10983
- const tokenConfig = payment.token || selectedPaymentMethod.tokenConfig;
10917
+ let merchantAddress;
10918
+ if (payment.recipientWallet) {
10919
+ merchantAddress = payment.recipientWallet;
10920
+ } else if (actualMerchantWallets[selectedPaymentMethod.network]) {
10921
+ merchantAddress = actualMerchantWallets[selectedPaymentMethod.network];
10922
+ } else {
10923
+ throw new Error(`No merchant wallet address found for ${selectedPaymentMethod.network} network`);
10924
+ }
10925
+ log("Using merchant address for payment:", merchantAddress);
10926
+ log("Sending transaction through wallet...");
10984
10927
  txHash = yield sendTransaction(walletConnection, {
10985
- to: recipientAddress,
10928
+ to: merchantAddress,
10986
10929
  amount: payment.totalAmount || payment.amount,
10987
- tokenAddress: tokenConfig == null ? void 0 : tokenConfig.contractAddress,
10988
- tokenDecimals: tokenConfig == null ? void 0 : tokenConfig.decimals,
10930
+ tokenAddress: (_a2 = selectedPaymentMethod.tokenConfig) == null ? void 0 : _a2.address,
10931
+ tokenDecimals: (_b = selectedPaymentMethod.tokenConfig) == null ? void 0 : _b.decimals,
10989
10932
  currency: selectedPaymentMethod.currency,
10990
- network: selectedPaymentMethod.network,
10991
- tokenConfig
10933
+ network: selectedPaymentMethod.network
10992
10934
  });
10993
10935
  }
10994
10936
  log("Transaction hash:", txHash);
@@ -11009,27 +10951,16 @@ const CoinleyCheckout = forwardRef(({
11009
10951
  onSuccess(payment.id, txHash, {
11010
10952
  network: selectedPaymentMethod.network,
11011
10953
  currency: selectedPaymentMethod.currency,
11012
- amount: payment.totalAmount || payment.amount,
11013
- recipientAddress
10954
+ amount: payment.totalAmount || payment.amount
11014
10955
  });
11015
10956
  }
11016
10957
  } catch (err) {
11017
10958
  log("Payment error:", err);
11018
- let errorMessage = err.message || "Failed to process payment";
11019
- if (errorMessage.includes("User rejected") || errorMessage.includes("user rejected")) {
11020
- errorMessage = "Transaction was rejected by user";
11021
- } else if (errorMessage.includes("insufficient funds")) {
11022
- errorMessage = "Insufficient funds in wallet";
11023
- } else if (errorMessage.includes("network")) {
11024
- errorMessage = "Network error. Please check your connection and try again";
11025
- } else if (errorMessage.includes("recipient") || errorMessage.includes("address")) {
11026
- errorMessage = "Invalid recipient address. Please contact support";
11027
- }
11028
- setError(errorMessage);
10959
+ setError(err.message || "Failed to process payment");
11029
10960
  setPaymentStatus("error");
11030
10961
  setStep("error");
11031
10962
  if (onError)
11032
- onError(new Error(errorMessage));
10963
+ onError(err);
11033
10964
  }
11034
10965
  });
11035
10966
  const getSupportedWallets = () => {
@@ -11037,12 +10968,6 @@ const CoinleyCheckout = forwardRef(({
11037
10968
  return [];
11038
10969
  return getSupportedWalletsForNetwork(selectedPaymentMethod.network);
11039
10970
  };
11040
- if (isLoadingWallets) {
11041
- 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: [
11042
- /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "animate-spin rounded-full h-6 w-6 border-2 border-blue-500 border-t-transparent" }),
11043
- /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-700", children: "Loading payment gateway..." })
11044
- ] }) }) });
11045
- }
11046
10971
  return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: isOpen && /* @__PURE__ */ jsxRuntimeExports.jsx(
11047
10972
  CoinleyModal,
11048
10973
  {
@@ -11065,8 +10990,7 @@ const CoinleyCheckout = forwardRef(({
11065
10990
  availableWallets,
11066
10991
  supportedWallets: getSupportedWallets(),
11067
10992
  step,
11068
- merchantWalletAddresses: merchantWallets,
11069
- recipientAddress: getRecipientAddress(),
10993
+ merchantWalletAddresses: actualMerchantWallets,
11070
10994
  debug: effectiveDebug
11071
10995
  }
11072
10996
  ) });
@@ -11096,7 +11020,7 @@ export {
11096
11020
  createPayment,
11097
11021
  detectWallets,
11098
11022
  generateMockTransactionHash,
11099
- getMerchantProfile,
11023
+ getMerchantWallets,
11100
11024
  getPayment,
11101
11025
  getSupportedNetworks,
11102
11026
  getSupportedWalletsForNetwork,