coinley-test 0.0.21 → 0.0.22
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.
- package/dist/index.esm.js +90 -6
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("framer-motion"),require("lucide-react"),require("@coinley/wallet-connect-core"),require("axios")):"function"==typeof define&&define.amd?define(["exports","react","framer-motion","lucide-react","@coinley/wallet-connect-core","axios"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CoinleyTest={},e.React,e.FramerMotion,e.LucideReact,e.CoinleyWalletCore,e.axios)}(this,function(e,t,s,a,r,n){"use strict";var o={exports:{}},l={},c=t,i=Symbol.for("react.element"),d=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,h=c.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function x(e,t,s){var a,r={},n=null,o=null;for(a in void 0!==s&&(n=""+s),void 0!==t.key&&(n=""+t.key),void 0!==t.ref&&(o=t.ref),t)m.call(t,a)&&!u.hasOwnProperty(a)&&(r[a]=t[a]);if(e&&e.defaultProps)for(a in t=e.defaultProps)void 0===r[a]&&(r[a]=t[a]);return{$$typeof:i,type:e,key:n,ref:o,props:r,_owner:h.current}}l.Fragment=d,l.jsx=x,l.jsxs=x,o.exports=l;var y=o.exports;class p{constructor(e,t,s){this.apiKey=t,this.apiSecret=s,this.api=n.create({baseURL:e.endsWith("/")?e.slice(0,-1):e,timeout:3e4,headers:{"Content-Type":"application/json"}}),this.api.interceptors.request.use(e=>{var t;e.headers["X-API-Key"]=this.apiKey,e.headers["X-API-Secret"]=this.apiSecret;const s=this.generateMerchantToken();return s&&(e.headers.Authorization=`Bearer ${s}`),console.log("API Request:",{method:null==(t=e.method)?void 0:t.toUpperCase(),url:e.url,data:e.data}),e},e=>(console.error("Request interceptor error:",e),Promise.reject(e))),this.api.interceptors.response.use(e=>(console.log("API Response:",{status:e.status,url:e.config.url,data:e.data}),e),e=>{var t,s,a,r,n;if(console.error("API Error:",{status:null==(t=e.response)?void 0:t.status,data:null==(s=e.response)?void 0:s.data,message:e.message}),401===(null==(a=e.response)?void 0:a.status))throw new Error("Authentication failed. Please check your API credentials.");if(404===(null==(r=e.response)?void 0:r.status))throw new Error("API endpoint not found. Please check your API URL.");if((null==(n=e.response)?void 0:n.status)>=500)throw new Error("Server error. Please try again later.");throw e})}generateMerchantToken(){try{const e=`${this.apiKey}:${this.apiSecret}`;return btoa(e)}catch(e){return console.error("Failed to generate token:",e),null}}async createPayment(e){var t,s;try{return(await this.api.post("/api/payments/create",e)).data}catch(a){if(null==(s=null==(t=a.response)?void 0:t.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Failed to create payment")}}async getPayment(e){var t,s;try{return(await this.api.get(`/api/payments/${e}`)).data}catch(a){if(null==(s=null==(t=a.response)?void 0:t.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Failed to get payment details")}}async getNetworks(){try{return(await this.api.get("/api/networks")).data}catch(e){return console.error("Get networks failed:",e),{networks:[{id:"ethereum",name:"Ethereum",shortName:"ethereum",chainId:"1",type:"ethereum",explorerUrl:"https://etherscan.io",isTestnet:!1},{id:"bsc",name:"Binance Smart Chain",shortName:"bsc",chainId:"56",type:"bsc",explorerUrl:"https://bscscan.com",isTestnet:!1},{id:"polygon",name:"Polygon",shortName:"polygon",chainId:"137",type:"ethereum",explorerUrl:"https://polygonscan.com",isTestnet:!1}]}}}async getStablecoins(){try{return(await this.api.get("/api/networks/stablecoins")).data}catch(e){return console.error("Get stablecoins failed:",e),{stablecoins:[{id:"usdt-eth",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}},{id:"usdc-eth",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E6441d81d0B93bF9EE0f74ca32F7e6f6",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}}]}}}async verifyQRPayment(e){var t,s;try{return(await this.api.post("/api/payments/verify-qr",{paymentId:e})).data}catch(a){if(null==(s=null==(t=a.response)?void 0:t.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Failed to verify payment")}}async processPayment(e,t,s,a){var r,n;try{return(await this.api.post("/api/payments/process",{paymentId:e,transactionHash:t,network:s,senderAddress:a})).data}catch(o){if(null==(n=null==(r=o.response)?void 0:r.data)?void 0:n.error)throw new Error(o.response.data.error);throw new Error(o.message||"Failed to process payment")}}async healthCheck(){try{return 200===(await this.api.get("/api/health")).status}catch(e){return console.error("Health check failed:",e),!1}}}const g=({selectedNetwork:e,selectedToken:t,paymentData:s,config:n,onTransactionSent:o,onError:l,isConnecting:c,setIsConnecting:i})=>{const{isConnected:d,address:m,disconnect:h}=r.useWallet(),{connectWallet:u,isPending:x}=r.useWalletConnect(),{detectedWallets:p,hasWallets:g,walletCount:f}=r.useWalletDetection(),{sendTransaction:b}=r.useWalletTransaction(),{openModal:w}=r.useWalletModal();p.filter(e=>e.name.toLowerCase().includes("metamask")||"injected"===e.provider||e.name.toLowerCase().includes("coinbase")||e.name.toLowerCase().includes("wallet connect"));const j=async e=>{try{if(i(!0),d&&(await h(),await new Promise(e=>setTimeout(e,1e3))),"metamask"===e&&window.ethereum&&window.ethereum.isMetaMask)try{await window.ethereum.request({method:"eth_requestAccounts"}),console.log("✅ Connected directly to MetaMask")}catch(t){throw console.error("MetaMask connection failed:",t),t}else await u(e)}catch(t){console.error("Wallet connection failed:",t),l(t.message||"Failed to connect wallet")}finally{i(!1)}};return y.jsx("div",{className:"text-center space-y-6",children:y.jsxs("div",{className:"space-y-4",children:[y.jsx("div",{className:"w-16 h-16 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center mx-auto",children:y.jsx(a.Wallet,{className:"w-8 h-8 text-[#7042D2]"})}),d?y.jsxs(y.Fragment,{children:[y.jsx("h3",{className:"text-lg font-semibold text-green-600",children:"Wallet Connected ✅"}),y.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-3",children:[y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Address:"}),y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsxs("span",{className:"font-mono text-sm",children:[null==m?void 0:m.slice(0,6),"...",null==m?void 0:m.slice(-4)]}),y.jsx("button",{onClick:async()=>{try{await h()}catch(e){console.error("Disconnect error:",e)}},className:"text-xs text-red-600 hover:text-red-800",children:"Disconnect"})]})]}),s&&y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Amount:"}),y.jsxs("span",{className:"font-medium",children:[s.totalAmount," ",null==t?void 0:t.symbol]})]}),y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Network:"}),y.jsx("span",{className:"font-medium",children:null==e?void 0:e.name})]})]})]}),y.jsx("button",{onClick:async()=>{var a;if(d&&s&&t)try{i(!0),console.log("🔍 Transaction Debug:"),console.log("Connected wallet address:",m),console.log("Payment data:",s),console.log("Selected token:",t),console.log("Selected network:",e);let r,n=null==(a=s.metadata)?void 0:a.recipientWallet;if(console.log("Merchant recipient address:",n),!n||"string"!=typeof n)throw new Error("Merchant wallet address not found in payment data");if(!n.match(/^0x[a-fA-F0-9]{40}$/))throw new Error(`Invalid merchant address format: ${n}`);if(t.contractAddress){console.log("🔍 ERC-20 Transaction Details:"),console.log("Token contract:",t.contractAddress),console.log("Token decimals:",t.decimals),console.log("Payment amount:",s.totalAmount);const e=t.decimals||6,a=Math.floor(s.totalAmount*Math.pow(10,e));console.log("Calculated amount (with decimals):",a);const o="0xa9059cbb",l=n.slice(2).toLowerCase().padStart(64,"0"),c=a.toString(16).padStart(64,"0"),i=`${o}${l}${c}`;console.log("🔍 Transaction Data:"),console.log("Method ID:",o),console.log("Recipient (padded):",l),console.log("Amount (padded):",c),console.log("Full data:",i);const d={to:t.contractAddress,data:i,value:"0x0"};console.log("📤 Sending ERC-20 transaction:",d),r=await b(d)}else{const e=Math.floor(s.totalAmount*Math.pow(10,18)),t={to:n,value:`0x${e.toString(16)}`};console.log("📤 Sending native transaction:",t),r=await b(t)}r&&(console.log("✅ Transaction sent successfully:",r),o(r))}catch(r){console.error("❌ Transaction failed:",r),l(r.message||"Transaction failed")}finally{i(!1)}else l("Wallet not connected or payment data missing")},disabled:c,className:"w-full bg-[#7042D2] text-white py-4 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center space-x-2",children:c?y.jsxs(y.Fragment,{children:[y.jsx(a.Loader2,{className:"w-5 h-5 animate-spin"}),y.jsx("span",{children:"Processing Payment..."})]}):y.jsxs(y.Fragment,{children:[y.jsx(a.Zap,{className:"w-5 h-5"}),y.jsx("span",{children:"Send Payment"})]})}),y.jsxs("p",{className:"text-xs text-gray-500",children:["Make sure you have enough ",null==t?void 0:t.symbol," and ETH for gas fees"]})]}):y.jsxs(y.Fragment,{children:[y.jsx("h3",{className:"text-lg font-semibold",children:"Connect Your Wallet"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 text-sm",children:"Choose your preferred wallet to complete the payment"}),y.jsxs("div",{className:"space-y-3",children:[y.jsxs("button",{onClick:()=>j("metamask"),disabled:x||c,className:"w-full p-3 border border-gray-300 rounded-lg hover:border-[#7042D2] flex items-center space-x-3 transition-colors disabled:opacity-50",children:[y.jsx("span",{className:"text-xl",children:"🦊"}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-medium",children:"MetaMask"}),y.jsx("div",{className:"text-xs text-gray-500",children:"Connect with MetaMask"})]})]}),y.jsxs("button",{onClick:()=>{try{console.log("Attempting to open wallet modal..."),w()}catch(e){console.error("Failed to open modal:",e),j("injected")}},disabled:x||c,className:"w-full p-3 border border-gray-300 rounded-lg hover:border-[#7042D2] flex items-center space-x-3 transition-colors disabled:opacity-50",children:[y.jsx("span",{className:"text-xl",children:"💼"}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-medium",children:"Other Wallets"}),y.jsx("div",{className:"text-xs text-gray-500",children:"Choose from available wallets"})]})]}),y.jsx("button",{onClick:()=>j("injected"),disabled:x||c,className:"w-full p-2 text-sm border border-dashed border-gray-300 rounded-lg hover:border-[#7042D2] transition-colors disabled:opacity-50",children:"Try Direct Connection"})]}),c&&y.jsxs("div",{className:"flex items-center justify-center space-x-2 text-gray-600",children:[y.jsx(a.Loader2,{className:"w-4 h-4 animate-spin"}),y.jsx("span",{children:"Connecting..."})]})]})]})})},f=({apiKey:e,apiSecret:n,apiUrl:o="http://localhost:9000",onSuccess:l,onError:c,onClose:i,isOpen:d,config:m,theme:h="light",merchantName:u,debug:x=!1})=>{const[f,b]=t.useState("select-method"),[w,j]=t.useState([]),[v,N]=t.useState([]),[k,C]=t.useState(null),[S,P]=t.useState(null),[A,T]=t.useState(null),[E,D]=t.useState(""),[M,W]=t.useState(null),[I,F]=t.useState(!1),[$,U]=t.useState(""),[R,q]=t.useState(!1),[L,_]=t.useState(""),[O,H]=t.useState(!1),B=t.useRef(new p(o,e,n)),K=r.createCoinleyWalletConfig({appName:u||"Coinley Payment",appDescription:"Crypto payment processing",chains:[{id:1,name:"Ethereum",network:"ethereum",rpcUrls:{default:{http:["https://eth.llamarpc.com"]}},nativeCurrency:{name:"Ethereum",symbol:"ETH",decimals:18}},{id:56,name:"BNB Smart Chain",network:"bsc",rpcUrls:{default:{http:["https://bsc-dataseed1.binance.org"]}},nativeCurrency:{name:"BNB",symbol:"BNB",decimals:18}}]});t.useEffect(()=>{d&&Q()},[d]);const Q=async()=>{try{F(!0),U("");const[e,t]=await Promise.all([B.current.getNetworks(),B.current.getStablecoins()]);j(e.networks||[]),N(t.stablecoins||[]),x&&(console.log("Initialized networks:",e.networks),console.log("Initialized tokens:",t.stablecoins))}catch(e){console.error("Failed to initialize payment:",e),U("Failed to load payment options. Please try again.")}finally{F(!1)}},z=e=>{T(e),b("select-network")},X=async(e,t)=>{try{F(!0);const s={amount:m.amount,currency:t.symbol,network:e.shortName,customerEmail:m.customerEmail,callbackUrl:m.callbackUrl,metadata:{...m.metadata,paymentMethod:A,selectedNetwork:e.shortName,selectedToken:t.symbol,merchantWalletAddresses:m.merchantWalletAddresses}};console.log("🔍 Payment payload with merchant wallets:",s);const a=await B.current.createPayment(s);W(a.payment),"wallet"===A?b("wallet-connect"):(await Y(a.payment),b("qr-code"))}catch(s){console.error("Payment initiation failed:",s),U(s.message||"Failed to create payment"),b("error")}finally{F(!1)}},Y=async e=>{var t,s;try{const a=(null==(t=e.metadata)?void 0:t.recipientWallet)||(null==(s=m.merchantWalletAddresses)?void 0:s[(null==k?void 0:k.shortName)||""]);if(!a)throw new Error("Recipient wallet address not found");let r="";r="ethereum"===(null==k?void 0:k.type)||"bsc"===(null==k?void 0:k.type)?(null==S?void 0:S.contractAddress)?`ethereum:${S.contractAddress}/transfer?address=${a}&uint256=${e.totalAmount*Math.pow(10,S.decimals)}`:`ethereum:${a}?value=${e.totalAmount}e18`:"tron"===(null==k?void 0:k.type)?`tron:${a}?amount=${e.totalAmount}`:`${null==S?void 0:S.symbol}:${a}?amount=${e.totalAmount}`,D(a),Z(e.id)}catch(a){console.error("QR code generation failed:",a),U("Failed to generate QR code"),b("error")}},Z=async e=>{let t=0;const s=async()=>{var a;try{const r=await B.current.verifyQRPayment(e);return r.verified&&(null==(a=r.payment)?void 0:a.transactionHash)?(_(r.payment.transactionHash),await G(e,r.payment.transactionHash),!0):(t++,t<60?setTimeout(s,5e3):(U("Payment verification timeout. Please check your transaction."),b("error")),!1)}catch(r){return console.error("Payment verification error:",r),t++,t<60?setTimeout(s,5e3):(U("Payment verification failed"),b("error")),!1}};setTimeout(s,2e3)},G=async(e,t)=>{b("success"),l&&l(e,t,{network:null==k?void 0:k.name,token:null==S?void 0:S.symbol,amount:null==M?void 0:M.totalAmount,method:A})},V=()=>{b("select-method"),T(null),C(null),P(null),D(""),W(null),U(""),_(""),i&&i()};return d?y.jsxs(r.CoinleyWalletProvider,{config:K,walletConfig:{appName:u||"Coinley Payment"},children:[y.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm",children:y.jsxs(s.motion.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.9,opacity:0},className:"relative w-full max-w-md mx-4 rounded-2xl shadow-2xl overflow-hidden "+("dark"===h?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[y.jsxs("div",{className:"relative p-6 border-b border-gray-200 dark:border-gray-700",children:["select-method"!==f&&"success"!==f&&"error"!==f&&y.jsx("button",{onClick:()=>{if("select-network"===f)b("select-method");else if("select-token"===f)b("select-network");else if("wallet-connect"===f||"qr-code"===f){v.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==k?void 0:k.shortName)||e.networkId===(null==k?void 0:k.id)}).length>1?b("select-token"):b("select-network")}},className:"absolute left-4 top-6 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors",children:y.jsx(a.ArrowLeft,{className:"w-5 h-5"})}),y.jsx("button",{onClick:V,className:"absolute right-4 top-6 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors",children:y.jsx(a.X,{className:"w-5 h-5"})}),y.jsxs("div",{className:"text-center",children:[y.jsxs("div",{className:"flex items-center justify-center space-x-2 mb-2",children:[y.jsx(a.Sparkles,{className:"w-5 h-5 text-[#7042D2]"}),y.jsx("h2",{className:"text-xl font-bold",children:"Pay with Crypto"}),y.jsx(a.Sparkles,{className:"w-5 h-5 text-[#7042D2]"})]}),u&&y.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:u}),y.jsx("div",{className:"mt-2",children:y.jsxs("span",{className:"text-2xl font-bold text-[#7042D2]",children:["$",m.amount.toFixed(2)]})})]})]}),y.jsx("div",{className:"p-6 min-h-[400px]",children:y.jsxs(s.AnimatePresence,{mode:"wait",children:["select-method"===f&&y.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[y.jsx("h3",{className:"text-lg font-semibold text-center mb-6",children:"Choose Payment Method"}),y.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>z("wallet"),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[y.jsx("div",{className:"p-3 bg-[#7042D2] bg-opacity-10 rounded-lg group-hover:bg-opacity-20 transition-colors",children:y.jsx(a.Wallet,{className:"w-6 h-6 text-[#7042D2]"})}),y.jsxs("div",{className:"text-left",children:[y.jsx("div",{className:"font-semibold",children:"Connect Wallet"}),y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:"MetaMask, WalletConnect & more"})]}),y.jsx(a.Zap,{className:"w-5 h-5 text-[#7042D2] ml-auto"})]})}),y.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>z("qr"),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[y.jsx("div",{className:"p-3 bg-[#7042D2] bg-opacity-10 rounded-lg group-hover:bg-opacity-20 transition-colors",children:y.jsx(a.QrCode,{className:"w-6 h-6 text-[#7042D2]"})}),y.jsxs("div",{className:"text-left",children:[y.jsx("div",{className:"font-semibold",children:"QR Code"}),y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Scan with mobile wallet"})]})]})})]},"select-method"),"select-network"===f&&y.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[y.jsx("h3",{className:"text-lg font-semibold text-center mb-6",children:"Select Network"}),I?y.jsx("div",{className:"flex justify-center py-8",children:y.jsx(a.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}):y.jsx("div",{className:"space-y-3",children:w.map(e=>y.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>(async e=>{C(e);const t=v.filter(t=>{var s;return(null==(s=t.Network)?void 0:s.shortName)===e.shortName||t.networkId===e.id});if(t.length>1)b("select-token");else if(1===t.length){const s=t[0];P(s),await X(e,s)}else U(`No supported tokens found for ${e.name}`),b("error")})(e),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[e.logo?y.jsx("img",{src:e.logo,alt:e.name,className:"w-8 h-8 rounded-full"}):y.jsx("div",{className:"w-8 h-8 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center",children:y.jsx("span",{className:"text-sm font-bold text-[#7042D2]",children:e.shortName.charAt(0).toUpperCase()})}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-semibold",children:e.name}),y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:e.shortName.toUpperCase()})]}),y.jsx(a.ChevronDown,{className:"w-5 h-5 text-gray-400 transform -rotate-90"})]})},e.id))})]},"select-network"),"select-token"===f&&y.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[y.jsxs("h3",{className:"text-lg font-semibold text-center mb-6",children:["Select Token on ",null==k?void 0:k.name]}),I?y.jsx("div",{className:"flex justify-center py-8",children:y.jsx(a.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}):y.jsx("div",{className:"space-y-3",children:v.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==k?void 0:k.shortName)||e.networkId===(null==k?void 0:k.id)}).map(e=>y.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>(async e=>{P(e),await X(k,e)})(e),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[e.logo?y.jsx("img",{src:e.logo,alt:e.symbol,className:"w-8 h-8 rounded-full"}):y.jsx("div",{className:"w-8 h-8 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center",children:y.jsx("span",{className:"text-sm font-bold text-[#7042D2]",children:e.symbol.charAt(0)})}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-semibold",children:e.name}),y.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:[e.symbol,e.isStablecoin&&y.jsx("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-600 text-xs rounded-full",children:"Stablecoin"})]})]}),y.jsx(a.ChevronDown,{className:"w-5 h-5 text-gray-400 transform -rotate-90"})]})},e.id))})]},"select-token"),"wallet-connect"===f&&y.jsx(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},children:y.jsx(g,{selectedNetwork:k,selectedToken:S,paymentData:M,config:m,onTransactionSent:async e=>{_(e),b("processing");try{await B.current.processPayment(M.id,e,(null==k?void 0:k.shortName)||"",""),await G(M.id,e)}catch(t){console.error("Payment processing failed:",t),await G(M.id,e)}},onError:U,isConnecting:O,setIsConnecting:H})},"wallet-connect"),"qr-code"===f&&y.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"text-center space-y-6",children:[y.jsxs("div",{className:"space-y-4",children:[y.jsx("h3",{className:"text-lg font-semibold",children:"Scan QR Code"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Use your mobile wallet to scan and pay"})]}),E&&y.jsx("div",{className:"bg-white p-4 rounded-xl mx-auto inline-block",children:y.jsxs("div",{className:"w-48 h-48 flex items-center justify-center text-gray-500",children:["QR Code: ",E.slice(0,10),"...",E.slice(-4)]})}),M&&y.jsxs("div",{className:"space-y-3",children:[y.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-2",children:[y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Network:"}),y.jsx("span",{className:"font-medium",children:null==k?void 0:k.name})]}),y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Amount:"}),y.jsxs("span",{className:"font-medium",children:[M.totalAmount," ",null==S?void 0:S.symbol]})]})]}),y.jsxs("div",{className:"flex items-center justify-center space-x-2 text-sm text-gray-600 dark:text-gray-400",children:[y.jsx(a.Loader2,{className:"w-4 h-4 animate-spin"}),y.jsx("span",{children:"Waiting for payment..."})]})]})]},"qr-code"),"processing"===f&&y.jsxs(s.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[y.jsx("div",{className:"w-16 h-16 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center mx-auto",children:y.jsx(a.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}),y.jsxs("div",{children:[y.jsx("h3",{className:"text-lg font-semibold text-[#7042D2]",children:"Processing Payment..."}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:"Your transaction is being processed"})]})]},"processing"),"success"===f&&y.jsxs(s.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[y.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx(a.CheckCircle2,{className:"w-8 h-8 text-green-500"})}),y.jsxs("div",{children:[y.jsx("h3",{className:"text-lg font-semibold text-green-600",children:"Payment Successful!"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:"Your payment has been processed successfully"})]}),L&&y.jsx("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4",children:y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Transaction:"}),y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsxs("span",{className:"font-mono text-sm",children:[L.slice(0,6),"...",L.slice(-4)]}),y.jsx("button",{onClick:()=>(async e=>{try{await navigator.clipboard.writeText(e),q(!0),setTimeout(()=>q(!1),2e3)}catch(t){console.error("Failed to copy:",t)}})(L),className:"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded",children:y.jsx(a.Copy,{className:"w-4 h-4"})}),(null==k?void 0:k.explorerUrl)&&y.jsx("a",{href:`${k.explorerUrl}/tx/${L}`,target:"_blank",rel:"noopener noreferrer",className:"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded",children:y.jsx(a.ExternalLink,{className:"w-4 h-4"})})]})]})}),y.jsx("button",{onClick:V,className:"w-full bg-[#7042D2] text-white py-3 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors",children:"Close"})]},"success"),"error"===f&&y.jsxs(s.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[y.jsx("div",{className:"w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx(a.AlertCircle,{className:"w-8 h-8 text-red-500"})}),y.jsxs("div",{children:[y.jsx("h3",{className:"text-lg font-semibold text-red-600",children:"Payment Failed"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:$||"Something went wrong. Please try again."})]}),y.jsxs("div",{className:"space-y-3",children:[y.jsx("button",{onClick:()=>{b("select-method"),U("")},className:"w-full bg-[#7042D2] text-white py-3 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors",children:"Try Again"}),y.jsx("button",{onClick:V,className:"w-full border border-gray-300 dark:border-gray-600 py-3 rounded-lg font-semibold hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Close"})]})]},"error")]})}),y.jsx("div",{className:"px-6 py-4 border-t border-gray-200 dark:border-gray-700 text-center",children:y.jsxs("p",{className:"text-xs text-gray-500",children:["Powered by ",y.jsx("span",{className:"font-semibold text-[#7042D2]",children:"Coinley"})]})})]})}),y.jsx(r.WalletModal,{})]}):null},b=t.createContext(null),w=t.forwardRef(({customerEmail:e="",merchantName:s="",onSuccess:a,onError:r,onClose:n,theme:o="light",autoOpen:l=!1,testMode:c=!1,debug:i=!1,merchantWalletAddresses:d={}},m)=>{const h=t.useContext(b);if(!h)throw new Error("CoinleyCheckout must be used within a CoinleyProvider");const{openPayment:u,closePayment:x}=h,y=t=>{try{if(i&&console.log("Opening Coinley checkout with config:",t),!t.amount||t.amount<=0)throw new Error("Amount must be greater than 0");const s={...t,customerEmail:t.customerEmail||e,merchantWalletAddresses:{...d,...t.merchantWalletAddresses},metadata:{...t.metadata,testMode:c,checkoutVersion:"1.0.0"}};u(s,{onSuccess:a,onError:r,onClose:n})}catch(s){console.error("Failed to open Coinley checkout:",s),r&&r(s)}},p=()=>{x()};return t.useImperativeHandle(m,()=>({open:y,close:p})),null});w.displayName="CoinleyCheckout";class j{constructor(e,t,s){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,this.apiKey=t,this.apiSecret=s}async request(e,t={}){const s=`${this.baseURL}${e}`,a={"Content-Type":"application/json","X-API-Key":this.apiKey,"X-API-Secret":this.apiSecret,...t.headers},r=await fetch(s,{...t,headers:a});if(!r.ok){const e=await r.json().catch(()=>({}));throw new Error(e.error||`HTTP ${r.status}`)}return r.json()}async getNetworks(){try{return await this.request("/api/networks")}catch(e){return console.error("Failed to fetch networks:",e),{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(e){return console.error("Failed to fetch tokens:",e),{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}}class v{constructor(){this.account=null,this.chainId=null}async connect(){if(!window.ethereum)throw new Error("MetaMask not installed. Please install MetaMask extension.");try{const e=await window.ethereum.request({method:"eth_requestAccounts"}),t=await window.ethereum.request({method:"eth_chainId"});return this.account=e[0],this.chainId=t,console.log("✅ MetaMask connected:",this.account),{account:this.account,chainId:this.chainId}}catch(e){throw console.error("MetaMask connection failed:",e),new Error(e.message||"Failed to connect to MetaMask")}}async sendTransaction(e){if(!this.account)throw new Error("Wallet not connected");try{console.log("🦊 Sending MetaMask transaction:",e);const t=await window.ethereum.request({method:"eth_sendTransaction",params:[{...e,from:this.account}]});return console.log("✅ Transaction sent:",t),t}catch(t){throw console.error("Transaction failed:",t),4001===t.code?new Error("Transaction cancelled by user"):t.message.includes("insufficient funds")?new Error("Insufficient funds in wallet"):new Error(t.message||"Transaction failed")}}isConnected(){return!!this.account}}const N={formatAmount:(e,t=2)=>e.toFixed(t),truncateAddress:(e,t=6,s=4)=>e?e.length<=t+s?e:`${e.slice(0,t)}...${e.slice(-s)}`:"",isValidAddress:(e,t)=>{if(!e)return!1;switch(t.toLowerCase()){case"ethereum":case"bsc":case"polygon":return/^0x[a-fA-F0-9]{40}$/.test(e);case"tron":return/^T[a-zA-Z0-9]{33}$/.test(e);case"solana":return/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e);default:return e.length>0}},copyToClipboard:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}};class k extends Error{constructor(e,t){super(e),this.name="CoinleyError",this.code=t}}e.CoinleyCheckout=w,e.CoinleyError=k,e.CoinleyPayment=f,e.CoinleyProvider=({apiKey:e,apiSecret:s,apiUrl:a,theme:r="light",debug:n=!1,children:o})=>{const[l,c]=t.useState(!1),[i,d]=t.useState(null),[m,h]=t.useState({}),[u,x]=t.useState(""),p=()=>{c(!1),d(null),m.onClose&&m.onClose()},g={openPayment:(e,t)=>{d(e),t&&h(t),c(!0)},closePayment:p};return y.jsxs(b.Provider,{value:g,children:[o,l&&i&&y.jsx(f,{apiKey:e,apiSecret:s,apiUrl:a,isOpen:l,config:i,theme:r,debug:n,merchantName:u,onSuccess:m.onSuccess,onError:m.onError,onClose:p})]})},e.DEFAULT_CONFIG={theme:"light",debug:!1,testMode:!1,autoOpen:!1},e.PaymentAPI=p,e.SimpleCoinleyPayment=({apiKey:e,apiSecret:s,apiUrl:a,config:r,onSuccess:n,onError:o,onClose:l,isOpen:c,theme:i="light"})=>{var d,m;const[h,u]=t.useState("method"),[x,p]=t.useState([]),[g,f]=t.useState([]),[b,w]=t.useState(null),[N,k]=t.useState(null),[C,S]=t.useState(null),[P,A]=t.useState(null),[T,E]=t.useState(!1),[D,M]=t.useState(""),[W,I]=t.useState(new v),[F,$]=t.useState(!1),[U,R]=t.useState(!1),q=t.useRef(new j(a,e,s));t.useEffect(()=>{c&&(_(),L())},[c]);const L=()=>{u("method"),w(null),k(null),S(null),A(null),M(""),$(!1),R(!1),I(new v)},_=async()=>{var e,t;try{E(!0),M(""),console.log("🔄 Loading networks and tokens...");const[s,a]=await Promise.all([q.current.getNetworks(),q.current.getTokens()]);p(s.networks||[]),f(a.stablecoins||[]),console.log("✅ Loaded networks:",null==(e=s.networks)?void 0:e.length),console.log("✅ Loaded tokens:",null==(t=a.stablecoins)?void 0:t.length)}catch(s){console.error("Failed to load data:",s),M("Failed to load payment options. Using fallback data.")}finally{E(!1)}};if(!c)return null;const O="dark"===i;return y.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:y.jsxs("div",{className:"rounded-lg shadow-xl max-w-md w-full mx-4 "+(O?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[y.jsxs("div",{className:"p-4 border-b flex justify-between items-center "+(O?"border-gray-700":"border-gray-200"),children:[y.jsxs("div",{className:"text-center flex-1",children:[y.jsx("h2",{className:"text-lg font-semibold",children:"Pay with Crypto"}),r.amount&&y.jsxs("p",{className:"text-2xl font-bold text-purple-600",children:["$",r.amount.toFixed(2)]})]}),y.jsx("button",{onClick:l,className:"ml-4 text-gray-500 hover:text-gray-700 "+(O?"hover:text-gray-300":""),children:"✕"})]}),y.jsxs("div",{className:"p-4 min-h-[400px]",children:[D&&y.jsxs("div",{className:"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200",children:[D,y.jsx("button",{onClick:()=>M(""),className:"ml-2 text-red-500 hover:text-red-700",children:"✕"})]}),"method"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsx("h3",{className:"font-medium text-center mb-6",children:"Choose Payment Method"}),y.jsxs("div",{className:"space-y-3",children:[y.jsxs("button",{onClick:()=>{S("wallet"),u("network")},className:"w-full p-4 border-2 rounded-lg hover:border-purple-500 text-left flex items-center space-x-3 transition-colors "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsx("span",{className:"text-2xl",children:"🦊"}),y.jsxs("div",{children:[y.jsx("div",{className:"font-medium",children:"MetaMask Wallet"}),y.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:"Connect and pay instantly"})]})]}),y.jsxs("button",{onClick:()=>{S("qr"),u("network")},className:"w-full p-4 border-2 rounded-lg hover:border-purple-500 text-left flex items-center space-x-3 transition-colors "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsx("span",{className:"text-2xl",children:"📱"}),y.jsxs("div",{children:[y.jsx("div",{className:"font-medium",children:"QR Code"}),y.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:"Scan with mobile wallet"})]})]})]})]}),"network"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsx("button",{onClick:()=>u("method"),className:""+(O?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),y.jsx("h3",{className:"font-medium",children:"Select Network"})]}),y.jsx("div",{className:"space-y-2",children:x.map(e=>y.jsxs("button",{onClick:()=>{w(e),u("token")},className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsx("div",{className:"font-medium",children:e.name}),y.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:e.shortName.toUpperCase()})]},e.id))})]}),"token"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsx("button",{onClick:()=>u("network"),className:""+(O?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),y.jsxs("h3",{className:"font-medium",children:["Select Token on ",null==b?void 0:b.name]})]}),y.jsx("div",{className:"space-y-2",children:g.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==b?void 0:b.shortName)}).map(e=>y.jsxs("button",{onClick:()=>{k(e),(async()=>{try{E(!0),M("");const e={amount:r.amount,currency:N.symbol,network:b.shortName,customerEmail:r.customerEmail,callbackUrl:r.callbackUrl,metadata:{...r.metadata,merchantWalletAddresses:r.merchantWalletAddresses,paymentMethod:C,selectedNetwork:b.shortName,selectedToken:N.symbol}};console.log("🔄 Creating payment:",e);const t=await q.current.createPayment(e);A(t.payment),console.log("✅ Payment created:",t.payment.id),u("wallet"===C?"wallet":"qr")}catch(e){console.error("Payment creation failed:",e),M(e.message)}finally{E(!1)}})()},disabled:T,className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left flex justify-between transition-colors disabled:opacity-50 "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsxs("div",{children:[y.jsx("div",{className:"font-medium",children:e.name}),y.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:e.symbol})]}),e.isStablecoin&&y.jsx("span",{className:"px-2 py-1 bg-green-100 text-green-600 text-xs rounded",children:"Stablecoin"})]},e.id))})]}),"wallet"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsx("h3",{className:"font-medium text-center",children:"Connect & Pay"}),F?y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-200",children:[y.jsx("p",{className:"text-green-600 text-sm font-medium",children:"✅ Wallet Connected"}),y.jsxs("p",{className:"font-mono text-xs text-green-700 mt-1",children:[null==(d=W.account)?void 0:d.slice(0,6),"...",null==(m=W.account)?void 0:m.slice(-4)]})]}),y.jsxs("div",{className:"p-4 rounded-lg space-y-2 "+(O?"bg-gray-800":"bg-gray-50"),children:[y.jsxs("div",{className:"flex justify-between text-sm",children:[y.jsx("span",{children:"Amount:"}),y.jsxs("span",{className:"font-medium",children:[null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]})]}),y.jsxs("div",{className:"flex justify-between text-sm",children:[y.jsx("span",{children:"Network:"}),y.jsx("span",{className:"font-medium",children:null==b?void 0:b.name})]}),y.jsxs("div",{className:"flex justify-between text-sm",children:[y.jsx("span",{children:"Token:"}),y.jsx("span",{className:"font-medium",children:null==N?void 0:N.name})]})]}),y.jsx("button",{onClick:async()=>{var e,t;try{R(!0),M("");const s=(null==(e=P.metadata)?void 0:e.recipientWallet)||(null==(t=r.merchantWalletAddresses)?void 0:t[b.shortName]);if(!s)throw new Error("Merchant wallet address not found");let a;if(console.log("🔄 Preparing transaction to:",s),N.contractAddress){const e=N.decimals||6,t=Math.floor(P.totalAmount*Math.pow(10,e)),r="0xa9059cbb",n=s.slice(2).toLowerCase().padStart(64,"0"),o=`${r}${n}${t.toString(16).padStart(64,"0")}`;a={to:N.contractAddress,data:o,value:"0x0"},console.log("🔄 ERC-20 Transaction:",{token:N.symbol,amount:P.totalAmount,amountWithDecimals:t,to:N.contractAddress,recipient:s})}else{a={to:s,value:`0x${Math.floor(P.totalAmount*Math.pow(10,18)).toString(16)}`},console.log("🔄 Native Transaction:",{amount:P.totalAmount,to:s})}const o=await W.sendTransaction(a);console.log("✅ Transaction successful:",o),u("success"),null==n||n(P.id,o,{network:b.name,token:N.symbol,amount:P.totalAmount,method:C})}catch(s){console.error("Transaction failed:",s),M(s.message)}finally{R(!1)}},disabled:U,className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium flex items-center justify-center space-x-2",children:U?y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-white"}),y.jsx("span",{children:"Sending Transaction..."})]}):y.jsxs("span",{children:["Send ",null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]})})]}):y.jsxs("div",{className:"text-center space-y-4",children:[y.jsx("div",{className:"w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx("span",{className:"text-2xl",children:"🦊"})}),y.jsx("p",{className:""+(O?"text-gray-300":"text-gray-600"),children:"Connect MetaMask to continue"}),y.jsx("button",{onClick:async()=>{try{E(!0),M("");const e=await W.connect();$(!0),console.log("✅ Wallet connected successfully:",e.account)}catch(e){console.error("Wallet connection failed:",e),M(e.message)}finally{E(!1)}},disabled:T,className:"w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 disabled:opacity-50 font-medium",children:T?"Connecting...":"Connect MetaMask"})]})]}),"qr"===h&&y.jsxs("div",{className:"text-center space-y-4",children:[y.jsx("h3",{className:"font-medium",children:"Scan QR Code"}),y.jsxs("div",{className:"p-8 rounded-lg "+(O?"bg-gray-800":"bg-gray-100"),children:[y.jsx("p",{className:""+(O?"text-gray-400":"text-gray-500"),children:"QR Code will appear here"}),y.jsxs("p",{className:"text-xs mt-2",children:["Send ",null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]}),y.jsx("p",{className:"text-xs",children:"to merchant wallet"})]}),y.jsx("p",{className:"text-xs "+(O?"text-gray-400":"text-gray-500"),children:"Waiting for payment confirmation..."})]}),"success"===h&&y.jsxs("div",{className:"text-center space-y-4",children:[y.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx("span",{className:"text-2xl",children:"✅"})}),y.jsx("h3",{className:"font-medium text-green-600",children:"Payment Successful!"}),y.jsx("p",{className:"text-sm "+(O?"text-gray-300":"text-gray-600"),children:"Your transaction has been sent successfully"}),y.jsx("button",{onClick:l,className:"w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 font-medium",children:"Close"})]}),T&&"wallet"!==h&&y.jsx("div",{className:"flex items-center justify-center py-8",children:y.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"})})]})]})})},e.SimpleCoinleyProvider=({children:e,...t})=>e,e.ThemeProvider=({initialTheme:e="light",children:s})=>{const[a,r]=t.useState(e);return t.useEffect(()=>{document.documentElement.setAttribute("data-coinley-theme",a)},[a]),y.jsx("div",{className:`coinley-theme-${a}`,children:s})},e.VERSION="0.0.1",e.useCoinley=()=>{const e=t.useContext(b);if(!e)throw new Error("useCoinley must be used within a CoinleyProvider");return e},e.utils=N,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("framer-motion"),require("lucide-react"),require("@coinley/wallet-connect-core"),require("axios")):"function"==typeof define&&define.amd?define(["exports","react","framer-motion","lucide-react","@coinley/wallet-connect-core","axios"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CoinleyTest={},e.React,e.FramerMotion,e.LucideReact,e.CoinleyWalletCore,e.axios)}(this,function(e,t,a,s,r,n){"use strict";var o={exports:{}},l={},c=t,i=Symbol.for("react.element"),d=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,h=c.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function x(e,t,a){var s,r={},n=null,o=null;for(s in void 0!==a&&(n=""+a),void 0!==t.key&&(n=""+t.key),void 0!==t.ref&&(o=t.ref),t)m.call(t,s)&&!u.hasOwnProperty(s)&&(r[s]=t[s]);if(e&&e.defaultProps)for(s in t=e.defaultProps)void 0===r[s]&&(r[s]=t[s]);return{$$typeof:i,type:e,key:n,ref:o,props:r,_owner:h.current}}l.Fragment=d,l.jsx=x,l.jsxs=x,o.exports=l;var y=o.exports;class p{constructor(e,t,a){this.apiKey=t,this.apiSecret=a,this.api=n.create({baseURL:e.endsWith("/")?e.slice(0,-1):e,timeout:3e4,headers:{"Content-Type":"application/json"}}),this.api.interceptors.request.use(e=>{var t;e.headers["X-API-Key"]=this.apiKey,e.headers["X-API-Secret"]=this.apiSecret;const a=this.generateMerchantToken();return a&&(e.headers.Authorization=`Bearer ${a}`),console.log("API Request:",{method:null==(t=e.method)?void 0:t.toUpperCase(),url:e.url,data:e.data}),e},e=>(console.error("Request interceptor error:",e),Promise.reject(e))),this.api.interceptors.response.use(e=>(console.log("API Response:",{status:e.status,url:e.config.url,data:e.data}),e),e=>{var t,a,s,r,n;if(console.error("API Error:",{status:null==(t=e.response)?void 0:t.status,data:null==(a=e.response)?void 0:a.data,message:e.message}),401===(null==(s=e.response)?void 0:s.status))throw new Error("Authentication failed. Please check your API credentials.");if(404===(null==(r=e.response)?void 0:r.status))throw new Error("API endpoint not found. Please check your API URL.");if((null==(n=e.response)?void 0:n.status)>=500)throw new Error("Server error. Please try again later.");throw e})}generateMerchantToken(){try{const e=`${this.apiKey}:${this.apiSecret}`;return btoa(e)}catch(e){return console.error("Failed to generate token:",e),null}}async createPayment(e){var t,a;try{return(await this.api.post("/api/payments/create",e)).data}catch(s){if(null==(a=null==(t=s.response)?void 0:t.data)?void 0:a.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to create payment")}}async getPayment(e){var t,a;try{return(await this.api.get(`/api/payments/${e}`)).data}catch(s){if(null==(a=null==(t=s.response)?void 0:t.data)?void 0:a.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to get payment details")}}async getNetworks(){try{return(await this.api.get("/api/networks")).data}catch(e){return console.error("Get networks failed:",e),{networks:[{id:"ethereum",name:"Ethereum",shortName:"ethereum",chainId:"1",type:"ethereum",explorerUrl:"https://etherscan.io",isTestnet:!1},{id:"bsc",name:"Binance Smart Chain",shortName:"bsc",chainId:"56",type:"bsc",explorerUrl:"https://bscscan.com",isTestnet:!1},{id:"polygon",name:"Polygon",shortName:"polygon",chainId:"137",type:"ethereum",explorerUrl:"https://polygonscan.com",isTestnet:!1}]}}}async getStablecoins(){try{return(await this.api.get("/api/networks/stablecoins")).data}catch(e){return console.error("Get stablecoins failed:",e),{stablecoins:[{id:"usdt-eth",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}},{id:"usdc-eth",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E6441d81d0B93bF9EE0f74ca32F7e6f6",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}}]}}}async verifyQRPayment(e){var t,a;try{return(await this.api.post("/api/payments/verify-qr",{paymentId:e})).data}catch(s){if(null==(a=null==(t=s.response)?void 0:t.data)?void 0:a.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to verify payment")}}async processPayment(e,t,a,s){var r,n;try{return(await this.api.post("/api/payments/process",{paymentId:e,transactionHash:t,network:a,senderAddress:s})).data}catch(o){if(null==(n=null==(r=o.response)?void 0:r.data)?void 0:n.error)throw new Error(o.response.data.error);throw new Error(o.message||"Failed to process payment")}}async healthCheck(){try{return 200===(await this.api.get("/api/health")).status}catch(e){return console.error("Health check failed:",e),!1}}}const g=({selectedNetwork:e,selectedToken:t,paymentData:a,config:n,onTransactionSent:o,onError:l,isConnecting:c,setIsConnecting:i})=>{const{isConnected:d,address:m,disconnect:h}=r.useWallet(),{connectWallet:u,isPending:x}=r.useWalletConnect(),{detectedWallets:p,hasWallets:g,walletCount:f}=r.useWalletDetection(),{sendTransaction:w}=r.useWalletTransaction(),{openModal:b}=r.useWalletModal();p.filter(e=>e.name.toLowerCase().includes("metamask")||"injected"===e.provider||e.name.toLowerCase().includes("coinbase")||e.name.toLowerCase().includes("wallet connect"));const v=async e=>{try{if(i(!0),d&&(await h(),await new Promise(e=>setTimeout(e,1e3))),"metamask"===e&&window.ethereum&&window.ethereum.isMetaMask)try{await window.ethereum.request({method:"eth_requestAccounts"}),console.log("✅ Connected directly to MetaMask")}catch(t){throw console.error("MetaMask connection failed:",t),t}else await u(e)}catch(t){console.error("Wallet connection failed:",t),l(t.message||"Failed to connect wallet")}finally{i(!1)}};return y.jsx("div",{className:"text-center space-y-6",children:y.jsxs("div",{className:"space-y-4",children:[y.jsx("div",{className:"w-16 h-16 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center mx-auto",children:y.jsx(s.Wallet,{className:"w-8 h-8 text-[#7042D2]"})}),d?y.jsxs(y.Fragment,{children:[y.jsx("h3",{className:"text-lg font-semibold text-green-600",children:"Wallet Connected ✅"}),y.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-3",children:[y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Address:"}),y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsxs("span",{className:"font-mono text-sm",children:[null==m?void 0:m.slice(0,6),"...",null==m?void 0:m.slice(-4)]}),y.jsx("button",{onClick:async()=>{try{await h()}catch(e){console.error("Disconnect error:",e)}},className:"text-xs text-red-600 hover:text-red-800",children:"Disconnect"})]})]}),a&&y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Amount:"}),y.jsxs("span",{className:"font-medium",children:[a.totalAmount," ",null==t?void 0:t.symbol]})]}),y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Network:"}),y.jsx("span",{className:"font-medium",children:null==e?void 0:e.name})]})]})]}),y.jsx("button",{onClick:async()=>{var s;if(d&&a&&t)try{i(!0),console.log("🔍 Transaction Debug:"),console.log("Connected wallet address:",m),console.log("Payment data:",a),console.log("Selected token:",t),console.log("Selected network:",e);let r,n=null==(s=a.metadata)?void 0:s.recipientWallet;if(console.log("Merchant recipient address:",n),!n||"string"!=typeof n)throw new Error("Merchant wallet address not found in payment data");if(!n.match(/^0x[a-fA-F0-9]{40}$/))throw new Error(`Invalid merchant address format: ${n}`);if(t.contractAddress){console.log("🔍 ERC-20 Transaction Details:"),console.log("Token contract:",t.contractAddress),console.log("Token decimals:",t.decimals),console.log("Payment amount:",a.totalAmount);const e=t.decimals||6,s=Math.floor(a.totalAmount*Math.pow(10,e));console.log("Calculated amount (with decimals):",s);const o="0xa9059cbb",l=n.slice(2).toLowerCase().padStart(64,"0"),c=s.toString(16).padStart(64,"0"),i=`${o}${l}${c}`;console.log("🔍 Transaction Data:"),console.log("Method ID:",o),console.log("Recipient (padded):",l),console.log("Amount (padded):",c),console.log("Full data:",i);const d={to:t.contractAddress,data:i,value:"0x0"};console.log("📤 Sending ERC-20 transaction:",d),r=await w(d)}else{const e=Math.floor(a.totalAmount*Math.pow(10,18)),t={to:n,value:`0x${e.toString(16)}`};console.log("📤 Sending native transaction:",t),r=await w(t)}r&&(console.log("✅ Transaction sent successfully:",r),o(r))}catch(r){console.error("❌ Transaction failed:",r),l(r.message||"Transaction failed")}finally{i(!1)}else l("Wallet not connected or payment data missing")},disabled:c,className:"w-full bg-[#7042D2] text-white py-4 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center space-x-2",children:c?y.jsxs(y.Fragment,{children:[y.jsx(s.Loader2,{className:"w-5 h-5 animate-spin"}),y.jsx("span",{children:"Processing Payment..."})]}):y.jsxs(y.Fragment,{children:[y.jsx(s.Zap,{className:"w-5 h-5"}),y.jsx("span",{children:"Send Payment"})]})}),y.jsxs("p",{className:"text-xs text-gray-500",children:["Make sure you have enough ",null==t?void 0:t.symbol," and ETH for gas fees"]})]}):y.jsxs(y.Fragment,{children:[y.jsx("h3",{className:"text-lg font-semibold",children:"Connect Your Wallet"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 text-sm",children:"Choose your preferred wallet to complete the payment"}),y.jsxs("div",{className:"space-y-3",children:[y.jsxs("button",{onClick:()=>v("metamask"),disabled:x||c,className:"w-full p-3 border border-gray-300 rounded-lg hover:border-[#7042D2] flex items-center space-x-3 transition-colors disabled:opacity-50",children:[y.jsx("span",{className:"text-xl",children:"🦊"}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-medium",children:"MetaMask"}),y.jsx("div",{className:"text-xs text-gray-500",children:"Connect with MetaMask"})]})]}),y.jsxs("button",{onClick:()=>{try{console.log("Attempting to open wallet modal..."),b()}catch(e){console.error("Failed to open modal:",e),v("injected")}},disabled:x||c,className:"w-full p-3 border border-gray-300 rounded-lg hover:border-[#7042D2] flex items-center space-x-3 transition-colors disabled:opacity-50",children:[y.jsx("span",{className:"text-xl",children:"💼"}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-medium",children:"Other Wallets"}),y.jsx("div",{className:"text-xs text-gray-500",children:"Choose from available wallets"})]})]}),y.jsx("button",{onClick:()=>v("injected"),disabled:x||c,className:"w-full p-2 text-sm border border-dashed border-gray-300 rounded-lg hover:border-[#7042D2] transition-colors disabled:opacity-50",children:"Try Direct Connection"})]}),c&&y.jsxs("div",{className:"flex items-center justify-center space-x-2 text-gray-600",children:[y.jsx(s.Loader2,{className:"w-4 h-4 animate-spin"}),y.jsx("span",{children:"Connecting..."})]})]})]})})},f=({apiKey:e,apiSecret:n,apiUrl:o="http://localhost:9000",onSuccess:l,onError:c,onClose:i,isOpen:d,config:m,theme:h="light",merchantName:u,debug:x=!1})=>{const[f,w]=t.useState("select-method"),[b,v]=t.useState([]),[j,N]=t.useState([]),[k,C]=t.useState(null),[S,T]=t.useState(null),[E,A]=t.useState(null),[P,M]=t.useState(""),[D,I]=t.useState(null),[$,W]=t.useState(!1),[F,U]=t.useState(""),[R,q]=t.useState(!1),[L,_]=t.useState(""),[H,O]=t.useState(!1),B=t.useRef(new p(o,e,n)),K=r.createCoinleyWalletConfig({appName:u||"Coinley Payment",appDescription:"Crypto payment processing",chains:[{id:1,name:"Ethereum",network:"ethereum",rpcUrls:{default:{http:["https://eth.llamarpc.com"]}},nativeCurrency:{name:"Ethereum",symbol:"ETH",decimals:18}},{id:56,name:"BNB Smart Chain",network:"bsc",rpcUrls:{default:{http:["https://bsc-dataseed1.binance.org"]}},nativeCurrency:{name:"BNB",symbol:"BNB",decimals:18}}]});t.useEffect(()=>{d&&Q()},[d]);const Q=async()=>{try{W(!0),U("");const[e,t]=await Promise.all([B.current.getNetworks(),B.current.getStablecoins()]);v(e.networks||[]),N(t.stablecoins||[]),x&&(console.log("Initialized networks:",e.networks),console.log("Initialized tokens:",t.stablecoins))}catch(e){console.error("Failed to initialize payment:",e),U("Failed to load payment options. Please try again.")}finally{W(!1)}},z=e=>{A(e),w("select-network")},G=async(e,t)=>{try{W(!0);const a={amount:m.amount,currency:t.symbol,network:e.shortName,customerEmail:m.customerEmail,callbackUrl:m.callbackUrl,metadata:{...m.metadata,paymentMethod:E,selectedNetwork:e.shortName,selectedToken:t.symbol,merchantWalletAddresses:m.merchantWalletAddresses}};console.log("🔍 Payment payload with merchant wallets:",a);const s=await B.current.createPayment(a);I(s.payment),"wallet"===E?w("wallet-connect"):(await Y(s.payment),w("qr-code"))}catch(a){console.error("Payment initiation failed:",a),U(a.message||"Failed to create payment"),w("error")}finally{W(!1)}},Y=async e=>{var t,a;try{const s=(null==(t=e.metadata)?void 0:t.recipientWallet)||(null==(a=m.merchantWalletAddresses)?void 0:a[(null==k?void 0:k.shortName)||""]);if(!s)throw new Error("Recipient wallet address not found");let r="";r="ethereum"===(null==k?void 0:k.type)||"bsc"===(null==k?void 0:k.type)?(null==S?void 0:S.contractAddress)?`ethereum:${S.contractAddress}/transfer?address=${s}&uint256=${e.totalAmount*Math.pow(10,S.decimals)}`:`ethereum:${s}?value=${e.totalAmount}e18`:"tron"===(null==k?void 0:k.type)?`tron:${s}?amount=${e.totalAmount}`:`${null==S?void 0:S.symbol}:${s}?amount=${e.totalAmount}`,M(s),X(e.id)}catch(s){console.error("QR code generation failed:",s),U("Failed to generate QR code"),w("error")}},X=async e=>{let t=0;const a=async()=>{var s;try{const r=await B.current.verifyQRPayment(e);return r.verified&&(null==(s=r.payment)?void 0:s.transactionHash)?(_(r.payment.transactionHash),await Z(e,r.payment.transactionHash),!0):(t++,t<60?setTimeout(a,5e3):(U("Payment verification timeout. Please check your transaction."),w("error")),!1)}catch(r){return console.error("Payment verification error:",r),t++,t<60?setTimeout(a,5e3):(U("Payment verification failed"),w("error")),!1}};setTimeout(a,2e3)},Z=async(e,t)=>{w("success"),l&&l(e,t,{network:null==k?void 0:k.name,token:null==S?void 0:S.symbol,amount:null==D?void 0:D.totalAmount,method:E})},V=()=>{w("select-method"),A(null),C(null),T(null),M(""),I(null),U(""),_(""),i&&i()};return d?y.jsxs(r.CoinleyWalletProvider,{config:K,walletConfig:{appName:u||"Coinley Payment"},children:[y.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm",children:y.jsxs(a.motion.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.9,opacity:0},className:"relative w-full max-w-md mx-4 rounded-2xl shadow-2xl overflow-hidden "+("dark"===h?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[y.jsxs("div",{className:"relative p-6 border-b border-gray-200 dark:border-gray-700",children:["select-method"!==f&&"success"!==f&&"error"!==f&&y.jsx("button",{onClick:()=>{if("select-network"===f)w("select-method");else if("select-token"===f)w("select-network");else if("wallet-connect"===f||"qr-code"===f){j.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==k?void 0:k.shortName)||e.networkId===(null==k?void 0:k.id)}).length>1?w("select-token"):w("select-network")}},className:"absolute left-4 top-6 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors",children:y.jsx(s.ArrowLeft,{className:"w-5 h-5"})}),y.jsx("button",{onClick:V,className:"absolute right-4 top-6 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors",children:y.jsx(s.X,{className:"w-5 h-5"})}),y.jsxs("div",{className:"text-center",children:[y.jsxs("div",{className:"flex items-center justify-center space-x-2 mb-2",children:[y.jsx(s.Sparkles,{className:"w-5 h-5 text-[#7042D2]"}),y.jsx("h2",{className:"text-xl font-bold",children:"Pay with Crypto"}),y.jsx(s.Sparkles,{className:"w-5 h-5 text-[#7042D2]"})]}),u&&y.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:u}),y.jsx("div",{className:"mt-2",children:y.jsxs("span",{className:"text-2xl font-bold text-[#7042D2]",children:["$",m.amount.toFixed(2)]})})]})]}),y.jsx("div",{className:"p-6 min-h-[400px]",children:y.jsxs(a.AnimatePresence,{mode:"wait",children:["select-method"===f&&y.jsxs(a.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[y.jsx("h3",{className:"text-lg font-semibold text-center mb-6",children:"Choose Payment Method"}),y.jsx(a.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>z("wallet"),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[y.jsx("div",{className:"p-3 bg-[#7042D2] bg-opacity-10 rounded-lg group-hover:bg-opacity-20 transition-colors",children:y.jsx(s.Wallet,{className:"w-6 h-6 text-[#7042D2]"})}),y.jsxs("div",{className:"text-left",children:[y.jsx("div",{className:"font-semibold",children:"Connect Wallet"}),y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:"MetaMask, WalletConnect & more"})]}),y.jsx(s.Zap,{className:"w-5 h-5 text-[#7042D2] ml-auto"})]})}),y.jsx(a.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>z("qr"),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[y.jsx("div",{className:"p-3 bg-[#7042D2] bg-opacity-10 rounded-lg group-hover:bg-opacity-20 transition-colors",children:y.jsx(s.QrCode,{className:"w-6 h-6 text-[#7042D2]"})}),y.jsxs("div",{className:"text-left",children:[y.jsx("div",{className:"font-semibold",children:"QR Code"}),y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Scan with mobile wallet"})]})]})})]},"select-method"),"select-network"===f&&y.jsxs(a.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[y.jsx("h3",{className:"text-lg font-semibold text-center mb-6",children:"Select Network"}),$?y.jsx("div",{className:"flex justify-center py-8",children:y.jsx(s.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}):y.jsx("div",{className:"space-y-3",children:b.map(e=>y.jsx(a.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>(async e=>{C(e);const t=j.filter(t=>{var a;return(null==(a=t.Network)?void 0:a.shortName)===e.shortName||t.networkId===e.id});if(t.length>1)w("select-token");else if(1===t.length){const a=t[0];T(a),await G(e,a)}else U(`No supported tokens found for ${e.name}`),w("error")})(e),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[e.logo?y.jsx("img",{src:e.logo,alt:e.name,className:"w-8 h-8 rounded-full"}):y.jsx("div",{className:"w-8 h-8 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center",children:y.jsx("span",{className:"text-sm font-bold text-[#7042D2]",children:e.shortName.charAt(0).toUpperCase()})}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-semibold",children:e.name}),y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:e.shortName.toUpperCase()})]}),y.jsx(s.ChevronDown,{className:"w-5 h-5 text-gray-400 transform -rotate-90"})]})},e.id))})]},"select-network"),"select-token"===f&&y.jsxs(a.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[y.jsxs("h3",{className:"text-lg font-semibold text-center mb-6",children:["Select Token on ",null==k?void 0:k.name]}),$?y.jsx("div",{className:"flex justify-center py-8",children:y.jsx(s.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}):y.jsx("div",{className:"space-y-3",children:j.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==k?void 0:k.shortName)||e.networkId===(null==k?void 0:k.id)}).map(e=>y.jsx(a.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>(async e=>{T(e),await G(k,e)})(e),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[e.logo?y.jsx("img",{src:e.logo,alt:e.symbol,className:"w-8 h-8 rounded-full"}):y.jsx("div",{className:"w-8 h-8 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center",children:y.jsx("span",{className:"text-sm font-bold text-[#7042D2]",children:e.symbol.charAt(0)})}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-semibold",children:e.name}),y.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:[e.symbol,e.isStablecoin&&y.jsx("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-600 text-xs rounded-full",children:"Stablecoin"})]})]}),y.jsx(s.ChevronDown,{className:"w-5 h-5 text-gray-400 transform -rotate-90"})]})},e.id))})]},"select-token"),"wallet-connect"===f&&y.jsx(a.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},children:y.jsx(g,{selectedNetwork:k,selectedToken:S,paymentData:D,config:m,onTransactionSent:async e=>{_(e),w("processing");try{await B.current.processPayment(D.id,e,(null==k?void 0:k.shortName)||"",""),await Z(D.id,e)}catch(t){console.error("Payment processing failed:",t),await Z(D.id,e)}},onError:U,isConnecting:H,setIsConnecting:O})},"wallet-connect"),"qr-code"===f&&y.jsxs(a.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"text-center space-y-6",children:[y.jsxs("div",{className:"space-y-4",children:[y.jsx("h3",{className:"text-lg font-semibold",children:"Scan QR Code"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Use your mobile wallet to scan and pay"})]}),P&&y.jsx("div",{className:"bg-white p-4 rounded-xl mx-auto inline-block",children:y.jsxs("div",{className:"w-48 h-48 flex items-center justify-center text-gray-500",children:["QR Code: ",P.slice(0,10),"...",P.slice(-4)]})}),D&&y.jsxs("div",{className:"space-y-3",children:[y.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-2",children:[y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Network:"}),y.jsx("span",{className:"font-medium",children:null==k?void 0:k.name})]}),y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Amount:"}),y.jsxs("span",{className:"font-medium",children:[D.totalAmount," ",null==S?void 0:S.symbol]})]})]}),y.jsxs("div",{className:"flex items-center justify-center space-x-2 text-sm text-gray-600 dark:text-gray-400",children:[y.jsx(s.Loader2,{className:"w-4 h-4 animate-spin"}),y.jsx("span",{children:"Waiting for payment..."})]})]})]},"qr-code"),"processing"===f&&y.jsxs(a.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[y.jsx("div",{className:"w-16 h-16 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center mx-auto",children:y.jsx(s.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}),y.jsxs("div",{children:[y.jsx("h3",{className:"text-lg font-semibold text-[#7042D2]",children:"Processing Payment..."}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:"Your transaction is being processed"})]})]},"processing"),"success"===f&&y.jsxs(a.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[y.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx(s.CheckCircle2,{className:"w-8 h-8 text-green-500"})}),y.jsxs("div",{children:[y.jsx("h3",{className:"text-lg font-semibold text-green-600",children:"Payment Successful!"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:"Your payment has been processed successfully"})]}),L&&y.jsx("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4",children:y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Transaction:"}),y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsxs("span",{className:"font-mono text-sm",children:[L.slice(0,6),"...",L.slice(-4)]}),y.jsx("button",{onClick:()=>(async e=>{try{await navigator.clipboard.writeText(e),q(!0),setTimeout(()=>q(!1),2e3)}catch(t){console.error("Failed to copy:",t)}})(L),className:"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded",children:y.jsx(s.Copy,{className:"w-4 h-4"})}),(null==k?void 0:k.explorerUrl)&&y.jsx("a",{href:`${k.explorerUrl}/tx/${L}`,target:"_blank",rel:"noopener noreferrer",className:"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded",children:y.jsx(s.ExternalLink,{className:"w-4 h-4"})})]})]})}),y.jsx("button",{onClick:V,className:"w-full bg-[#7042D2] text-white py-3 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors",children:"Close"})]},"success"),"error"===f&&y.jsxs(a.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[y.jsx("div",{className:"w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx(s.AlertCircle,{className:"w-8 h-8 text-red-500"})}),y.jsxs("div",{children:[y.jsx("h3",{className:"text-lg font-semibold text-red-600",children:"Payment Failed"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:F||"Something went wrong. Please try again."})]}),y.jsxs("div",{className:"space-y-3",children:[y.jsx("button",{onClick:()=>{w("select-method"),U("")},className:"w-full bg-[#7042D2] text-white py-3 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors",children:"Try Again"}),y.jsx("button",{onClick:V,className:"w-full border border-gray-300 dark:border-gray-600 py-3 rounded-lg font-semibold hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Close"})]})]},"error")]})}),y.jsx("div",{className:"px-6 py-4 border-t border-gray-200 dark:border-gray-700 text-center",children:y.jsxs("p",{className:"text-xs text-gray-500",children:["Powered by ",y.jsx("span",{className:"font-semibold text-[#7042D2]",children:"Coinley"})]})})]})}),y.jsx(r.WalletModal,{})]}):null},w=t.createContext(null),b=t.forwardRef(({customerEmail:e="",merchantName:a="",onSuccess:s,onError:r,onClose:n,theme:o="light",autoOpen:l=!1,testMode:c=!1,debug:i=!1,merchantWalletAddresses:d={}},m)=>{const h=t.useContext(w);if(!h)throw new Error("CoinleyCheckout must be used within a CoinleyProvider");const{openPayment:u,closePayment:x}=h,y=t=>{try{if(i&&console.log("Opening Coinley checkout with config:",t),!t.amount||t.amount<=0)throw new Error("Amount must be greater than 0");const a={...t,customerEmail:t.customerEmail||e,merchantWalletAddresses:{...d,...t.merchantWalletAddresses},metadata:{...t.metadata,testMode:c,checkoutVersion:"1.0.0"}};u(a,{onSuccess:s,onError:r,onClose:n})}catch(a){console.error("Failed to open Coinley checkout:",a),r&&r(a)}},p=()=>{x()};return t.useImperativeHandle(m,()=>({open:y,close:p})),null});b.displayName="CoinleyCheckout";class v{constructor(e,t,a){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,this.apiKey=t,this.apiSecret=a}async request(e,t={}){const a=`${this.baseURL}${e}`,s={"Content-Type":"application/json","X-API-Key":this.apiKey,"X-API-Secret":this.apiSecret,...t.headers},r=await fetch(a,{...t,headers:s});if(!r.ok){const e=await r.json().catch(()=>({}));throw new Error(e.error||`HTTP ${r.status}`)}return r.json()}async getNetworks(){try{return await this.request("/api/networks")}catch(e){return console.error("Failed to fetch networks:",e),{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(e){return console.error("Failed to fetch tokens:",e),{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}}class j{constructor(){this.account=null,this.chainId=null}async connect(){if(!window.ethereum)throw new Error("MetaMask not installed. Please install MetaMask extension.");if(window.ethereum.providers){console.log("🔍 Multiple wallets detected:",window.ethereum.providers.length);const e=window.ethereum.providers.find(e=>e.isMetaMask);if(!e)throw new Error("MetaMask not found among installed wallets");console.log("🦊 Using MetaMask provider specifically"),window.ethereum=e}else if(!window.ethereum.isMetaMask)throw new Error("Please use MetaMask wallet");try{console.log("🦊 Requesting MetaMask account access...");const e=await window.ethereum.request({method:"eth_requestAccounts"});if(!e||0===e.length)throw new Error("No accounts found in MetaMask");const t=await window.ethereum.request({method:"eth_chainId"});if(this.account=e[0],this.chainId=t,console.log("✅ MetaMask connected successfully:"),console.log(" Account:",this.account),console.log(" Chain ID:",this.chainId),"0xa0419a048a1469b34a5245f08c0697ba956a56ab"!==this.account.toLowerCase())throw console.warn("⚠️ Connected to different account than expected"),console.warn(" Expected: 0xa0419a048A1469B34a5245f08C0697Ba956a56Ab"),console.warn(" Connected:",this.account),new Error(`Please switch MetaMask to account 0xa041...56Ab. Currently connected to ${this.account.slice(0,6)}...${this.account.slice(-4)}`);return{account:this.account,chainId:this.chainId}}catch(e){throw console.error("MetaMask connection failed:",e),new Error(e.message||"Failed to connect to MetaMask")}}async sendTransaction(e){if(!this.account)throw new Error("Wallet not connected");try{if(console.log("🦊 Sending MetaMask transaction:",e),!window.ethereum.isMetaMask)throw new Error("Not using MetaMask provider");if(e.data&&e.data.includes("a9059cbb")){console.log("🔍 Checking USDT balance...");try{const t=await window.ethereum.request({method:"eth_call",params:[{to:e.to,data:`0x70a08231000000000000000000000000${this.account.slice(2)}`},"latest"]}),a=parseInt(t,16),s=a/1e6;console.log("💰 USDT Balance:",s);const r=e.data.slice(-64),n=parseInt(r,16),o=n/1e6;if(console.log("💸 Transaction Amount:",o),a<n)throw new Error(`Insufficient USDT balance. You have ${s} USDT but need ${o} USDT`)}catch(t){console.warn("Could not check balance:",t)}}try{const e=await window.ethereum.request({method:"eth_getBalance",params:[this.account,"latest"]}),t=parseInt(e,16)/Math.pow(10,18);if(console.log("⛽ ETH Balance for gas:",t),t<.001)throw new Error(`Insufficient ETH for gas fees. You have ${t.toFixed(4)} ETH but need at least 0.001 ETH`)}catch(a){console.warn("Could not check ETH balance:",a)}const s={...e,from:this.account};try{const e=await window.ethereum.request({method:"eth_estimateGas",params:[s]}),t=Math.floor(1.2*parseInt(e,16));s.gas=`0x${t.toString(16)}`,console.log("⛽ Gas estimate:",parseInt(e,16)),console.log("⛽ Gas limit (with buffer):",t)}catch(a){console.warn("Gas estimation failed:",a),s.gas="0x15F90"}console.log("📤 Final transaction params:",s);const r=await window.ethereum.request({method:"eth_sendTransaction",params:[s]});return console.log("✅ Transaction sent successfully:",r),r}catch(s){throw console.error("Transaction failed:",s),4001===s.code?new Error("Transaction cancelled by user"):s.message.includes("insufficient funds")?new Error("Insufficient funds in wallet"):s.message.includes("gas")?new Error("Gas estimation failed. You may not have enough ETH for gas fees."):s.message.includes("invalid opcode")?new Error("Transaction failed - invalid operation. This usually means insufficient token balance or contract interaction failed."):new Error(s.message||"Transaction failed")}}isConnected(){return!!this.account}}const N={formatAmount:(e,t=2)=>e.toFixed(t),truncateAddress:(e,t=6,a=4)=>e?e.length<=t+a?e:`${e.slice(0,t)}...${e.slice(-a)}`:"",isValidAddress:(e,t)=>{if(!e)return!1;switch(t.toLowerCase()){case"ethereum":case"bsc":case"polygon":return/^0x[a-fA-F0-9]{40}$/.test(e);case"tron":return/^T[a-zA-Z0-9]{33}$/.test(e);case"solana":return/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e);default:return e.length>0}},copyToClipboard:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}};class k extends Error{constructor(e,t){super(e),this.name="CoinleyError",this.code=t}}e.CoinleyCheckout=b,e.CoinleyError=k,e.CoinleyPayment=f,e.CoinleyProvider=({apiKey:e,apiSecret:a,apiUrl:s,theme:r="light",debug:n=!1,children:o})=>{const[l,c]=t.useState(!1),[i,d]=t.useState(null),[m,h]=t.useState({}),[u,x]=t.useState(""),p=()=>{c(!1),d(null),m.onClose&&m.onClose()},g={openPayment:(e,t)=>{d(e),t&&h(t),c(!0)},closePayment:p};return y.jsxs(w.Provider,{value:g,children:[o,l&&i&&y.jsx(f,{apiKey:e,apiSecret:a,apiUrl:s,isOpen:l,config:i,theme:r,debug:n,merchantName:u,onSuccess:m.onSuccess,onError:m.onError,onClose:p})]})},e.DEFAULT_CONFIG={theme:"light",debug:!1,testMode:!1,autoOpen:!1},e.PaymentAPI=p,e.SimpleCoinleyPayment=({apiKey:e,apiSecret:a,apiUrl:s,config:r,onSuccess:n,onError:o,onClose:l,isOpen:c,theme:i="light"})=>{var d,m;const[h,u]=t.useState("method"),[x,p]=t.useState([]),[g,f]=t.useState([]),[w,b]=t.useState(null),[N,k]=t.useState(null),[C,S]=t.useState(null),[T,E]=t.useState(null),[A,P]=t.useState(!1),[M,D]=t.useState(""),[I,$]=t.useState(new j),[W,F]=t.useState(!1),[U,R]=t.useState(!1),q=t.useRef(new v(s,e,a));t.useEffect(()=>{c&&(_(),L())},[c]);const L=()=>{u("method"),b(null),k(null),S(null),E(null),D(""),F(!1),R(!1),$(new j)},_=async()=>{var e,t;try{P(!0),D(""),console.log("🔄 Loading networks and tokens...");const[a,s]=await Promise.all([q.current.getNetworks(),q.current.getTokens()]);p(a.networks||[]),f(s.stablecoins||[]),console.log("✅ Loaded networks:",null==(e=a.networks)?void 0:e.length),console.log("✅ Loaded tokens:",null==(t=s.stablecoins)?void 0:t.length)}catch(a){console.error("Failed to load data:",a),D("Failed to load payment options. Using fallback data.")}finally{P(!1)}};if(!c)return null;const H="dark"===i;return y.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:y.jsxs("div",{className:"rounded-lg shadow-xl max-w-md w-full mx-4 "+(H?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[y.jsxs("div",{className:"p-4 border-b flex justify-between items-center "+(H?"border-gray-700":"border-gray-200"),children:[y.jsxs("div",{className:"text-center flex-1",children:[y.jsx("h2",{className:"text-lg font-semibold",children:"Pay with Crypto"}),r.amount&&y.jsxs("p",{className:"text-2xl font-bold text-purple-600",children:["$",r.amount.toFixed(2)]})]}),y.jsx("button",{onClick:l,className:"ml-4 text-gray-500 hover:text-gray-700 "+(H?"hover:text-gray-300":""),children:"✕"})]}),y.jsxs("div",{className:"p-4 min-h-[400px]",children:[M&&y.jsxs("div",{className:"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200",children:[M,y.jsx("button",{onClick:()=>D(""),className:"ml-2 text-red-500 hover:text-red-700",children:"✕"})]}),"method"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsx("h3",{className:"font-medium text-center mb-6",children:"Choose Payment Method"}),y.jsxs("div",{className:"space-y-3",children:[y.jsxs("button",{onClick:()=>{S("wallet"),u("network")},className:"w-full p-4 border-2 rounded-lg hover:border-purple-500 text-left flex items-center space-x-3 transition-colors "+(H?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsx("span",{className:"text-2xl",children:"🦊"}),y.jsxs("div",{children:[y.jsx("div",{className:"font-medium",children:"MetaMask Wallet"}),y.jsx("div",{className:"text-sm "+(H?"text-gray-400":"text-gray-500"),children:"Connect and pay instantly"})]})]}),y.jsxs("button",{onClick:()=>{S("qr"),u("network")},className:"w-full p-4 border-2 rounded-lg hover:border-purple-500 text-left flex items-center space-x-3 transition-colors "+(H?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsx("span",{className:"text-2xl",children:"📱"}),y.jsxs("div",{children:[y.jsx("div",{className:"font-medium",children:"QR Code"}),y.jsx("div",{className:"text-sm "+(H?"text-gray-400":"text-gray-500"),children:"Scan with mobile wallet"})]})]})]})]}),"network"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsx("button",{onClick:()=>u("method"),className:""+(H?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),y.jsx("h3",{className:"font-medium",children:"Select Network"})]}),y.jsx("div",{className:"space-y-2",children:x.map(e=>y.jsxs("button",{onClick:()=>{b(e),u("token")},className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors "+(H?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsx("div",{className:"font-medium",children:e.name}),y.jsx("div",{className:"text-sm "+(H?"text-gray-400":"text-gray-500"),children:e.shortName.toUpperCase()})]},e.id))})]}),"token"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsx("button",{onClick:()=>u("network"),className:""+(H?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),y.jsxs("h3",{className:"font-medium",children:["Select Token on ",null==w?void 0:w.name]})]}),y.jsx("div",{className:"space-y-2",children:g.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==w?void 0:w.shortName)}).map(e=>y.jsxs("button",{onClick:()=>{k(e),(async()=>{try{P(!0),D("");const e={amount:r.amount,currency:N.symbol,network:w.shortName,customerEmail:r.customerEmail,callbackUrl:r.callbackUrl,metadata:{...r.metadata,merchantWalletAddresses:r.merchantWalletAddresses,paymentMethod:C,selectedNetwork:w.shortName,selectedToken:N.symbol}};console.log("🔄 Creating payment:",e);const t=await q.current.createPayment(e);E(t.payment),console.log("✅ Payment created:",t.payment.id),u("wallet"===C?"wallet":"qr")}catch(e){console.error("Payment creation failed:",e),D(e.message)}finally{P(!1)}})()},disabled:A,className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left flex justify-between transition-colors disabled:opacity-50 "+(H?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsxs("div",{children:[y.jsx("div",{className:"font-medium",children:e.name}),y.jsx("div",{className:"text-sm "+(H?"text-gray-400":"text-gray-500"),children:e.symbol})]}),e.isStablecoin&&y.jsx("span",{className:"px-2 py-1 bg-green-100 text-green-600 text-xs rounded",children:"Stablecoin"})]},e.id))})]}),"wallet"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsx("h3",{className:"font-medium text-center",children:"Connect & Pay"}),W?y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-200",children:[y.jsx("p",{className:"text-green-600 text-sm font-medium",children:"✅ Wallet Connected"}),y.jsxs("p",{className:"font-mono text-xs text-green-700 mt-1",children:[null==(d=I.account)?void 0:d.slice(0,6),"...",null==(m=I.account)?void 0:m.slice(-4)]})]}),y.jsxs("div",{className:"p-4 rounded-lg space-y-2 "+(H?"bg-gray-800":"bg-gray-50"),children:[y.jsxs("div",{className:"flex justify-between text-sm",children:[y.jsx("span",{children:"Amount:"}),y.jsxs("span",{className:"font-medium",children:[null==T?void 0:T.totalAmount," ",null==N?void 0:N.symbol]})]}),y.jsxs("div",{className:"flex justify-between text-sm",children:[y.jsx("span",{children:"Network:"}),y.jsx("span",{className:"font-medium",children:null==w?void 0:w.name})]}),y.jsxs("div",{className:"flex justify-between text-sm",children:[y.jsx("span",{children:"Token:"}),y.jsx("span",{className:"font-medium",children:null==N?void 0:N.name})]})]}),y.jsx("button",{onClick:async()=>{var e,t;try{R(!0),D("");const a=(null==(e=T.metadata)?void 0:e.recipientWallet)||(null==(t=r.merchantWalletAddresses)?void 0:t[w.shortName]);if(!a)throw new Error("Merchant wallet address not found");let s;if(console.log("🔄 Preparing transaction to:",a),N.contractAddress){const e=N.decimals||6,t=Math.floor(T.totalAmount*Math.pow(10,e)),r="0xa9059cbb",n=a.slice(2).toLowerCase().padStart(64,"0"),o=`${r}${n}${t.toString(16).padStart(64,"0")}`;s={to:N.contractAddress,data:o,value:"0x0"},console.log("🔄 ERC-20 Transaction:",{token:N.symbol,amount:T.totalAmount,amountWithDecimals:t,to:N.contractAddress,recipient:a})}else{s={to:a,value:`0x${Math.floor(T.totalAmount*Math.pow(10,18)).toString(16)}`},console.log("🔄 Native Transaction:",{amount:T.totalAmount,to:a})}const o=await I.sendTransaction(s);console.log("✅ Transaction successful:",o),u("success"),null==n||n(T.id,o,{network:w.name,token:N.symbol,amount:T.totalAmount,method:C})}catch(a){console.error("Transaction failed:",a),D(a.message)}finally{R(!1)}},disabled:U,className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium flex items-center justify-center space-x-2",children:U?y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-white"}),y.jsx("span",{children:"Sending Transaction..."})]}):y.jsxs("span",{children:["Send ",null==T?void 0:T.totalAmount," ",null==N?void 0:N.symbol]})})]}):y.jsxs("div",{className:"text-center space-y-4",children:[y.jsx("div",{className:"w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx("span",{className:"text-2xl",children:"🦊"})}),y.jsx("p",{className:""+(H?"text-gray-300":"text-gray-600"),children:"Connect MetaMask to continue"}),y.jsx("button",{onClick:async()=>{try{P(!0),D("");const e=await I.connect();F(!0),console.log("✅ Wallet connected successfully:",e.account)}catch(e){console.error("Wallet connection failed:",e),D(e.message)}finally{P(!1)}},disabled:A,className:"w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 disabled:opacity-50 font-medium",children:A?"Connecting...":"Connect MetaMask"})]})]}),"qr"===h&&y.jsxs("div",{className:"text-center space-y-4",children:[y.jsx("h3",{className:"font-medium",children:"Scan QR Code"}),y.jsxs("div",{className:"p-8 rounded-lg "+(H?"bg-gray-800":"bg-gray-100"),children:[y.jsx("p",{className:""+(H?"text-gray-400":"text-gray-500"),children:"QR Code will appear here"}),y.jsxs("p",{className:"text-xs mt-2",children:["Send ",null==T?void 0:T.totalAmount," ",null==N?void 0:N.symbol]}),y.jsx("p",{className:"text-xs",children:"to merchant wallet"})]}),y.jsx("p",{className:"text-xs "+(H?"text-gray-400":"text-gray-500"),children:"Waiting for payment confirmation..."})]}),"success"===h&&y.jsxs("div",{className:"text-center space-y-4",children:[y.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx("span",{className:"text-2xl",children:"✅"})}),y.jsx("h3",{className:"font-medium text-green-600",children:"Payment Successful!"}),y.jsx("p",{className:"text-sm "+(H?"text-gray-300":"text-gray-600"),children:"Your transaction has been sent successfully"}),y.jsx("button",{onClick:l,className:"w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 font-medium",children:"Close"})]}),A&&"wallet"!==h&&y.jsx("div",{className:"flex items-center justify-center py-8",children:y.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"})})]})]})})},e.SimpleCoinleyProvider=({children:e,...t})=>e,e.ThemeProvider=({initialTheme:e="light",children:a})=>{const[s,r]=t.useState(e);return t.useEffect(()=>{document.documentElement.setAttribute("data-coinley-theme",s)},[s]),y.jsx("div",{className:`coinley-theme-${s}`,children:a})},e.VERSION="0.0.1",e.useCoinley=()=>{const e=t.useContext(w);if(!e)throw new Error("useCoinley must be used within a CoinleyProvider");return e},e.utils=N,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=index.umd.js.map
|