coinley-test 0.36.102 → 0.37.102
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.umd.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("react"),require("wagmi"),require("@tanstack/react-query"),require("@wagmi/core"),require("@wagmi/core/chains"),require("@wagmi/connectors"),require("viem"),require("react-dom"),require("qrcode"),require("axios"),require("react-dom/client")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","react","wagmi","@tanstack/react-query","@wagmi/core","@wagmi/core/chains","@wagmi/connectors","viem","react-dom","qrcode","axios","react-dom/client"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CoinleyTest={},e.React,e.React,e.Wagmi,e.ReactQuery,e.WagmiCore,e.chains,e.connectors,e.Viem,e.ReactDOM,e.QRCode,e.axios,e.ReactDOM)}(this,function(e,t,n,s,a,r,o,i,c,l,d,m,u){"use strict";const h="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABxCAYAAAAj+QZ8AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAzrSURBVHgB7V3dcRs5Em4MtXWPq41gZ1+v7mwrgh3rArAUgagITNcFYDmAK9ERSBuBfQGsxY3Aku26V/MiOO7j1nqAQwMgRQ4xQONnhqOfr8q2TA4H1HzoRqO70c1g4JhUH/dhNKqgrhfT2cEMOoQaqxidyx+P5J8F8PpYjnkNPYLBgPGq+vxSFOJM/rhvXpp39ZAkGaUk40r+WK69jKT8JMdbQE8oYKDAByTJmMItGQj10OR7zyA3itFr2CQD1NhFMYYeMVhCHA8C1co7pV4yYXL4aSz/GVvfFFBBjxguIcCeOt4szYxOhiG2/V7M+T2yY7iEMOaTgIl8mBWkoth7Cduqah2u97JjuIQIUXqvYWlSohZyUEaDE/88/M+P0BMGrLIIYFAZ/R+HTGovJ+42IRqvYxZ485kKBob7QEgZZZoWoyMgrg//+vDX/0JPuA+ESLCXEApG/kxvm0LEkK2secDVZYjFpRZzIWibSyHm0COGSwjnYWoiyOIqjujXskcJUWCBqgItLuriPipOgAombqBH7EEGTKovUvz/xIdxnc8Rx8IdiHpxn7ouCVJXGnPIBD1h9p5BIU6kS6ZkBXt//uvf365fk0SIcvJJv5LUL6Wcdvq1w09z+c9MeknfSHLmEAteX8t7B30EBHsBHkLkPSsI+h482bOs3froERAT+UdLMcPlSch91M0P0w9Pz5bXpqksRcaW6Yj/H8v3vkpyLvRuOBzGxd6F2voZwpBEyKT6XMln8dF4BCzfjW2oz2hCjAu89FxmiPkctyNmMWprdOS5J11dSQsrVgXjxJAT8lyqp2aMpTnGxv1TJCRgdyzO5Jf7Giwtgv8GwWhfH5T0hK0fUQu6UeUf8UfvxY1Jl0LIHMJQBksL5zMIhXCqpLDAFpNrYSAwymnIKEkf4PUv6/+NJsQs2BHirKTlHUVaTAw9cB1xqaQijJDACYGTzUQ5adAqcbb+UuI+RPwCcTgyodjSe6UQ/4ZAtLrLi4DYhn5Y5DVscvjlguLK3xyDvWm+lEYI5+8hHiWJFMEvIRA1/3ZgfYMV9OgfYzPKZWrxfv5JLtx8DCFQhD+5bL6cRIgSN+IXb4GXlCi1VbQEt0IWdA40yRztXaG5DaEQ/Nj2crrrpP72BtJAkJRg1bhlAZr9Cc0y1LPXK/1KTYVZbcsB3rapw2RC1AwW0WvJEktS7A8sWDWyH61jkD/ul3q1xwhVUwj0HnN+1vZ2Huei4Ghvp/qwSumxfWd7I4NqRND3TdLt43rbmO7+PYYNgj93bTazEKIG4PUppELHyM+t76WrRhoEzFw+uMk/Ph0FW1O3N3/l8+9lc7/Lgd6jboR0TF5VNyeW++eQEj8EtKpf7SmGC4i78VvpRPTuUfLGQ1A3CpHkjEOIgk2ti3zXUtJiiq6gc38DXEar+15LMkgqLishSnWhOZce9tyX68mF5f4pUjL3XmHZqC1hVGkJocBnIdcN6uXZI4ZKR2obO22Rx/VE6esG6m+n/nsLW/jX/Rnp5GuTDpP7Fb6IGzJCPMadhHCVjc1rnBVppAg4b5rCinBeHzs/x7fd9uqhuNz59TfrPY3qDA8f3JIxD/lYZzH1TKRgztXEcu8ZWiztH6vtD17wlt23w/qxH1NwI5IMNRx0iDyk2POntMUiLDpftIeOOZ9ufxd5fYv1Y6RjDCFIIAPRywkq9YuxQvp8WAkxkKS2HWdT+VgFpvWw7zG24Dv2Jq8/kv6nl3rH7L4eQ9AQQojcw4BQJ7yiJ2AvhCAMKe+CQqgrKBs+bmecAIxyAlldKUk7g0R4s070ovpdadJ8DL6TM+DPoHizEeGDyeHNmZwHYYukiDA3E0HMGUAsD4fOIAP2LF/EnKtjGAqtQG2EOCzTfDT0/+UM0jFhte8QN+rnur526U+cRXIMuZ8oLgJUWG/nM9bg3wBqFXWalO7UwEplbeYORexGN+6qSLp26Wijws7ktf4sQvQvXT0hb65ywOw92twk0oSG0+mvfhd9KBQhLUeCc2EOjsQ5EjFc/vIul0YHUBOUFR8bUrxQ/jpprXV1VFoTcvgJ3d5H0D0uncRgEvSoeCGlqzIvL1xmaddYfScFft114QIEM9LxFfrFZXKq6T0FbgzT1os4YEbjR2lx9W7KDh3M1Pf4H+wKHVgqdxmFdpknx8TjgRkb1BytBwDtyxIq6N6J1UBEKd0Z7+ARmhDj0k53l6dAiGd6F/+wsfL2rjyzPR9y3ARhk3jPseF+V6RguHF3a0rZZxmLIaLV26uca9o7W0Kf4PUP0x4Lhg0NXve78ukI8boXYnbgsxoayPEQRQz6m27dGnmRGGm7LwgOUK38OwxO4oJNFjxuDldIihiazdwzGT+p1NkLnQlOdcUsVFY75+/7cNrdFWQP4Zq0nRI0MeiW2SSIq4yQxaM0POJOoCsJ0VJSjMqtC3g9x5j8dPa35Bzg+4hkQnSlAv7MxOCpiQGIOeQowXHPEEWIJkFgXZEx5ImnPAasDOj7kJxJEHagg/PgIe/SEbS8rGYlm26Aaw5meRzDA4ZTQizF8LvHA/dlWSVEp+aMLgTryE3iwKj4y/ew22DZTmHJXFQLNkbvdpH8ADX/43d4wNiIh7yqvpyY+k47IUPi8qEv6itCMP4hivC6IlnhOR/+EKAIMalAO04y8J/hfgjQEhJQdrsb7C5ddGjQi7oOPMFuICXjkYwVstTtjYKOEGJQarY6FKR8YsvSSgx37rOHpsZM9vvNNKqgfRxWKf2mqDCOW0G7ZTedfnjyCnYAU8zyRE6Mt31NDL2GpFWGo0IdLcA2dMCLmar8o01sXL9cZvaktSBN1xjt4bgTU4P4nFATOBnLzMWZ/YhxFqwRIc1q9FchEWFV2CZ9PIwtbJapnaiM/Rx9rxy4zVzUJ0hPM2UuGrVUP5fqRpXSZrB3Ysqnxh0M6rmfoML2uXZdaC22MDQBVueiOV+H8Y4K/Lv2hfkjg03YSYDPmuXrjMqZQBouJbnpNbkCoc612/Zo6oDrt+Pca4s/UW4zaWEdc/zLWexL9bHdu4qrS7gFJyE4VojbBR2o1IfpMHqyt4LtrHBABwdJrYTcdmhQ43iDXJbrvQ+05QDoGvLtpTqpddLNqV7xe8s46x0arMVqNrB1vf+w0KoOWGtYgJ3nWleyE2LUlK2NRRpsprmNdKHWvrbvZkvCsBZLa0JLkcsSxRLq6aTklxAsZ5RnzbiFpUa6+eXLrWtdSeGjkf29tmJpDZgKRI66kumkZCUkqXyqC42yfqZlats47VahcL5H2vipIjjOMoOq2UBkocyMhFD7ykahGSfRRcVaH177oR9nf13/+rMEVp9zF/scx5KST0K0Ps+PRh3dqKJiZLCXJCmhFfscx6ivLIS06vMcEFbp6Ar7VCkxxT49ZzLD15RkQjz6PA1aOmabY/mlo713LaV7KE1KEF2Qki4hHn2eBNEoX95Pu+39EL8ZlRRbtW4bkggxMzbOWeiFtZhl5f+YY7FVmfeUodkLCACFFFOt27sdSO1jWEEX0oH7jkb9QrNPKP0fdvaunQMFuh9iBQEgkLJP8QqkEcI6OOjfVprbsQPfgLt3Ldn5qI7pBSKAlNZJnEZI7h25uidvO/xJU428fdNmnI5zICEupL1GSpvqbO2Tgkjt9JlXXalSftsHQI36II7lXSeorvL92OjgihSA99YLVJ8Uu+XVU6dPAlx1FQty//OFNzbBxW9ARYTaWgKlUYYLjtsdkuLMRng8IUWLoy4UusL0gbPIJSt+Btq9CA87oPuzYLRxHdDGSUudep1EsYF4QqgmpAuqYICq3tD6kIL619JapdIJoXWf9kJ5iTHJo7nYW0pSpaislLDlQkXZrp74S2mMlGlNA6FVqmlb4b1uDVkMl7XFvlFpadMzkNILN/QX0xDq5O0BOeRJlY6QVqkhXaiLIgshCCRlevV0DJvZPUjGaow0sxe73VDThjQRz0lSsQ7q+hEyOYKaDjN6u1Yi5GJ/KScFtoc9bVqWGc6pOytTL1Lrmci4AlZM9etxDseU7pzB98WGXldPD6AnJCdbm9k+lsScgSpEY2qb6JomQR0Umghqlwr1DEKAXagpnoY+6oStIVv2uyFmDnlB1d/hR+GwCzUbUVw/+6E5XynotOVROogLKrWz8yZQgkkP2ZwM7gXDJoTSkJ7Y2bkJPeNpxT5r/sdP0BMGLiHMX6FUQHy7V+oxjFxeCcpQMGQwRljQ48+29NZfNwADlxAvLpOzz/vqQk3E3SYkw7n2oUnJsAkRwmEFiXzn/gYkJQOXEGFP51Eue07zhREwJCkZupVldxYWLH/VB1cXat5fdaJhE8JriwUl3nTRrk4T3Bbdq1NCDUEYNCFm87Z8SAtzUukMOoK94bHo7Yw6orMjbTmxDOD05U/SBz2l2wab3ncgjS78H0eagrHjdQciAAAAAElFTkSuQmCC",p="YWG990wOlIikc1tU7-WWTepfU8d1f4dp",y="qtIcCe_-8t4rIWktnWJm0",g=r.createConfig({chains:[o.mainnet,o.bsc,o.polygon,o.arbitrum,o.optimism,o.avalanche,o.celo,o.base],connectors:[i.injected(),i.metaMask({dappMetadata:{name:"Coinley Payment",icon:h}}),i.coinbaseWallet({appName:"Coinley Payment",appLogoUrl:h})],transports:{[o.mainnet.id]:r.fallback([r.http(`https://eth-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://eth-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://cloudflare-eth.com",{timeout:1e4,retryCount:1}),r.http("https://eth.llamarpc.com",{timeout:1e4,retryCount:1}),r.http("https://ethereum.publicnode.com",{timeout:1e4,retryCount:1})]),[o.bsc.id]:r.fallback([r.http(`https://bnb-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://bnb-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://bsc-dataseed.bnbchain.org",{timeout:1e4,retryCount:1}),r.http("https://bsc-dataseed-public.bnbchain.org",{timeout:1e4,retryCount:1}),r.http("https://bsc.nodereal.io",{timeout:1e4,retryCount:1})]),[o.polygon.id]:r.fallback([r.http(`https://polygon-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://polygon-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://polygon.llamarpc.com",{timeout:1e4,retryCount:1}),r.http("https://polygon-rpc.com",{timeout:1e4,retryCount:1}),r.http("https://polygon.drpc.org",{timeout:1e4,retryCount:1})]),[o.arbitrum.id]:r.fallback([r.http(`https://arb-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://arb-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://arb1.arbitrum.io/rpc",{timeout:1e4,retryCount:1}),r.http("https://arbitrum.llamarpc.com",{timeout:1e4,retryCount:1})]),[o.optimism.id]:r.fallback([r.http(`https://opt-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://opt-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://mainnet.optimism.io",{timeout:1e4,retryCount:1}),r.http("https://optimism.llamarpc.com",{timeout:1e4,retryCount:1})]),[o.avalanche.id]:r.fallback([r.http(`https://avax-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://avax-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://api.avax.network/ext/bc/C/rpc",{timeout:1e4,retryCount:1}),r.http("https://avalanche.public-rpc.com",{timeout:1e4,retryCount:1})]),[o.celo.id]:r.fallback([r.http(`https://celo-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://celo-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://forno.celo.org",{timeout:1e4,retryCount:1}),r.http("https://celo.drpc.org",{timeout:1e4,retryCount:1})]),[o.base.id]:r.fallback([r.http(`https://base-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://base-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://mainnet.base.org",{timeout:1e4,retryCount:1}),r.http("https://base.llamarpc.com",{timeout:1e4,retryCount:1}),r.http("https://base.meowrpc.com",{timeout:1e4,retryCount:1})])}});let f=class{constructor(e,t,n=null){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,t&&t.startsWith("pk_")?(this.publicKey=t,this.apiKey=null,this.apiSecret=null):(this.publicKey=null,this.apiKey=t,this.apiSecret=n)}async request(e,t={}){const n=`${this.baseURL}${e}`,s={"Content-Type":"application/json",...t.headers};this.publicKey?s["X-Public-Key"]=this.publicKey:(s["X-API-Key"]=this.apiKey,s["X-API-Secret"]=this.apiSecret);const a=t.timeout||6e4,r=new AbortController,o=setTimeout(()=>r.abort(),a);try{const e=await fetch(n,{...t,headers:s,signal:r.signal});if(clearTimeout(o),!e.ok){const t=await e.json().catch(()=>({}));throw new Error(t.error||`HTTP ${e.status}`)}return e.json()}catch(i){if(clearTimeout(o),"AbortError"===i.name)throw new Error(`Request timeout after ${a/1e3}s: ${e}`);throw i}}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"},{id:"137",name:"Polygon",shortName:"polygon",chainId:"0x89",type:"polygon"},{id:"42161",name:"Arbitrum",shortName:"arbitrum",chainId:"0xa4b1",type:"arbitrum"},{id:"10",name:"Optimism",shortName:"optimism",chainId:"0xa",type:"optimism"},{id:"43114",name:"Avalanche",shortName:"avalanche",chainId:"0xa86a",type:"avalanche"}]}}}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"}},{id:"2",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"3",name:"Tether USD",symbol:"USDT",contractAddress:"0x55d398326f99059fF775485246999027B3197955",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"4",name:"USD Coin",symbol:"USDC",contractAddress:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"5",name:"Tether USD",symbol:"USDT",contractAddress:"0xc2132D05D31c914a87c6611C10748AEb04B58e8F",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"6",name:"USD Coin",symbol:"USDC",contractAddress:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"7",name:"Tether USD",symbol:"USDT",contractAddress:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"8",name:"USD Coin",symbol:"USDC",contractAddress:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"9",name:"Tether USD",symbol:"USDT",contractAddress:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"10",name:"USD Coin",symbol:"USDC",contractAddress:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"11",name:"Tether USD",symbol:"USDT",contractAddress:"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"12",name:"USD Coin",symbol:"USDC",contractAddress:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"13",name:"Tether USD",symbol:"USDT",contractAddress:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"14",name:"USD Coin",symbol:"USDC",contractAddress:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"15",name:"Tether USD",symbol:"USDT",contractAddress:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}},{id:"16",name:"USD Coin",symbol:"USDC",contractAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}async verifyQRPayment(e){return await this.request("/api/payments/verify-qr",{method:"POST",body:JSON.stringify({paymentId:e})})}async checkPaymentStatus(e){return await this.request(`/api/payments/status/${e}`)}async getContractInfo(e){try{const t=await this.request(`/api/payments/contract/${e}`);if(!t.success)throw new Error("Contract not supported on this network");return t.contractInfo}catch(t){throw console.error("❌ Failed to get contract info:",t),new Error(t.message||"Failed to get contract information")}}async processPayment(e,t,n,s){try{return await this.request("/api/payments/process",{method:"POST",body:JSON.stringify({paymentId:e,transactionHash:t,network:n,senderAddress:s}),timeout:9e4})}catch(a){throw console.error("❌ [API] processPayment failed:",{error:a.message,name:a.name,stack:a.stack}),a}}async failPayment(e,t="Payment cancelled by user"){return await this.request("/api/payments/fail",{method:"POST",body:JSON.stringify({paymentId:e,reason:t,status:"failed"})})}};const b={ethereum:1,bsc:56,polygon:137,arbitrum:42161,optimism:10,avalanche:43114,celo:42220,base:8453},x=e=>"number"==typeof e?e:"string"==typeof e?e.startsWith("0x")?parseInt(e,16):parseInt(e,10):1,w=e=>b[e]||1;function v(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}const k="2.39.0";let N={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:n})=>t?`${e??"https://viem.sh"}${t}${n?`#${n}`:""}`:void 0,version:`viem@${k}`};class C extends Error{constructor(e,t={}){var n;const s=t.cause instanceof C?t.cause.details:(null==(a=t.cause)?void 0:a.message)?t.cause.message:t.details;var a;const r=t.cause instanceof C&&t.cause.docsPath||t.docsPath,o=null==(n=N.getDocsUrl)?void 0:n.call(N,{...t,docsPath:r});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...o?[`Docs: ${o}`]:[],...s?[`Details: ${s}`]:[],...N.version?[`Version: ${N.version}`]:[]].join("\n"),t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=k}walk(e){return P(this,e)}}function P(e,t){return(null==t?void 0:t(e))?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?P(e.cause,t):t?null:e}class j extends C{constructor({max:e,min:t,signed:n,size:s,value:a}){super(`Number "${a}" is not in safe ${s?`${8*s}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class I extends C{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function S(e,{strict:t=!0}={}){return!!e&&("string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")))}function A(e){return S(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function E(e,{dir:t="left"}={}){let n="string"==typeof e?e.replace("0x",""):e,s=0;for(let a=0;a<n.length-1&&"0"===n["left"===t?a:n.length-a-1].toString();a++)s++;return n="left"===t?n.slice(s):n.slice(0,n.length-s),"string"==typeof e?(1===n.length&&"right"===t&&(n=`${n}0`),`0x${n.length%2==1?`0${n}`:n}`):n}class F extends C{constructor({offset:e,position:t,size:n}){super(`Slice ${"start"===t?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}}class D extends C{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function U(e,{dir:t,size:n=32}={}){return"string"==typeof e?function(e,{dir:t,size:n=32}={}){if(null===n)return e;const s=e.replace("0x","");if(s.length>2*n)throw new D({size:Math.ceil(s.length/2),targetSize:n,type:"hex"});return`0x${s["right"===t?"padEnd":"padStart"](2*n,"0")}`}(e,{dir:t,size:n}):function(e,{dir:t,size:n=32}={}){if(null===n)return e;if(e.length>n)throw new D({size:e.length,targetSize:n,type:"bytes"});const s=new Uint8Array(n);for(let a=0;a<n;a++){const r="right"===t;s[r?a:n-a-1]=e[r?a:e.length-a-1]}return s}(e,{dir:t,size:n})}const T=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function B(e,t={}){return"number"==typeof e||"bigint"==typeof e?L(e,t):"string"==typeof e?function(e,t={}){const n=M.encode(e);return R(n,t)}(e,t):"boolean"==typeof e?function(e,t={}){const n=`0x${Number(e)}`;if("number"==typeof t.size)return q(n,{size:t.size}),U(n,{size:t.size});return n}(e,t):R(e,t)}function R(e,t={}){let n="";for(let a=0;a<e.length;a++)n+=T[e[a]];const s=`0x${n}`;return"number"==typeof t.size?(q(s,{size:t.size}),U(s,{dir:"right",size:t.size})):s}function L(e,t={}){const{signed:n,size:s}=t,a=BigInt(e);let r;s?r=n?(1n<<8n*BigInt(s)-1n)-1n:2n**(8n*BigInt(s))-1n:"number"==typeof e&&(r=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof r&&n?-r-1n:0;if(r&&a>r||a<o){const t="bigint"==typeof e?"n":"";throw new j({max:r?`${r}${t}`:void 0,min:`${o}${t}`,signed:n,size:s,value:`${e}${t}`})}const i=`0x${(n&&a<0?(1n<<BigInt(8*s))+BigInt(a):a).toString(16)}`;return s?U(i,{size:s}):i}const M=new TextEncoder;const $=new TextEncoder;function G(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){const n=L(e,t);return W(n)}(e,t):"boolean"==typeof e?function(e,t={}){const n=new Uint8Array(1);if(n[0]=Number(e),"number"==typeof t.size)return q(n,{size:t.size}),U(n,{size:t.size});return n}(e,t):S(e)?W(e,t):H(e,t)}const O={zero:48,nine:57,A:65,F:70,a:97,f:102};function z(e){return e>=O.zero&&e<=O.nine?e-O.zero:e>=O.A&&e<=O.F?e-(O.A-10):e>=O.a&&e<=O.f?e-(O.a-10):void 0}function W(e,t={}){let n=e;t.size&&(q(n,{size:t.size}),n=U(n,{dir:"right",size:t.size}));let s=n.slice(2);s.length%2&&(s=`0${s}`);const a=s.length/2,r=new Uint8Array(a);for(let o=0,i=0;o<a;o++){const e=z(s.charCodeAt(i++)),t=z(s.charCodeAt(i++));if(void 0===e||void 0===t)throw new C(`Invalid byte sequence ("${s[i-2]}${s[i-1]}" in "${s}").`);r[o]=16*e+t}return r}function H(e,t={}){const n=$.encode(e);return"number"==typeof t.size?(q(n,{size:t.size}),U(n,{dir:"right",size:t.size})):n}function q(e,{size:t}){if(A(e)>t)throw new I({givenSize:A(e),maxSize:t})}function V(e,t={}){const{signed:n}=t;t.size&&q(e,{size:t.size});const s=BigInt(e);if(!n)return s;const a=(e.length-2)/2;return s<=(1n<<8n*BigInt(a)-1n)-1n?s:s-BigInt(`0x${"f".padStart(2*a,"f")}`)-1n}function Q(e,t={}){return Number(V(e,t))}function Z(e,t){return({exclude:n,format:s})=>({exclude:n,format:(e,a)=>{const r=t(e,a);if(n)for(const t of n)delete r[t];return{...r,...s(e,a)}},type:e})}const K={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Y(e,t){const n={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?Q(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Q(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?K[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(n.authorizationList=e.authorizationList.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))),n.yParity=(()=>{if(e.yParity)return Number(e.yParity);if("bigint"==typeof n.v){if(0n===n.v||27n===n.v)return 0;if(1n===n.v||28n===n.v)return 1;if(n.v>=35n)return n.v%2n==0n?1:0}})(),"legacy"===n.type&&(delete n.accessList,delete n.maxFeePerBlobGas,delete n.maxFeePerGas,delete n.maxPriorityFeePerGas,delete n.yParity),"eip2930"===n.type&&(delete n.maxFeePerBlobGas,delete n.maxFeePerGas,delete n.maxPriorityFeePerGas),"eip1559"===n.type&&delete n.maxFeePerBlobGas,n}const _=Z("transaction",Y);function J(e,t){const n=(e.transactions??[]).map(e=>"string"==typeof e?e:Y(e));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:n,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const X=Z("block",J);const ee={"0x0":"reverted","0x1":"success"};function te(e,t){const n={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(e=>function(e,{args:t,eventName:n}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...n?{args:t,eventName:n}:{}}}(e)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Q(e.transactionIndex):null,status:e.status?ee[e.status]:null,type:e.type?K[e.type]||e.type:null};return e.blobGasPrice&&(n.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(n.blobGasUsed=BigInt(e.blobGasUsed)),n}const ne=Z("transactionReceipt",te),se={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function ae(e,t){const n={};return void 0!==e.authorizationList&&(n.authorizationList=e.authorizationList.map(e=>({address:e.address,r:e.r?L(BigInt(e.r)):e.r,s:e.s?L(BigInt(e.s)):e.s,chainId:L(e.chainId),nonce:L(e.nonce),...void 0!==e.yParity?{yParity:L(e.yParity)}:{},...void 0!==e.v&&void 0===e.yParity?{v:L(e.v)}:{}}))),void 0!==e.accessList&&(n.accessList=e.accessList),void 0!==e.blobVersionedHashes&&(n.blobVersionedHashes=e.blobVersionedHashes),void 0!==e.blobs&&("string"!=typeof e.blobs[0]?n.blobs=e.blobs.map(e=>R(e)):n.blobs=e.blobs),void 0!==e.data&&(n.data=e.data),e.account&&(n.from=e.account.address),void 0!==e.from&&(n.from=e.from),void 0!==e.gas&&(n.gas=L(e.gas)),void 0!==e.gasPrice&&(n.gasPrice=L(e.gasPrice)),void 0!==e.maxFeePerBlobGas&&(n.maxFeePerBlobGas=L(e.maxFeePerBlobGas)),void 0!==e.maxFeePerGas&&(n.maxFeePerGas=L(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=L(e.maxPriorityFeePerGas)),void 0!==e.nonce&&(n.nonce=L(e.nonce)),void 0!==e.to&&(n.to=e.to),void 0!==e.type&&(n.type=se[e.type]),void 0!==e.value&&(n.value=L(e.value)),n}const re=Z("transactionRequest",ae);const oe=2n**256n-1n;function ie(e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}class ce extends C{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class le extends C{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}}class de extends C{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}}const me={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new de({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new le({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new ce({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new ce({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const n=t??this.position;return this.assertPosition(n+e-1),this.bytes.subarray(n,n+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,255&e),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const n=this.inspectBytes(e);return this.position+=t??e,n},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function ue(e,{recursiveReadLimit:t=8192}={}){const n=Object.create(me);return n.bytes=e,n.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),n.positionReadCount=new Map,n.recursiveReadLimit=t,n}function he(e,t="hex"){const n=pe(e),s=ue(new Uint8Array(n.length));return n.encode(s),"hex"===t?R(s.bytes):s.bytes}function pe(e){return Array.isArray(e)?function(e){const t=e.reduce((e,t)=>e+t.length,0),n=ye(t);return{length:t<=55?1+t:1+n+t,encode(s){t<=55?s.pushByte(192+t):(s.pushByte(247+n),1===n?s.pushUint8(t):2===n?s.pushUint16(t):3===n?s.pushUint24(t):s.pushUint32(t));for(const{encode:t}of e)t(s)}}}(e.map(e=>pe(e))):function(e){const t="string"==typeof e?W(e):e,n=ye(t.length),s=1===t.length&&t[0]<128?1:t.length<=55?1+t.length:1+n+t.length;return{length:s,encode(e){1===t.length&&t[0]<128?e.pushBytes(t):t.length<=55?(e.pushByte(128+t.length),e.pushBytes(t)):(e.pushByte(183+n),1===n?e.pushUint8(t.length):2===n?e.pushUint16(t.length):3===n?e.pushUint24(t.length):e.pushUint32(t.length),e.pushBytes(t))}}}(e)}function ye(e){if(e<256)return 1;if(e<65536)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new C("Length is too large.")}const ge={ether:-9,wei:9};function fe(e,t="wei"){return function(e,t){let n=e.toString();const s=n.startsWith("-");s&&(n=n.slice(1)),n=n.padStart(t,"0");let[a,r]=[n.slice(0,n.length-t),n.slice(n.length-t)];return r=r.replace(/(0+)$/,""),`${s?"-":""}${a||"0"}${r?`.${r}`:""}`}(e,ge[t])}function be(e){const t=Object.entries(e).map(([e,t])=>void 0===t||!1===t?null:[e,t]).filter(Boolean),n=t.reduce((e,[t])=>Math.max(e,t.length),0);return t.map(([e,t])=>` ${`${e}:`.padEnd(n+1)} ${t}`).join("\n")}class xe extends C{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class we extends C{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",be(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class ve extends C{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}function ke(e){const{kzg:t}=e,n=e.to??("string"==typeof e.blobs[0]?"hex":"bytes"),s="string"==typeof e.blobs[0]?e.blobs.map(e=>W(e)):e.blobs,a=[];for(const r of s)a.push(Uint8Array.from(t.blobToKzgCommitment(r)));return"bytes"===n?a:a.map(e=>R(e))}function Ne(e){const{kzg:t}=e,n=e.to??("string"==typeof e.blobs[0]?"hex":"bytes"),s="string"==typeof e.blobs[0]?e.blobs.map(e=>W(e)):e.blobs,a="string"==typeof e.commitments[0]?e.commitments.map(e=>W(e)):e.commitments,r=[];for(let o=0;o<s.length;o++){const e=s[o],n=a[o];r.push(Uint8Array.from(t.computeBlobKzgProof(e,n)))}return"bytes"===n?r:r.map(e=>R(e))}
|
|
2
|
-
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ce(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Pe(e,...t){if(!((n=e)instanceof Uint8Array||ArrayBuffer.isView(n)&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");var n;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function je(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ie(e,t){Pe(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Se(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ae(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ee(e,t){return e<<32-t|e>>>t}function Fe(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const De=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=Fe(e[t]);return e};function Ue(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),Pe(e),e}class Te{}function Be(e){const t=t=>e().update(Ue(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Re(e,t,n){return e&t^~e&n}function Le(e,t,n){return e&t^e&n^t&n}class Me extends Te{constructor(e,t,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ae(this.buffer)}update(e){je(this),Pe(e=Ue(e));const{view:t,buffer:n,blockLen:s}=this,a=e.length;for(let r=0;r<a;){const o=Math.min(s-this.pos,a-r);if(o===s){const t=Ae(e);for(;s<=a-r;r+=s)this.process(t,r);continue}n.set(e.subarray(r,r+o),this.pos),this.pos+=o,r+=o,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){je(this),Ie(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:s,isLE:a}=this;let{pos:r}=this;t[r++]=128,Se(this.buffer.subarray(r)),this.padOffset>s-r&&(this.process(n,0),r=0);for(let d=r;d<s;d++)t[d]=0;!function(e,t,n,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,s);const a=BigInt(32),r=BigInt(4294967295),o=Number(n>>a&r),i=Number(n&r),c=s?4:0,l=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+l,i,s)}(n,s-8,BigInt(8*this.length),a),this.process(n,0);const o=Ae(e),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=i/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,l[d],a)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:s,finished:a,destroyed:r,pos:o}=this;return e.destroyed=r,e.finished=a,e.length=s,e.pos=o,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const $e=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ge=BigInt(2**32-1),Oe=BigInt(32);function ze(e,t=!1){return t?{h:Number(e&Ge),l:Number(e>>Oe&Ge)}:{h:0|Number(e>>Oe&Ge),l:0|Number(e&Ge)}}const We=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),He=new Uint32Array(64);class qe extends Me{constructor(e=32){super(64,e,8,!1),this.A=0|$e[0],this.B=0|$e[1],this.C=0|$e[2],this.D=0|$e[3],this.E=0|$e[4],this.F=0|$e[5],this.G=0|$e[6],this.H=0|$e[7]}get(){const{A:e,B:t,C:n,D:s,E:a,F:r,G:o,H:i}=this;return[e,t,n,s,a,r,o,i]}set(e,t,n,s,a,r,o,i){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|s,this.E=0|a,this.F=0|r,this.G=0|o,this.H=0|i}process(e,t){for(let d=0;d<16;d++,t+=4)He[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){const e=He[d-15],t=He[d-2],n=Ee(e,7)^Ee(e,18)^e>>>3,s=Ee(t,17)^Ee(t,19)^t>>>10;He[d]=s+He[d-7]+n+He[d-16]|0}let{A:n,B:s,C:a,D:r,E:o,F:i,G:c,H:l}=this;for(let d=0;d<64;d++){const e=l+(Ee(o,6)^Ee(o,11)^Ee(o,25))+Re(o,i,c)+We[d]+He[d]|0,t=(Ee(n,2)^Ee(n,13)^Ee(n,22))+Le(n,s,a)|0;l=c,c=i,i=o,o=r+e|0,r=a,a=s,s=n,n=e+t|0}n=n+this.A|0,s=s+this.B|0,a=a+this.C|0,r=r+this.D|0,o=o+this.E|0,i=i+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,s,a,r,o,i,c,l)}roundClean(){Se(He)}destroy(){this.set(0,0,0,0,0,0,0,0),Se(this.buffer)}}const Ve=Be(()=>new qe);function Qe(e){const{commitment:t,version:n=1}=e,s=e.to??("string"==typeof t?"hex":"bytes"),a=Ve(S(r=t,{strict:!1})?G(r):r);var r;return a.set([n],0),"bytes"===s?a:R(a)}const Ze=4096,Ke=131072,Ye=761855;class _e extends C{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class Je extends C{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class Xe extends C{constructor({hash:e,size:t}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${t}`],name:"InvalidVersionedHashSizeError"})}}class et extends C{constructor({hash:e,version:t}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:["Expected: 1",`Received: ${t}`],name:"InvalidVersionedHashVersionError"})}}function tt(e){const{data:t,kzg:n,to:s}=e,a=e.blobs??function(e){const t=e.to??("string"==typeof e.data?"hex":"bytes"),n="string"==typeof e.data?W(e.data):e.data,s=A(n);if(!s)throw new Je;if(s>Ye)throw new _e({maxSize:Ye,size:s});const a=[];let r=!0,o=0;for(;r;){const e=ue(new Uint8Array(Ke));let t=0;for(;t<Ze;){const s=n.slice(o,o+31);if(e.pushByte(0),e.pushBytes(s),s.length<31){e.pushByte(128),r=!1;break}t++,o+=31}a.push(e)}return"bytes"===t?a.map(e=>e.bytes):a.map(e=>R(e.bytes))}({data:t,to:s}),r=e.commitments??ke({blobs:a,kzg:n,to:s}),o=e.proofs??Ne({blobs:a,commitments:r,kzg:n,to:s}),i=[];for(let c=0;c<a.length;c++)i.push({blob:a[c],commitment:r[c],proof:o[c]});return i}class nt extends C{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class st extends C{constructor({chainId:e}){super("number"==typeof e?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}class at extends C{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${fe(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(at,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class rt extends C{constructor({cause:e,maxPriorityFeePerGas:t,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${fe(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${fe(n)} gwei`:""}).`].join("\n"),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(rt,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class ot extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const it=BigInt(0),ct=BigInt(1),lt=BigInt(2),dt=BigInt(7),mt=BigInt(256),ut=BigInt(113),ht=[],pt=[],yt=[];for(let Xn=0,es=ct,ts=1,ns=0;Xn<24;Xn++){[ts,ns]=[ns,(2*ts+3*ns)%5],ht.push(2*(5*ns+ts)),pt.push((Xn+1)*(Xn+2)/2%64);let e=it;for(let t=0;t<7;t++)es=(es<<ct^(es>>dt)*ut)%mt,es<&&(e^=ct<<(ct<<BigInt(t))-ct);yt.push(e)}const gt=function(e,t=!1){const n=e.length;let s=new Uint32Array(n),a=new Uint32Array(n);for(let r=0;r<n;r++){const{h:n,l:o}=ze(e[r],t);[s[r],a[r]]=[n,o]}return[s,a]}(yt,!0),ft=gt[0],bt=gt[1],xt=(e,t,n)=>n>32?((e,t,n)=>t<<n-32|e>>>64-n)(e,t,n):((e,t,n)=>e<<n|t>>>32-n)(e,t,n),wt=(e,t,n)=>n>32?((e,t,n)=>e<<n-32|t>>>64-n)(e,t,n):((e,t,n)=>t<<n|e>>>32-n)(e,t,n);class vt extends Te{constructor(e,t,n,s=!1,a=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.rounds=a,Ce(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var r;this.state=new Uint8Array(200),this.state32=(r=this.state,new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)))}clone(){return this._cloneInto()}keccak(){De(this.state32),function(e,t=24){const n=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let s=0;s<10;s++)n[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){const t=(s+8)%10,a=(s+2)%10,r=n[a],o=n[a+1],i=xt(r,o,1)^n[t],c=wt(r,o,1)^n[t+1];for(let n=0;n<50;n+=10)e[s+n]^=i,e[s+n+1]^=c}let t=e[2],a=e[3];for(let n=0;n<24;n++){const s=pt[n],r=xt(t,a,s),o=wt(t,a,s),i=ht[n];t=e[i],a=e[i+1],e[i]=r,e[i+1]=o}for(let s=0;s<50;s+=10){for(let t=0;t<10;t++)n[t]=e[s+t];for(let t=0;t<10;t++)e[s+t]^=~n[(t+2)%10]&n[(t+4)%10]}e[0]^=ft[s],e[1]^=bt[s]}Se(n)}(this.state32,this.rounds),De(this.state32),this.posOut=0,this.pos=0}update(e){je(this),Pe(e=Ue(e));const{blockLen:t,state:n}=this,s=e.length;for(let a=0;a<s;){const r=Math.min(t-this.pos,s-a);for(let t=0;t<r;t++)n[this.pos++]^=e[a++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,128&t&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){je(this,!1),Pe(e),this.finish();const t=this.state,{blockLen:n}=this;for(let s=0,a=e.length;s<a;){this.posOut>=n&&this.keccak();const r=Math.min(n-this.posOut,a-s);e.set(t.subarray(this.posOut,this.posOut+r),s),this.posOut+=r,s+=r}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ce(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ie(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Se(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:a,enableXOF:r}=this;return e||(e=new vt(t,n,s,r,a)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=a,e.suffix=n,e.outputLen=s,e.enableXOF=r,e.destroyed=this.destroyed,e}}const kt=(()=>{return e=1,t=136,n=32,Be(()=>new vt(t,e,n));var e,t,n})();const Nt=new ot(8192);function Ct(e,t){if(Nt.has(`${e}.${t}`))return Nt.get(`${e}.${t}`);const n=e.substring(2).toLowerCase(),s=(a=H(n),kt(S(a,{strict:!1})?G(a):a));var a;const r=n.split("");for(let i=0;i<40;i+=2)s[i>>1]>>4>=8&&r[i]&&(r[i]=r[i].toUpperCase()),(15&s[i>>1])>=8&&r[i+1]&&(r[i+1]=r[i+1].toUpperCase());const o=`0x${r.join("")}`;return Nt.set(`${e}.${t}`,o),o}const Pt=/^0x[a-fA-F0-9]{40}$/,jt=new ot(8192);function It(e,t){const{strict:n=!0}=t??{},s=`${e}.${n}`;if(jt.has(s))return jt.get(s);const a=!(!Pt.test(e)||e.toLowerCase()!==e&&n&&Ct(e)!==e);return jt.set(s,a),a}function St(e,t,n,{strict:s}={}){return S(e,{strict:!1})?function(e,t,n,{strict:s}={}){const a=`0x${e.replace("0x","").slice(2*t,2*n)}`;s&&At(a,t,n);return a}(e,t,n,{strict:s}):function(e,t,n,{strict:s}={}){const a=e.slice(t,n);s&&At(a,t,n);return a}(e,t,n,{strict:s})}function At(e,t,n){if(A(e)!==n-t)throw new F({offset:n,position:"end",size:A(e)})}function Et(e){const{chainId:t,maxPriorityFeePerGas:n,maxFeePerGas:s,to:a}=e;if(t<=0)throw new st({chainId:t});if(a&&!It(a))throw new nt({address:a});if(s&&s>oe)throw new at({maxFeePerGas:s});if(n&&s&&n>s)throw new rt({maxFeePerGas:s,maxPriorityFeePerGas:n})}function Ft(e){if(!e||0===e.length)return[];const t=[];for(let n=0;n<e.length;n++){const{address:s,storageKeys:a}=e[n];for(let e=0;e<a.length;e++)if(a[e].length-2!=64)throw new ve({storageKey:a[e]});if(!It(s,{strict:!1}))throw new nt({address:s});t.push([s,a])}return t}function Dt(e,t){const n=function(e){if(e.type)return e.type;if(void 0!==e.authorizationList)return"eip7702";if(void 0!==e.blobs||void 0!==e.blobVersionedHashes||void 0!==e.maxFeePerBlobGas||void 0!==e.sidecars)return"eip4844";if(void 0!==e.maxFeePerGas||void 0!==e.maxPriorityFeePerGas)return"eip1559";if(void 0!==e.gasPrice)return void 0!==e.accessList?"eip2930":"legacy";throw new we({transaction:e})}(e);return"eip1559"===n?function(e,t){const{chainId:n,gas:s,nonce:a,to:r,value:o,maxFeePerGas:i,maxPriorityFeePerGas:c,accessList:l,data:d}=e;Et(e);const m=Ft(l),u=[L(n),a?L(a):"0x",c?L(c):"0x",i?L(i):"0x",s?L(s):"0x",r??"0x",o?L(o):"0x",d??"0x",m,...Ut(e,t)];return ie(["0x02",he(u)])}(e,t):"eip2930"===n?function(e,t){const{chainId:n,gas:s,data:a,nonce:r,to:o,value:i,accessList:c,gasPrice:l}=e;!function(e){const{chainId:t,maxPriorityFeePerGas:n,gasPrice:s,maxFeePerGas:a,to:r}=e;if(t<=0)throw new st({chainId:t});if(r&&!It(r))throw new nt({address:r});if(n||a)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(s&&s>oe)throw new at({maxFeePerGas:s})}(e);const d=Ft(c),m=[L(n),r?L(r):"0x",l?L(l):"0x",s?L(s):"0x",o??"0x",i?L(i):"0x",a??"0x",d,...Ut(e,t)];return ie(["0x01",he(m)])}(e,t):"eip4844"===n?function(e,t){const{chainId:n,gas:s,nonce:a,to:r,value:o,maxFeePerBlobGas:i,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:d,data:m}=e;!function(e){const{blobVersionedHashes:t}=e;if(t){if(0===t.length)throw new Je;for(const e of t){const t=A(e),n=Q(St(e,0,1));if(32!==t)throw new Xe({hash:e,size:t});if(1!==n)throw new et({hash:e,version:n})}}Et(e)}(e);let u=e.blobVersionedHashes,h=e.sidecars;if(e.blobs&&(void 0===u||void 0===h)){const t="string"==typeof e.blobs[0]?e.blobs:e.blobs.map(e=>R(e)),n=e.kzg,s=ke({blobs:t,kzg:n});if(void 0===u&&(u=function(e){const{commitments:t,version:n}=e,s=e.to??("string"==typeof t[0]?"hex":"bytes"),a=[];for(const r of t)a.push(Qe({commitment:r,to:s,version:n}));return a}({commitments:s})),void 0===h){h=tt({blobs:t,commitments:s,proofs:Ne({blobs:t,commitments:s,kzg:n})})}}const p=Ft(d),y=[L(n),a?L(a):"0x",l?L(l):"0x",c?L(c):"0x",s?L(s):"0x",r??"0x",o?L(o):"0x",m??"0x",p,i?L(i):"0x",u??[],...Ut(e,t)],g=[],f=[],b=[];if(h)for(let x=0;x<h.length;x++){const{blob:e,commitment:t,proof:n}=h[x];g.push(e),f.push(t),b.push(n)}return ie(["0x03",he(h?[y,g,f,b]:y)])}(e,t):"eip7702"===n?function(e,t){const{authorizationList:n,chainId:s,gas:a,nonce:r,to:o,value:i,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:d,data:m}=e;!function(e){const{authorizationList:t}=e;if(t)for(const n of t){const{chainId:e}=n,t=n.address;if(!It(t))throw new nt({address:t});if(e<0)throw new st({chainId:e})}Et(e)}(e);const u=Ft(d),h=function(e){if(!e||0===e.length)return[];const t=[];for(const n of e){const{chainId:e,nonce:s,...a}=n,r=n.address;t.push([e?B(e):"0x",r,s?B(s):"0x",...Ut({},a)])}return t}(n);return ie(["0x04",he([L(s),r?L(r):"0x",l?L(l):"0x",c?L(c):"0x",a?L(a):"0x",o??"0x",i?L(i):"0x",m??"0x",u,h,...Ut(e,t)])])}(e,t):function(e,t){const{chainId:n=0,gas:s,data:a,nonce:r,to:o,value:i,gasPrice:c}=e;!function(e){const{chainId:t,maxPriorityFeePerGas:n,gasPrice:s,maxFeePerGas:a,to:r}=e;if(r&&!It(r))throw new nt({address:r});if(void 0!==t&&t<=0)throw new st({chainId:t});if(n||a)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(s&&s>oe)throw new at({maxFeePerGas:s})}(e);let l=[r?L(r):"0x",c?L(c):"0x",s?L(s):"0x",o??"0x",i?L(i):"0x",a??"0x"];if(t){const e=(()=>{if(t.v>=35n){return(t.v-35n)/2n>0?t.v:27n+(35n===t.v?0n:1n)}if(n>0)return BigInt(2*n)+BigInt(35n+t.v-27n);const e=27n+(27n===t.v?0n:1n);if(t.v!==e)throw new xe({v:t.v});return e})(),s=E(t.r),a=E(t.s);l=[...l,L(e),"0x00"===s?"0x":s,"0x00"===a?"0x":a]}else n>0&&(l=[...l,L(n),"0x","0x"]);return he(l)}(e,t)}function Ut(e,t){const n=t??e,{v:s,yParity:a}=n;if(void 0===n.r)return[];if(void 0===n.s)return[];if(void 0===s&&void 0===a)return[];const r=E(n.r),o=E(n.s);return["number"==typeof a?a?L(1):"0x":0n===s?"0x":1n===s?L(1):27n===s?"0x":L(1),"0x00"===r?"0x":r,"0x00"===o?"0x":o]}const Tt={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}};function Bt(e,t){return function(e){return"deposit"===e.type||void 0!==e.sourceHash}(e)?function(e){!function(e){const{from:t,to:n}=e;if(t&&!It(t))throw new nt({address:t});if(n&&!It(n))throw new nt({address:n})}(e);const{sourceHash:t,data:n,from:s,gas:a,isSystemTx:r,mint:o,to:i,value:c}=e;return ie(["0x7e",he([t,s,i??"0x",o?B(o):"0x",c?B(c):"0x",a?B(a):"0x",r?"0x1":"0x",n??"0x"])])}(e):Dt(e,t)}const Rt={blockTime:2e3,contracts:Tt,formatters:{block:X({format(e){var t;return{transactions:null==(t=e.transactions)?void 0:t.map(e=>{if("string"==typeof e)return e;const t=Y(e);return"0x7e"===t.typeHex&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?V(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}),stateRoot:e.stateRoot}}}),transaction:_({format(e){const t={};return"0x7e"===e.type&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?V(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:ne({format:e=>({l1GasPrice:e.l1GasPrice?V(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?V(e.l1GasUsed):null,l1Fee:e.l1Fee?V(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null})})},serializers:{transaction:Bt}},Lt=v({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:250,rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),Mt=v({id:43114,name:"Avalanche",blockTime:1700,nativeCurrency:{decimals:18,name:"Avalanche",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax.network/ext/bc/C/rpc"]}},blockExplorers:{default:{name:"SnowTrace",url:"https://snowtrace.io",apiUrl:"https://api.snowtrace.io"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:11907934}}}),$t=1,Gt=v({...Rt,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...Rt.contracts,disputeGameFactory:{[$t]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[$t]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[$t]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[$t]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:1}),Ot=v({id:56,name:"BNB Smart Chain",blockTime:750,nativeCurrency:{decimals:18,name:"BNB",symbol:"BNB"},rpcUrls:{default:{http:["https://56.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com",apiUrl:"https://api.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:15921452}}}),zt={estimateFeesPerGas:async e=>{var t;if(!(null==(t=e.request)?void 0:t.feeCurrency))return null;const[n,s]=await Promise.all([Wt(e.client,e.request.feeCurrency),Ht(e.client,e.request.feeCurrency)]);return{maxFeePerGas:e.multiply(n-s)+s,maxPriorityFeePerGas:s}}};async function Wt(e,t){const n=await e.request({method:"eth_gasPrice",params:[t]});return BigInt(n)}async function Ht(e,t){const n=await e.request({method:"eth_maxPriorityFeePerGas",params:[t]});return BigInt(n)}function qt(e){return 0===e||0n===e||null==e||"0"===e||""===e||"string"==typeof e&&("0x"===E(e).toLowerCase()||"0x00"===E(e).toLowerCase())}function Vt(e){return!qt(e)}function Qt(e){return"cip64"===e.type||function(e){return void 0!==e.maxFeePerGas&&void 0!==e.maxPriorityFeePerGas}(e)&&Vt(e.feeCurrency)}const Zt={transaction:function(e,t){return Qt(e)?function(e,t){!function(e){const{chainId:t,maxPriorityFeePerGas:n,gasPrice:s,maxFeePerGas:a,to:r,feeCurrency:o}=e;if(t<=0)throw new st({chainId:t});if(r&&!It(r))throw new nt({address:r});if(s)throw new C("`gasPrice` is not a valid CIP-64 Transaction attribute.");if(Vt(a)&&a>Kt)throw new at({maxFeePerGas:a});if(Vt(n)&&Vt(a)&&n>a)throw new rt({maxFeePerGas:a,maxPriorityFeePerGas:n});if(Vt(o)&&!It(o))throw new C("`feeCurrency` MUST be a token address for CIP-64 transactions.");if(qt(o))throw new C("`feeCurrency` must be provided for CIP-64 transactions.")}(e);const{chainId:n,gas:s,nonce:a,to:r,value:o,maxFeePerGas:i,maxPriorityFeePerGas:c,accessList:l,feeCurrency:d,data:m}=e,u=[B(n),a?B(a):"0x",c?B(c):"0x",i?B(i):"0x",s?B(s):"0x",r??"0x",o?B(o):"0x",m??"0x",Ft(l),d,...Ut(e,t)];return ie(["0x7b",he(u)])}(e,t):Bt(e,t)}};const Kt=oe;const Yt=v({...{blockTime:1e3,contracts:Tt,formatters:{block:X({format(e){var t;return{transactions:null==(t=e.transactions)?void 0:t.map(e=>{if("string"==typeof e)return e;return{...Y(e),...e.gatewayFee?{gatewayFee:V(e.gatewayFee),gatewayFeeRecipient:e.gatewayFeeRecipient}:{},feeCurrency:e.feeCurrency}})}}}),transaction:_({format(e){if("0x7e"===e.type)return{isSystemTx:e.isSystemTx,mint:e.mint?V(e.mint):void 0,sourceHash:e.sourceHash,type:"deposit"};const t={feeCurrency:e.feeCurrency};return"0x7b"===e.type?t.type="cip64":("0x7c"===e.type&&(t.type="cip42"),t.gatewayFee=e.gatewayFee?V(e.gatewayFee):null,t.gatewayFeeRecipient=e.gatewayFeeRecipient),t}}),transactionRequest:re({format(e){const t={};return e.feeCurrency&&(t.feeCurrency=e.feeCurrency),Qt(e)&&(t.type="0x7b"),t}})},serializers:Zt,fees:zt},id:42220,name:"Celo",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://forno.celo.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://celoscan.io",apiUrl:"https://api.celoscan.io/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:13112599}},testnet:!1}),_t=v({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),Jt=1,Xt=v({...Rt,id:10,name:"OP Mainnet",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.optimism.io"]}},blockExplorers:{default:{name:"Optimism Explorer",url:"https://optimistic.etherscan.io",apiUrl:"https://api-optimistic.etherscan.io/api"}},contracts:{...Rt.contracts,disputeGameFactory:{[Jt]:{address:"0xe5965Ab5962eDc7477C8520243A95517CD252fA9"}},l2OutputOracle:{[Jt]:{address:"0xdfe97868233d1aa22e815a266982f2cf17685a27"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:4286263},portal:{[Jt]:{address:"0xbEb5Fc579115071764c7423A4f12eDde41f106Ed"}},l1StandardBridge:{[Jt]:{address:"0x99C9fc46f92E8a1c0deC1b1747d010903E884bE1"}}},sourceId:1}),en=v({id:137,name:"Polygon",blockTime:2e3,nativeCurrency:{name:"POL",symbol:"POL",decimals:18},rpcUrls:{default:{http:["https://polygon-rpc.com"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://polygonscan.com",apiUrl:"https://api.polygonscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:25770160}}}),tn=(e,t,n=!1)=>{if(!e||"string"!=typeof e)throw new Error(`Missing ${t} address`);if(!e.startsWith("0x"))throw new Error(`Invalid ${t} address format: must start with 0x`);if(42!==e.length)throw new Error(`Invalid ${t} address length: expected 42 characters, got ${e.length}`);if("0x0000000000000000000000000000000000000000"===e&&!n)throw new Error(`Invalid ${t} address: cannot be zero address`)},nn=e=>{const t=(e=>{tn(e.token,"token"),tn(e.recipient1,"recipient1"),tn(e.recipient2,"recipient2");const t=0n===BigInt(e.recipient3Percentage||0);if(tn(e.recipient3,"recipient3",t),!e.paymentId||"string"!=typeof e.paymentId||0===e.paymentId.length)throw new Error("Invalid payment ID: must be a non-empty string");let n,s,a,r;try{n=BigInt(e.amount||0),s=BigInt(e.recipient1Percentage||0),a=BigInt(e.recipient2Percentage||0),r=BigInt(e.recipient3Percentage||0)}catch(i){throw new Error("Invalid numeric values: cannot convert to BigInt")}if(n<=0n)throw new Error(`Invalid amount: ${e.amount} (must be greater than 0)`);const o=s+a+r;if(10000n!==o)throw new Error(`Invalid percentages: total is ${o} but must equal 10000 basis points (100%). Individual: ${s}, ${a}, ${r}`);return{amount:n,percentage1:s,percentage2:a,percentage3:r}})(e);return{token:e.token,amount:t.amount,paymentId:e.paymentId,recipient1:e.recipient1,recipient2:e.recipient2,recipient3:e.recipient3,recipient1Percentage:t.percentage1,recipient2Percentage:t.percentage2,recipient3Percentage:t.percentage3}},sn=[{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[],payable:!1,stateMutability:"nonpayable",type:"function"}],an=[{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"}],rn=e=>{var t,n;const s=(null==(t=null==e?void 0:e.message)?void 0:t.toLowerCase())||(null==(n=null==e?void 0:e.toString())?void 0:n.toLowerCase())||"",a=(null==e?void 0:e.code)||(null==e?void 0:e.reason)||"";return s.includes("user rejected")||s.includes("user denied")||s.includes("user cancelled")||s.includes("rejected by user")||4001===a||"ACTION_REJECTED"===a?{type:"user_rejected",title:"Transaction Cancelled",message:"You cancelled the transaction. No charges were made.",suggestion:'Click "Pay Now" to try again when you\'re ready.'}:s.includes("insufficient funds")||s.includes("insufficient balance")||s.includes("insufficient eth")||s.includes("insufficient matic")||s.includes("insufficient bnb")||-32e3===a?{type:"insufficient_funds",title:"Insufficient Funds",message:"You don't have enough tokens or gas fees in your wallet.",suggestion:"Add more funds to your wallet and try again."}:s.includes("network error")||s.includes("rpc error")||s.includes("connection failed")||s.includes("timeout")||s.includes("request failed")?{type:"network_error",title:"Network Error",message:"Unable to connect to the blockchain network.",suggestion:"Check your internet connection and try again."}:s.includes("wrong network")||s.includes("unsupported network")||s.includes("chain mismatch")||4902===a?{type:"wrong_network",title:"Wrong Network",message:"Please switch to the correct network in your wallet.",suggestion:"Your wallet should prompt you to switch networks."}:s.includes("wallet not connected")||s.includes("no provider")||s.includes("wallet disconnected")||4900===a?{type:"wallet_disconnected",title:"Wallet Disconnected",message:"Your wallet is not connected.",suggestion:"Please reconnect your wallet and try again."}:s.includes("gas estimation failed")||s.includes("execution reverted")||s.includes("out of gas")?{type:"gas_error",title:"Transaction Failed",message:"The transaction couldn't be processed.",suggestion:"This might be a temporary issue. Please try again."}:s.includes("approve")&&s.includes("failed")?{type:"approval_failed",title:"Token Approval Failed",message:"Failed to approve token spending.",suggestion:"Please try the approval step again."}:s.includes("transaction failed")||s.includes("revert")||s.includes("contract call failed")?{type:"transaction_failed",title:"Transaction Failed",message:"The blockchain transaction was unsuccessful.",suggestion:"Please check your wallet and try again."}:s.includes("popup")||s.includes("blocked")?{type:"popup_blocked",title:"Wallet Popup Blocked",message:"Your browser blocked the wallet popup.",suggestion:"Please allow popups for this site and try again."}:s.includes("rate limit")||s.includes("too many requests")?{type:"rate_limited",title:"Too Many Requests",message:"Please wait a moment before trying again.",suggestion:"Wait 30 seconds and retry your transaction."}:s.includes("payment not yet confirmed")||s.includes("not yet confirmed on-chain")||s.includes("payment not found on-chain")||s.includes("please complete the payment")?{type:"payment_pending",title:"Payment Pending",message:"Your payment is still being confirmed on the blockchain.",suggestion:"Please wait a moment and try again, or check if your transaction completed successfully."}:s.includes("deep link")||s.includes("app not installed")||s.includes("wallet app")?{type:"mobile_wallet_error",title:"Wallet App Issue",message:"Unable to open or connect to your wallet app.",suggestion:"Make sure your wallet app is installed and try again."}:{type:"unknown_error",title:"Something Went Wrong",message:"An unexpected error occurred.",suggestion:"Please try again or contact support if the problem persists."}},on=(e,t="")=>({timestamp:(new Date).toISOString(),context:t,userFriendly:rn(e),technical:{message:(null==e?void 0:e.message)||"Unknown error",code:null==e?void 0:e.code,reason:null==e?void 0:e.reason,stack:null==e?void 0:e.stack,name:null==e?void 0:e.name}});["✅ 3s RPC propagation delay after approval (Coinbase Wallet fix)","✅ Allowance verification loop (3 attempts, 2s intervals)","✅ Avalanche simulation bypass (JSON-RPC error workaround)","✅ Ethereum simulation bypass (stale RPC state workaround)","✅ 120s transaction timeout (was 60s)","✅ 20% gas price buffer (FIXED: proper estimateFeesPerGas import)","✅ Balance check fallback RPC (Alchemy primary, 3+ public fallbacks)","✅ USDT reset handling","⚡ Alchemy RPCs: ALL 8 CHAINS (ETH, BSC, MATIC, ARB, OP, AVAX, CELO, BASE) - 99.9% uptime",'✅ 8s backend sync delay (prevents "payment not found" RPC indexing lag)',"🆕 Base network support (Chain ID 8453, Contract: 0x6D827e60d0dC279cAa09f026d1641ECDb5704753)"].forEach(e=>{});const cn=async(e,t)=>{try{const n=await r.estimateFeesPerGas(e,{chainId:t}),s=120n,a=100n;return{maxFeePerGas:n.maxFeePerGas?n.maxFeePerGas*s/a:void 0,maxPriorityFeePerGas:n.maxPriorityFeePerGas?n.maxPriorityFeePerGas*s/a:void 0}}catch(n){return console.warn("⚠️ Could not estimate gas with buffer, using default:",n.message),{}}},ln="YWG990wOlIikc1tU7-WWTepfU8d1f4dp",dn=(e,t,a,o,i,l)=>{const[d,m]=n.useState("idle"),[u,h]=n.useState(""),[p,y]=n.useState(null),{data:f,isPending:b,error:w,sendTransaction:v}=s.useSendTransaction(),{isLoading:k,isSuccess:N}=s.useWaitForTransactionReceipt({hash:f}),C=async()=>{var e,t,n,s,a,o,c;try{m("splitPayment");const u=window.coinleyPendingSplitPayment;if(!u)throw new Error("Missing split payment data");const{contractCall:h,selectedToken:p,paymentData:f,selectedNetwork:b}=u,w=b.chainId||10,v=await i.getContractInfo(w),{abi:k}=v,N=nn(h.params),C=x(w),P=1===C,j=P||43114===C;try{const{request:e}=await r.simulateContract(g,{address:h.contractAddress,abi:k,functionName:"splitPayment",args:[N]})}catch(l){console.error("❌ Transaction simulation failed:",l),console.error("🔍 Simulation Error Details:",{message:l.message,cause:l.cause,data:l.data,reason:l.reason,code:l.code,details:l.details,shortMessage:l.shortMessage,metaMessages:l.metaMessages,name:l.name});const a=l.data||(null==(e=l.cause)?void 0:e.data);a&&(console.error("🔍 Raw Error Data (hex):",a),"string"==typeof a&&a.startsWith("0x08c379a0")?console.error("🔍 Error type: Error(string) - contract has custom revert message"):"string"==typeof a&&a.startsWith("0x4e487b71")?console.error("🔍 Error type: Panic - likely assert() failure or array bounds"):a&&console.error("🔍 Error type: Custom error or unknown revert"));const r=l.reason||(null==(t=l.cause)?void 0:t.reason)||(null==(n=l.cause)?void 0:n.shortMessage)||(null==(s=l.data)?void 0:s.message)||"Unknown revert reason (contract may use require() without message)";if(console.error("🔍 Contract Revert Reason:",r),console.error("🔍 Failed Contract Call:",{contract:h.contractAddress,function:"splitPayment",paymentId:N.paymentId,amount:N.amount.toString(),token:N.token}),!j){const{userFriendlyMessage:e}=(e=>{if(!e.message)return{revertReason:"Transaction will revert",userFriendlyMessage:"Transaction simulation failed"};const t=e.message.toLowerCase();return t.includes("abi encoding params/values length mismatch")?{revertReason:"Smart contract parameter mismatch. This is likely a technical issue.",userFriendlyMessage:"Technical error: Contract parameters mismatch. Please try again or contact support."}:t.includes("payment id already used")?{revertReason:"This payment ID has already been used.",userFriendlyMessage:"This payment has already been processed. Please check your transaction history."}:t.includes("percentages must equal 100")?{revertReason:"Payment split percentages are incorrect.",userFriendlyMessage:"Internal error: Payment split configuration is invalid. Please contact support."}:t.includes("token transfer failed")||t.includes("transfer amount exceeds")?{revertReason:"Insufficient token balance or approval.",userFriendlyMessage:"Insufficient balance or token approval. Please check your wallet balance."}:t.includes("amount must be greater than 0")?{revertReason:"Payment amount is invalid.",userFriendlyMessage:"Invalid payment amount. Please try again."}:t.includes("invalid recipient")||t.includes("zero address")?{revertReason:"One of the payment recipients has an invalid address.",userFriendlyMessage:"Payment configuration error: Invalid recipient address. Please contact support."}:t.includes("insufficient gas")||t.includes("out of gas")?{revertReason:"Insufficient gas for transaction.",userFriendlyMessage:"Not enough gas to process transaction. Please increase gas limit or check ETH balance."}:t.includes("nonce")?{revertReason:"Transaction nonce conflict.",userFriendlyMessage:"Transaction ordering conflict. Please try again in a moment."}:{revertReason:e.message,userFriendlyMessage:`Transaction simulation failed: ${e.message.substring(0,100)}${e.message.length>100?"...":""}`}})(l);throw new Error(e)}{const e=P?"ETHEREUM":"AVALANCHE",t=P?"Stale RPC state, gas estimation quirks, contract has 100% Etherscan success rate":"JSON-RPC errors during simulation (common with Avalanche RPCs), but transactions succeed on-chain";console.warn(`⚠️ [${e}] Simulation failed but proceeding anyway`),console.warn(`⚠️ [${e}] The wallet will catch any actual errors`),console.warn(`⚠️ [${e}] Reason: ${t}`),console.warn("📤 Sending transaction to wallet for real validation...")}}const I=await cn(g,w),S="arbitrum"===b.shortName,A=S?2:0;let E;for(let e=0;e<=A;e++)try{if(e>0){const t=2e3*e;await new Promise(e=>setTimeout(e,t))}E=await r.writeContract(g,{address:h.contractAddress,abi:k,functionName:"splitPayment",args:[N],...I});break}catch(d){const t=(null==(a=d.message)?void 0:a.includes("Internal JSON-RPC error"))||(null==(o=d.message)?void 0:o.includes("-32603"))||(null==(c=d.message)?void 0:c.includes("nonce"));if(e===A||!t&&!S)throw d}return y(E),m("processing"),window.coinleyPendingSplitPayment=null,E}catch(u){console.error("❌ Step 2 (SplitPayment) failed:",u);const e=on(u,"split_payment_transaction");console.error("🔍 Detailed error log:",e);const t=rn(u);throw h(t),m("error"),u}},P=async t=>{try{if(m("processing"),!i||!i.processPayment)throw new Error("API instance not available or missing processPayment method");await new Promise(e=>setTimeout(e,8e3));const n=await i.processPayment(e.id,t,a.shortName,o);return m("success"),n}catch(n){console.error("❌ Final payment processing failed:",n);const e=on(n,"final_payment_processing");console.error("🔍 Detailed error log:",e);const t=rn(n);throw h(t),m("error"),n}};return{transactionStep:d,transactionError:u,currentTransactionHash:p,txPending:b,isConfirming:k,isConfirmed:N,executePaymentTransaction:async()=>{var n,s,i,d;if(!o||!(null==e?void 0:e.contractCall))throw new Error("Missing wallet connection or payment data");const u=e.contractCall;if(!u.contractAddress)throw new Error("PaymentSplitter contract data missing from payment response");if((null==l?void 0:l.ensureCorrectNetwork)&&a){if(!(await l.ensureCorrectNetwork(a)))throw console.error("❌ Network verification failed - transaction aborted"),new Error("Network verification failed. Please ensure you are on the correct network.")}if(!t.contractAddress)throw new Error("Native token transactions not yet supported with PaymentSplitter. Please use ERC-20 tokens.");{const l=t.decimals||6,j=u.approvalAmount||Math.floor(e.totalAmount*Math.pow(10,l));try{let e,i="unknown";try{e=await r.readContract(g,{address:u.tokenAddress,abi:an,functionName:"balanceOf",args:[o]}),i="wallet-rpc"}catch(p){console.warn("⚠️ Balance check via wallet RPC failed:",{error:p.message,isEmptyData:(null==(n=p.message)?void 0:n.includes("returned no data"))||(null==(s=p.message)?void 0:s.includes("0x")),wallet:"Using wallet-controlled RPC"});const t=(null==a?void 0:a.chainId)||(null==a?void 0:a.id);if(!t)throw console.error("❌ No chainId available for fallback RPC"),p;{const n=x(t),s=(e=>{const t={1:_t,56:Ot,137:en,42161:Lt,10:Xt,43114:Mt,42220:Yt,8453:Gt}[e],n={1:[`https://eth-mainnet.g.alchemy.com/v2/${ln}`,"https://cloudflare-eth.com","https://eth.llamarpc.com","https://ethereum.publicnode.com"],56:[`https://bnb-mainnet.g.alchemy.com/v2/${ln}`,"https://bsc-dataseed.bnbchain.org","https://bsc-dataseed-public.bnbchain.org","https://bsc.nodereal.io"],137:[`https://polygon-mainnet.g.alchemy.com/v2/${ln}`,"https://polygon.llamarpc.com","https://polygon-rpc.com","https://polygon.drpc.org"],42161:[`https://arb-mainnet.g.alchemy.com/v2/${ln}`,"https://arb1.arbitrum.io/rpc","https://arbitrum.llamarpc.com"],10:[`https://opt-mainnet.g.alchemy.com/v2/${ln}`,"https://mainnet.optimism.io","https://optimism.llamarpc.com"],43114:[`https://avax-mainnet.g.alchemy.com/v2/${ln}`,"https://api.avax.network/ext/bc/C/rpc","https://avalanche.public-rpc.com"],42220:[`https://celo-mainnet.g.alchemy.com/v2/${ln}`,"https://forno.celo.org","https://celo.drpc.org"],8453:[`https://base-mainnet.g.alchemy.com/v2/${ln}`,"https://mainnet.base.org","https://base.llamarpc.com","https://base.meowrpc.com"]}[e];if(!t||!n)return null;const s=n.map(e=>c.http(e,{timeout:1e4,retryCount:1}));return c.createPublicClient({chain:t,transport:c.fallback(s)})})(n);if(!s)throw console.error("❌ No fallback RPC client available for chain",n),p;try{e=await s.readContract({address:u.tokenAddress,abi:an,functionName:"balanceOf",args:[o]}),i="fallback-rpc"}catch(f){throw console.error("❌ Balance check via fallback RPC also failed:",f.message),p}}}const d=BigInt(j);if(e<d){const n=`Insufficient ${t.symbol} balance. You have ${(Number(e)/Math.pow(10,l)).toFixed(6)} ${t.symbol} but need ${(Number(d)/Math.pow(10,l)).toFixed(6)} ${t.symbol}`;throw new Error(n)}}catch(b){if(console.error("Balance check failed:",b),b.message.includes("Insufficient"))throw b;console.warn("⚠️ Continuing despite balance check failure - transaction will be validated by wallet")}m("approve"),window.coinleyPendingSplitPayment={contractCall:u,selectedToken:t,paymentData:e,selectedNetwork:a};try{const e="0xdac17f958d2ee523a2206206994597c13d831ec7"===u.tokenAddress.toLowerCase()||"USDT"===t.symbol.toUpperCase();let n,s=c.erc20Abi;e&&(s=sn);try{n=BigInt(j)}catch(w){throw console.error("❌ Failed to convert amount to BigInt:",{amount:j,amountType:typeof j,error:w.message}),new Error(`Invalid amount value: ${j}`)}let i=0n,l=0;const d=3;for(;l<d;)try{i=await r.readContract(g,{address:u.tokenAddress,abi:c.erc20Abi,functionName:"allowance",args:[o,u.contractAddress]});break}catch(v){l++,l<d?(console.warn(`⚠️ Allowance check attempt ${l} failed, retrying in 2s...`,v.message),await new Promise(e=>setTimeout(e,2e3))):(console.warn("⚠️ Could not check allowance after 3 attempts, assuming 0 allowance:",v.message),i=0n)}if(i>=n){m("splitPayment");const e=await C();return e&&await P(e),e}if(e&&i>0n){const e=await cn(g,a.chainId),t=await r.writeContract(g,{address:u.tokenAddress,abi:c.erc20Abi,functionName:"approve",args:[u.contractAddress,0n],...e});await r.waitForTransactionReceipt(g,{hash:t,confirmations:1,timeout:12e4})}const h=await cn(g,a.chainId),p=await r.writeContract(g,{address:u.tokenAddress,abi:c.erc20Abi,functionName:"approve",args:[u.contractAddress,n],...h});y(p);await r.waitForTransactionReceipt(g,{hash:p,confirmations:1,timeout:12e4});await new Promise(e=>setTimeout(e,3e3));let f=0;const b=3;let x=!1;for(;f<b&&!x;){try{if(await r.readContract(g,{address:u.tokenAddress,abi:c.erc20Abi,functionName:"allowance",args:[o,u.contractAddress]})>=n){x=!0;break}f<b-1&&await new Promise(e=>setTimeout(e,2e3))}catch(k){console.warn(`⚠️ Allowance verification attempt ${f+1} failed:`,k.message),f<b-1&&await new Promise(e=>setTimeout(e,2e3))}f++}x||(console.warn("⚠️ Could not verify allowance after 3 attempts, proceeding anyway"),console.warn("⚠️ Transaction will fail if allowance has not propagated"));const N=await C();return N&&await P(N),N}catch(N){console.error("❌ ERC20 Approve failed:",N);const e=on(N,"approve_transaction");console.error("🔍 Detailed error log:",e);const t=rn(N);if(h(t),m("idle"),(null==(i=N.message)?void 0:i.includes("User rejected"))||(null==(d=N.message)?void 0:d.includes("User denied"))||4001===N.code)throw new Error("Transaction was cancelled by user");throw new Error(`Approve failed: ${N.message}`)}}},executeSplitPayment:C,processFinalPayment:P,resetTransaction:()=>{m("idle"),h(""),y(null),window.coinleyPendingSplitPayment=null},setTransactionError:h,setTransactionStep:m}},mn=({options:e=[],value:s,onChange:a,placeholder:r,renderOption:o,getOptionKey:i,getOptionValue:c,getSearchableText:d,disabled:m=!1})=>{const[u,h]=n.useState(!1),[p,y]=n.useState(""),[g,f]=n.useState({top:0,left:0,width:400,maxHeight:450}),b=n.useRef(null),x=n.useRef(null),w=e.filter(e=>(d?d(e):"").toLowerCase().includes(p.toLowerCase())),v=e.find(e=>c(e)===s),k=()=>{if(x.current){const e=window.innerWidth,t=window.innerHeight,n=Math.min(400,e-40),s=Math.min(450,t-100);f({top:t/2-s/2,left:e/2-n/2,width:n,maxHeight:s})}};n.useEffect(()=>{const e=e=>{b.current&&!b.current.contains(e.target)&&x.current&&!x.current.contains(e.target)&&(h(!1),y(""))},t=()=>{u&&k()};if(u){k();const n=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${n}px`,document.body.style.width="100%",document.addEventListener("mousedown",e),window.addEventListener("resize",t)}return()=>{if(u){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",window.scrollTo(0,-1*parseInt(e||"0"))}document.removeEventListener("mousedown",e),window.removeEventListener("resize",t)}},[u]);const N=u&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-30 transition-opacity",style:{zIndex:999998},onClick:()=>{h(!1),y("")}}),t.jsxs("div",{ref:b,className:"fixed bg-white border-2 border-gray-200 rounded-3xl shadow-2xl overflow-hidden",style:{top:g.top,left:g.left,width:g.width,maxHeight:g.maxHeight,zIndex:999999,transform:"translateZ(0)",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(0, 0, 0, 0.05)"},children:[t.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 bg-gradient-to-r from-[#7042D2]/10 to-purple-50",children:[t.jsx("h3",{className:"text-lg font-semibold text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:r||"Select Option"}),t.jsx("button",{onClick:()=>{h(!1),y("")},className:"text-gray-500 hover:text-gray-700 transition-colors p-1 rounded-full hover:bg-gray-100",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),t.jsx("div",{className:"p-4 border-b border-gray-200 bg-gray-50",children:t.jsx("input",{type:"text",placeholder:"Search networks and tokens...",value:p,onChange:e=>y(e.target.value),className:"w-full p-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#7042D2]/20 focus:border-[#7042D2] text-sm",style:{fontFamily:"Bricolage Grotesque, sans-serif"},autoFocus:!0})}),t.jsx("div",{className:"overflow-y-auto custom-scrollbar",style:{maxHeight:(g.maxHeight||450)-180+"px",minHeight:"200px"},children:0===w.length?t.jsxs("div",{className:"p-8 text-gray-500 text-center",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"text-4xl mb-3",children:"🔍"}),t.jsx("div",{className:"text-lg mb-2",children:"No options found"}),t.jsx("div",{className:"text-sm text-gray-400",children:"Try a different search term"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"px-4 py-3 bg-gray-50 border-b border-gray-100 text-sm text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("span",{className:"font-semibold",children:w.length})," option",1!==w.length?"s":""," available"]}),t.jsx("div",{className:"p-2",children:w.map(e=>t.jsx("button",{type:"button",onClick:()=>{a(c(e)),h(!1),y("")},className:"w-full p-4 text-left hover:bg-[#7042D2]/10 transition-all duration-200 rounded-xl mb-2 last:mb-0 "+(c(e)===s?"bg-[#7042D2]/20 text-[#7042D2] border-2 border-[#7042D2]/30":"text-gray-800 border-2 border-transparent hover:border-[#7042D2]/20"),style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:o(e)},i(e)))})]})}),t.jsx("div",{className:"p-3 bg-gradient-to-r from-gray-50 to-gray-100 border-t border-gray-200 text-center",children:t.jsx("div",{className:"text-xs text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:w.length>5?"↕️ Scroll to see more options":"✨ Select your preferred option"})})]})]});return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"relative",children:t.jsx("button",{ref:x,type:"button",onClick:()=>{m||(u||k(),h(!u))},disabled:m,className:`w-full p-4 border-2 rounded-2xl bg-gradient-to-r from-white to-gray-50 text-left focus:outline-none focus:ring-3 focus:ring-[#7042D2]/20 focus:border-[#7042D2] transition-all duration-300 ease-out shadow-lg hover:shadow-xl ${m?"opacity-50 cursor-not-allowed":"hover:border-[#7042D2]/50 cursor-pointer"} ${u?"border-[#7042D2] ring-3 ring-[#7042D2]/20":"border-gray-200"}`,style:{minHeight:"60px",fontFamily:"Bricolage Grotesque, sans-serif",fontSize:"16px",fontWeight:"500"},children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("div",{className:"flex items-center space-x-3",children:v?o(v):t.jsx("span",{className:"text-gray-500",children:r})}),t.jsx("div",{className:"transform transition-transform duration-200 "+(u?"rotate-180":""),children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 text-[#7042D2]",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]})})}),"undefined"!=typeof document&&document.body&&l.createPortal(N,document.body),t.jsx("style",{jsx:!0,children:"\n .custom-scrollbar {\n scrollbar-width: thin;\n scrollbar-color: #7042D2 #f1f1f1;\n }\n .custom-scrollbar::-webkit-scrollbar {\n width: 12px;\n }\n .custom-scrollbar::-webkit-scrollbar-track {\n background: #f8f9fa;\n border-radius: 10px;\n margin: 4px;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb {\n background: linear-gradient(180deg, #7042D2 0%, #5b34b1 100%);\n border-radius: 10px;\n border: 2px solid #f8f9fa;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb:hover {\n background: linear-gradient(180deg, #5b34b1 0%, #4c2a93 100%);\n }\n .custom-scrollbar::-webkit-scrollbar-corner {\n background: #f8f9fa;\n }\n "})]})},un=({currentStep:e,targetStep:s,children:a,className:r="",duration:o=300})=>{const[i,c]=n.useState(e===s),[l,d]=n.useState(e===s);return n.useEffect(()=>{e===s?(d(!0),setTimeout(()=>c(!0),10)):(c(!1),setTimeout(()=>d(!1),o))},[e,s,o]),l?t.jsx("div",{className:`\n transition-all duration-300 ease-out\n ${i?"transform translate-y-0 opacity-100":"transform translate-y-full opacity-0"}\n ${r}\n `,style:{transitionDuration:`${o}ms`},children:a}):null},hn=({status:e,message:s,theme:a="light",payment:r=null,transactionHash:o=null,selectedPaymentMethod:i=null,selectedNetwork:c=null,merchantName:l="Merchant",onClose:d=null})=>{const[m,u]=n.useState(!1),[h,p]=n.useState(0);n.useEffect(()=>{if("processing"===e){const e=setInterval(()=>{p(e=>e>=90?e:e+15*Math.random())},500);return()=>clearInterval(e)}},[e]);const y=async()=>{if(o)try{await navigator.clipboard.writeText(o),u(!0),setTimeout(()=>u(!1),2e3)}catch(e){console.error("Failed to copy transaction hash:",e)}},g=()=>{switch(e){case"processing":return t.jsxs("div",{className:"relative",children:[t.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-t-[#7042D2] border-blue-500/20"}),t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx("div",{className:"w-6 h-6 bg-[#7042D2] rounded-full animate-pulse"})})]});case"success":return t.jsx("div",{className:"rounded-full h-16 w-16 bg-green-500 flex items-center justify-center animate-bounce",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-10 w-10 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})});case"error":return t.jsx("div",{className:"rounded-full h-12 w-12 bg-red-100 flex items-center justify-center",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8 text-red-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})});default:return null}};return"processing"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Processing Payment"}),t.jsx("p",{className:"text-center text-gray-600 mb-6",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Your transaction has been sent to the blockchain and is being processed..."}),t.jsxs("div",{className:"w-full max-w-xs mb-4",children:[t.jsx("div",{className:"bg-gray-200 rounded-full h-3",children:t.jsx("div",{className:"bg-[#7042D2] h-3 rounded-full transition-all duration-500 ease-out",style:{width:`${h}%`}})}),t.jsxs("div",{className:"text-center mt-2 text-sm text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Processing... ",Math.round(h),"%"]})]}),t.jsxs("div",{className:"text-center space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Transaction submitted"})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-yellow-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Confirming on blockchain..."})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-gray-300 rounded-full"}),t.jsx("span",{className:"text-sm text-gray-400",children:"Finalizing payment..."})]})]}),t.jsx("div",{className:"mt-6 p-3 bg-blue-50 rounded-lg border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-800 text-center",children:"Please don't close this window. This usually takes 10-30 seconds."})})]}):"success"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-2xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Payment Successful!"}),r&&i&&t.jsxs("p",{className:"text-center max-w-[235px] mb-6 text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Your payment of ",t.jsxs("span",{className:"text-[#7042D2] font-semibold",children:[r.totalAmount||r.amount," ",i.currency]})," has been completed."]}),o&&t.jsxs("div",{className:"w-full mb-6 px-4",children:[t.jsx("p",{className:"text-sm font-medium mb-2 text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Transaction Details"}),t.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border cursor-pointer transition-colors bg-gray-50 border-gray-200 hover:bg-gray-100 mb-3",onClick:y,children:[t.jsx("span",{className:"font-mono text-sm text-gray-700",children:(f=o,f?f.length<=16?f:`${f.slice(0,8)}...${f.slice(-8)}`:"")}),t.jsxs("div",{className:"flex items-center",children:[m?t.jsx("span",{className:"text-green-500 text-xs font-medium mr-2",children:"Copied!"}):null,t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-gray-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})]})]}),(()=>{const e=((e,t)=>{if(!e||!t)return null;const n="string"==typeof t?t:t.shortName||t.name;return{ethereum:`https://etherscan.io/tx/${e}`,bsc:`https://bscscan.com/tx/${e}`,polygon:`https://polygonscan.com/tx/${e}`,arbitrum:`https://arbiscan.io/tx/${e}`,optimism:`https://optimistic.etherscan.io/tx/${e}`,avalanche:`https://snowtrace.io/tx/${e}`,celo:`https://celoscan.io/tx/${e}`,base:`https://basescan.org/tx/${e}`}[null==n?void 0:n.toLowerCase()]||null})(o,c),n=(e=>{if(!e)return"Explorer";const t="string"==typeof e?e:e.shortName||e.name;return{ethereum:"Etherscan",bsc:"BscScan",polygon:"PolygonScan",arbitrum:"Arbiscan",optimism:"Optimistic Etherscan",avalanche:"SnowTrace",celo:"CeloScan",base:"BaseScan"}[null==t?void 0:t.toLowerCase()]||"Explorer"})(c);return c&&e&&t.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 w-full p-3 rounded-lg border border-[#7042D2] bg-white hover:bg-purple-50 transition-colors group",children:[t.jsxs("span",{className:"text-sm font-medium text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["View on ",n]}),t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-[#7042D2] group-hover:translate-x-1 transition-transform",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})()]}),d&&t.jsx("button",{onClick:d,className:"w-full py-3 px-4 bg-[#7042D2] text-white font-semibold rounded-2xl text-lg shadow-md hover:bg-[#5b34b1] transition-colors",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Close"})]}):t.jsxs("div",{className:"flex flex-col items-center justify-center py-6",children:[t.jsx("div",{className:"mb-4",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-2 text-gray-900",children:"processing"===e?"Processing Payment":"error"===e?"Payment Failed":"Unknown Status"}),t.jsx("p",{className:"text-center text-gray-600",children:s})]});var f},pn={bitcoin:1,ethereum:1027,bsc:1839,polygon:3890,cardano:2010,avalanche:5805,fantom:3513,arbitrum:11841,optimism:11840,USDT:825,USDC:3408,BUSD:4687,DAI:4943,FRAX:6952,TUSD:2563,USDP:5992,USDD:5994,FDUSD:26081,PYUSD:28295,WBTC:3717,LINK:1975,UNI:7083,AAVE:7278,COMP:5692,YFI:5864,MKR:1518,SUSHI:6758,CRV:6538,SNX:2586,UMA:5617,BAL:5728,MANA:1966,SAND:6210,APE:18876,LDO:8e3,GRT:6719,ENS:13855,RPL:2943,SHIB:5994,MATIC:3890,BNB:1839,ADA:2010,SOL:5426,DOT:6636,AVAX:5805,TRX:1958,ALGO:4030,FTM:3513,ARB:11841,OP:11840,"1INCH":8104,DYDX:11156,ICP:8916,FIL:2280,CAKE:7186,RUNE:4157,ALPHA:7232,BNT:1727,KNC:1982,ZRX:1896,REN:2539,LRC:1934,WETH:2396,WMATIC:3890,WBNB:1839,UST:7129,USTC:7129,LUSD:8115,MIM:9681,FEI:8642,TRIBE:8741,RAI:8525,SUSD:2927},yn={ethereum:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bsc:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",polygon:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arbitrum:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avalanche:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",celo:"https://s2.coinmarketcap.com/static/img/coins/64x64/5567.png",optimism:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png",base:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",eth:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bnb:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",trx:"https://s2.coinmarketcap.com/static/img/coins/64x64/1958.png",algo:"https://s2.coinmarketcap.com/static/img/coins/64x64/4030.png",sol:"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png",matic:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arb:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avax:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",op:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png"},gn={metamask:"https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg",coinbase:"https://avatars.githubusercontent.com/u/18060234?s=280&v=4",rabby:"https://rabby.io/logo-128.png",zerion:"https://app.zerion.io/favicon-32x32.png",phantom:"https://phantom.app/favicons/apple-touch-icon.png",trust:"https://trustwallet.com/favicon-196x196.png",okx:"https://static.okx.com/cdn/assets/imgs/248/58E63FEA47A2B7D7.png",binance:"https://bin.bnbstatic.com/static/images/common/favicon.ico",cryptocom:"https://crypto.com/favicon.ico",hot:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiNGRjZBNkEiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmg0djhoLTR2LTJoMnYtNGgtMnYtMnptNiAwaDJ2MmgtdjdoLTJ2LTIiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg==",backpack:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiMwMEQ0QUEiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMGg4djJoLTJ2NmgtdjhoLTZWMTB6bTIgMnY0aDJWMTJ6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4=","1inch":"https://1inch.io/favicon.svg",default:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiM2MzY2RjEiIHN0cm9rZT0iI0Y5RkFGQiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmgxMnY4SDEweiIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIxLjUiIHJ4PSIxIi8+CjxjaXJjbGUgY3g9IjE4IiBjeT0iMTYiIHI9IjEiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg=="},fn=e=>(e=>{if(!e)return null;const t=pn[e.toUpperCase()];return t?`https://s2.coinmarketcap.com/static/img/coins/64x64/${t}.png`:null})(e),bn=(e,t)=>{const n=e.toLowerCase(),s=t.toLowerCase();for(const[a,r]of Object.entries(gn))if(n.includes(a)||s.includes(a))return r;return gn.default},xn=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),wn=e=>{switch(e){case"trust":return window.ethereum&&!0===window.ethereum.isTrust;case"metaMask":return window.ethereum&&!0===window.ethereum.isMetaMask;case"injected":return window.ethereum&&!window.ethereum.isMetaMask&&!window.ethereum.isCoinbaseWallet;default:return!1}},vn=(e,t)=>{if(!t)return console.warn("⚠️ No network selected"),[];if(!["ethereum","bsc","polygon","arbitrum","optimism","avalanche","celo","base"].includes(t.shortName))return console.warn("⚠️ Network not in EVM list:",t.shortName),[];return[...(e||[]).map(e=>(e=>({type:e.id,name:e.name,icon:bn(e.name,e.id),description:`Connect using ${e.name}`,isInstalled:!0,connector:e,isWagmi:!0}))(e)),...xn()?[{type:"trust",name:"Trust Wallet",icon:"🛡️",description:"Multi-chain wallet with transaction deep links",isInstalled:!1,connector:null,isWagmi:!1,mobileOnly:!0,hasTransactionDeepLinks:!0}]:[]]},kn=(e,t,n,s,a="metamask",r=null)=>{if(!e)return null;try{const t="https://paymentscreen.vercel.app",s=new URLSearchParams,r=(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId);if(!r)return console.error("❌ Cannot generate QR: No payment ID"),null;s.set("paymentId",r),s.set("preferredWallet",a),s.set("isMobile","true");const o=`${t}?${s.toString()}`;let i;switch(a){case"metamask":i=`https://metamask.app.link/dapp/${o.replace("https://","")}`;break;case"trust":const e=(null==n?void 0:n.chainId)||1;i=`https://link.trustwallet.com/open_url?coin_id=${(e=>{const t="string"==typeof e&&e.startsWith("0x")?parseInt(e,16):parseInt(e);return[1,56,137,42161,10,43114,42220,8453].includes(t)?60:{}[t]||60})(e)}&url=${encodeURIComponent(o)}`;break;case"coinbase":i=`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(o)}`;break;default:i=o}return i}catch(o){return console.error("❌ Error generating QR payment URI:",o),null}},Nn=(e,t)=>{if(!t)return null;try{switch(e){case"metamask":return t.includes("metamask.app.link")?t:`https://metamask.app.link/dapp/${t.replace("https://","")}`;case"trust":return t.includes("link.trustwallet.com")?t:`https://link.trustwallet.com/open_url?coin_id=60&url=${encodeURIComponent(t)}`;case"coinbase":return t.includes("go.cb-w.com")?t:`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(t)}`;default:return t}}catch(n){return console.error(`❌ Error generating ${e} deep link:`,n),t}},Cn=Object.freeze(Object.defineProperty({__proto__:null,generateMobilePaymentDeepLink:Nn,generateQRPaymentURI:kn},Symbol.toStringTag,{value:"Module"})),Pn=({walletAddress:e,amount:s,currency:a,network:r,theme:o="light",paymentData:i=null,onPaymentDetected:c=null,config:l=null,selectedToken:m=null,selectedNetwork:u=null,preferredWallet:h="metamask",compact:p=!1})=>{const[y,g]=n.useState(""),[f,b]=n.useState(""),[x,w]=n.useState(!0),[v,k]=n.useState(!1),[N,C]=n.useState(!1),P=n.useRef(null);return n.useEffect(()=>{(async()=>{if(!(null==i?void 0:i.id))return console.warn("⚠️ No payment data provided for QR code"),void w(!1);w(!0);try{if(!m||!m.contractAddress)throw console.error("❌ QR Code Error: selectedToken missing or incomplete:",m),new Error("Cannot generate QR code: Token contract address required");if(!u||!u.chainId)throw console.error("❌ QR Code Error: selectedNetwork missing or incomplete:",u),new Error("Cannot generate QR code: Network chain ID required");const e=kn(i,0,u,0,h);if(e.includes("metamask.app.link")||e.includes("link.trustwallet.com")||e.includes("go.cb-w.com"),!e)throw new Error("Failed to generate Coinley payment URL");g(e);const t=xn(),n=await d.toDataURL(e,{width:p?140:t?350:280,margin:2,errorCorrectionLevel:"M",color:{dark:"dark"===o?"#FFFFFF":"#000000",light:"dark"===o?"#000000":"#FFFFFF"}});b(n),w(!1)}catch(e){console.error("❌ Failed to generate QR code:",e),w(!1)}})()},[i,s,a,r,o,m,u,l,h]),n.useEffect(()=>()=>{P.current&&clearInterval(P.current)},[]),t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"flex gap-3 items-start w-full mb-2",children:[t.jsx("div",{className:"p-1.5 rounded-lg bg-white shadow-sm border flex-shrink-0",children:x?t.jsx("div",{className:"flex items-center justify-center",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600 mx-auto mb-1"}),t.jsx("div",{className:"text-xs text-gray-600",children:"Generating..."})]})}):f?t.jsx("img",{src:f,alt:"Payment QR Code",className:"rounded-lg",style:{width:140,height:140}}):t.jsx("div",{className:"flex items-center justify-center bg-gray-100 rounded-lg",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center p-2",children:[t.jsx("div",{className:"text-lg mb-1",children:"⚠️"}),t.jsx("div",{className:"text-xs text-gray-600",children:(null==i?void 0:i.id)?"QR Failed":"Payment not created"})]})})}),t.jsxs("div",{className:"flex-1 flex flex-col justify-center",children:[t.jsxs("div",{className:"p-2 bg-gray-50 rounded-lg mb-2",children:[t.jsxs("div",{className:"flex justify-between items-center mb-1",children:[t.jsx("span",{className:"text-xs font-medium text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"text-sm font-bold text-[#7042D2]",children:[s," ",a]})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-xs text-gray-500",children:"Network:"}),t.jsx("span",{className:"text-xs font-medium text-gray-700",children:r})]})]}),N?t.jsxs("div",{className:"flex items-center justify-center text-xs font-semibold text-green-600 p-1.5 bg-green-50 rounded-lg",children:[t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3.5 w-3.5 mr-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"Payment Received!"]}):t.jsx("div",{className:"p-1.5 rounded-lg bg-blue-50 border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-700 text-center leading-tight",children:"📱 Scan with phone camera"})})]})]})})},jn=({selectedNetwork:e,onWalletSelect:a,onConnect:r,connectedWallet:o,loading:i,paymentData:c=null,selectedToken:l=null,api:d=null})=>{const[m,u]=n.useState(null),{connectors:h}=s.useConnect(),{isConnected:p,address:y}=s.useAccount(),g=vn(h,e),f=async(t,n)=>{if(xn())if(c)try{const{generateQRPaymentURI:s,generateMobilePaymentDeepLink:a}=await Promise.resolve().then(()=>Cn),r=s(c,l,e,(null==d?void 0:d.config)||{},n);if(!r)throw new Error("Failed to generate payment URL");const o=a(n,r);if(!o)throw new Error(`Failed to generate ${t.name} deep link`);window.location.href=o}catch(s){console.error("❌ Mobile wallet connection failed:",s),alert(`Failed to open ${t.name}: ${s.message}`)}else alert("Please create a payment first before selecting a mobile wallet.");else alert(`Please install ${t.name} mobile app or use the browser extension if available.`)};return e?0===g.length?t.jsxs("div",{className:"text-center p-4",children:[t.jsxs("p",{className:"text-gray-500 mb-4",children:["No compatible wallets found for ",e.name]}),t.jsx("div",{className:"p-3 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-sm text-amber-800",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"font-medium mb-2",children:"Install a compatible wallet:"}),t.jsxs("div",{className:"space-y-1 text-xs",children:[t.jsxs("div",{children:["• ",t.jsx("a",{href:"https://metamask.io/download/",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install MetaMask Wallet"})]}),t.jsxs("div",{children:["• ",t.jsx("a",{href:"https://www.coinbase.com/wallet",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Coinbase Wallet"})]})]})]})})]}):t.jsxs("div",{className:"space-y-4",children:[t.jsxs("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Select Wallet for ",e.name]}),t.jsx(mn,{options:g,value:(null==o?void 0:o.walletType)||m||"",onChange:async e=>{u(e);const t=g.find(t=>t.type===e);t&&(a(e),t.isWagmi&&t.connector?await r(t.connector):t.isWagmi||await f(t,e))},placeholder:"Choose your wallet...",renderOption:e=>{var n,s;return t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsxs("div",{className:"w-8 h-8 flex items-center justify-center",children:[e.icon.startsWith("http")||e.icon.startsWith("data:")?t.jsx("img",{src:e.icon,alt:e.name,className:"w-6 h-6 rounded-full object-contain",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="block"}}):t.jsx("div",{className:"text-2xl",children:e.icon}),t.jsx("div",{className:"text-xl",style:{display:"none"},children:"🔗"})]}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800 flex items-center",children:[e.name,wn(e.type)&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full",children:"DETECTED"}),(null==o?void 0:o.walletType)===e.type&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full",children:"CONNECTED"})]}),t.jsx("div",{className:"text-sm text-gray-500",children:(null==o?void 0:o.walletType)===e.type?`Connected • ${null==(n=o.account)?void 0:n.slice(0,6)}...${null==(s=o.account)?void 0:s.slice(-4)}`:e.description})]}),i&&m===e.type&&t.jsx("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-[#7042D2]"})]})},getOptionKey:e=>e.type,getOptionValue:e=>e.type,getSearchableText:e=>`${e.name} ${e.description}`,disabled:i})]}):t.jsx("div",{className:"text-center p-4",children:t.jsx("p",{className:"text-gray-500",children:"Please select a network first"})})},In=(()=>{if("undefined"!=typeof process&&process.env)return!1;if("undefined"!=typeof window){const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||e.includes("192.168.")}return!1})()||(()=>{if("undefined"!=typeof window){const e=new URLSearchParams(window.location.search);return"true"===e.get("debug")||"true"===e.get("debugMode")}return!1})(),Sn=({paymentData:e,selectedToken:s,selectedNetwork:a,config:r,onPaymentStarted:o=()=>{},onError:i=()=>{}})=>{var c,l;const[d,m]=n.useState(null),[u,h]=n.useState(!1),[p,y]=n.useState([]),[g,f]=n.useState(!1),[b,x]=n.useState(0);n.useEffect(()=>{var t,n,r;(null==e?void 0:e.id)&&(null==s?void 0:s.contractAddress)&&(null==a?void 0:a.chainId)&&((null==(t=null==e?void 0:e.contractCall)?void 0:t.contractAddress)||(null==e?void 0:e.contractAddress))?w("success","✅ Payment data complete",{paymentId:e.id,tokenContract:s.contractAddress,chainId:a.chainId,paymentContract:(null==(r=null==e?void 0:e.contractCall)?void 0:r.contractAddress)||(null==e?void 0:e.contractAddress)}):(w("debug","⏳ Waiting for complete payment data",{hasPaymentId:!!(null==e?void 0:e.id),hasTokenContract:!!(null==s?void 0:s.contractAddress),hasChainId:!!(null==a?void 0:a.chainId),hasPaymentContract:!(!(null==(n=null==e?void 0:e.contractCall)?void 0:n.contractAddress)&&!(null==e?void 0:e.contractAddress)),checkCount:b}),x(e=>e+1))},[e,s,a,b]);const w=(e,t,n=null)=>{const s=(new Date).toLocaleTimeString(),a={id:Date.now()+Math.random(),type:e,message:t,data:n,timestamp:s};In&&(y(e=>[...e,a].slice(-20)),e.toUpperCase())},v=[{id:"metamask",name:"MetaMask",icon:"🦊",description:"Connect with MetaMask mobile"},{id:"trust",name:"Trust Wallet",icon:"🛡️",description:"Connect with Trust Wallet"},{id:"coinbase",name:"Coinbase Wallet",icon:"💙",description:"Connect with Coinbase Wallet"}];if(!e)return t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"⚠️ Payment Required"}),t.jsx("div",{className:"text-sm text-amber-700",children:"Please create a payment before selecting a wallet"})]})});const k=(null==e?void 0:e.id)&&(null==s?void 0:s.contractAddress)&&(null==a?void 0:a.chainId)&&((null==(c=null==e?void 0:e.contractCall)?void 0:c.contractAddress)||(null==e?void 0:e.contractAddress));return t.jsx("div",{className:"space-y-4",children:k?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Select Mobile Wallet"}),t.jsx(mn,{options:v,value:d||"",onChange:async t=>{const n=v.find(e=>e.id===t);if(n){m(t),h(!0);try{if(w("info",`🚀 Mobile wallet selected: ${n.name}`),!e)throw new Error("Payment data not available. Please create payment first.");w("debug","🔍 Payment Data Check",{hasPaymentData:!!e,hasSelectedToken:!!s,hasSelectedNetwork:!!a,hasConfig:!!r,paymentId:(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId),tokenAddress:null==s?void 0:s.contractAddress,networkChainId:null==a?void 0:a.chainId,amount:(null==e?void 0:e.totalAmount)||(null==e?void 0:e.amount)||(null==r?void 0:r.amount)});const i=kn(e,0,a,0,t);if(!i)throw new Error("Failed to generate payment URL");w("success","📱 Generated payment URL",{url:i,length:i.length});const c=Nn(t,i);if(!c)throw new Error(`Failed to generate ${n.name} deep link`);w("success",`🔗 Deep link generated for ${n.name}`,{deepLink:c}),o({walletType:t,walletName:n.name,paymentUrl:i,deepLink:c}),setTimeout(()=>{w("info",`📱 Opening ${n.name}...`),window.location.href=c},500)}catch(c){w("error","❌ Mobile wallet connection failed",{error:c.message,walletId:t,hasPaymentData:!!e,hasSelectedToken:!!s,hasSelectedNetwork:!!a}),i(c.message),h(!1),m(null)}}},placeholder:"Choose your wallet...",renderOption:e=>t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsx("div",{className:"w-8 h-8 flex items-center justify-center",children:t.jsx("div",{className:"text-2xl",children:e.icon})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name,d===e.id&&u&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full animate-pulse",children:"Opening..."})]}),t.jsx("div",{className:"text-sm text-gray-500",children:e.description})]})]}),getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.description}`,disabled:u}),t.jsx("div",{className:"text-xs text-gray-500 mt-2",children:"Select a wallet to open it with your payment details"})]}),u&&d&&t.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-lg animate-pulse",children:t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-blue-600 border-t-transparent"}),t.jsxs("div",{className:"text-sm text-blue-700",children:["Opening ",null==(l=v.find(e=>e.id===d))?void 0:l.name,"..."]})]})}),t.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[t.jsxs("div",{className:"flex justify-between items-center text-sm",children:[t.jsx("span",{className:"text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"font-semibold text-gray-800",children:[e.totalAmount," ",(null==s?void 0:s.symbol)||"USDC"]})]}),t.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[t.jsx("span",{className:"text-gray-600",children:"Network:"}),t.jsx("span",{className:"text-gray-800",children:(null==a?void 0:a.name)||"Ethereum"})]})]}),t.jsx("div",{className:"p-3 bg-purple-50 border border-purple-200 rounded-lg",children:t.jsxs("div",{className:"text-xs text-purple-700",children:[t.jsx("div",{className:"font-medium mb-1",children:"📱 Mobile Payment"}),t.jsx("div",{children:"Your selected wallet app will open with payment details pre-filled"})]})}),In&&t.jsxs("div",{className:"mt-4",children:[t.jsxs("button",{onClick:()=>f(!g),className:"w-full text-xs py-2 px-3 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition-colors",children:[g?"🔽 Hide Debug Info":"🔧 Show Debug Info"," (",p.length," logs)"]}),g&&t.jsxs("div",{className:"mt-2 p-3 bg-gray-900 text-green-400 rounded-lg text-xs font-mono max-h-80 overflow-y-auto",children:[t.jsx("div",{className:"text-white mb-2 font-bold",children:"📱 Mobile Debug Panel"}),0===p.length?t.jsx("div",{className:"text-gray-400",children:"No debug logs yet. Try selecting a wallet..."}):p.map(e=>t.jsxs("div",{className:"mb-3 pb-2 border-b border-gray-700",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("span",{className:"px-2 py-1 rounded text-xs font-bold "+("error"===e.type?"bg-red-600 text-white":"success"===e.type?"bg-green-600 text-white":"debug"===e.type?"bg-blue-600 text-white":"bg-gray-600 text-white"),children:e.type.toUpperCase()}),t.jsx("span",{className:"text-gray-400",children:e.timestamp})]}),t.jsx("div",{className:"text-yellow-300 mb-1",children:e.message}),e.data&&t.jsx("div",{className:"text-gray-300 text-xs",children:t.jsxs("details",{children:[t.jsx("summary",{className:"cursor-pointer text-blue-300 hover:text-blue-200",children:"📊 Data"}),t.jsx("pre",{className:"mt-1 p-2 bg-gray-800 rounded overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(e.data,null,2)})]})})]},e.id)),t.jsx("button",{onClick:()=>y([]),className:"mt-2 px-3 py-1 bg-red-600 text-white rounded text-xs hover:bg-red-700",children:"Clear Logs"})]})]})]}):t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"⏳ Preparing Payment..."}),t.jsx("div",{className:"text-sm text-amber-700",children:"Payment is being prepared. Please wait a moment..."}),t.jsx("div",{className:"mt-3",children:t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-amber-600 border-t-transparent mx-auto"})})]})})})},An=({error:e,onRetry:n,onDismiss:s,context:a="payment",className:r=""})=>{if(!e)return null;const o=rn(e),i=(e=>{switch(e){case"user_rejected":return"info";case"insufficient_funds":case"wrong_network":case"wallet_disconnected":case"payment_pending":return"warning";case"network_error":case"gas_error":case"rate_limited":return"error";default:return"critical"}})(o.type),c=(e=>{switch(e){case"user_rejected":default:return"Try Again";case"insufficient_funds":return"Add Funds & Retry";case"wrong_network":return"Switch Network & Retry";case"wallet_disconnected":return"Reconnect Wallet";case"payment_pending":return"Check Again";case"network_error":case"rate_limited":return"Retry";case"popup_blocked":return"Allow Popups & Retry";case"mobile_wallet_error":return"Open Wallet App"}})(o.type),l={info:{container:"bg-blue-50 border-blue-200",title:"text-blue-800",message:"text-blue-700",icon:"ℹ️",button:"bg-blue-600 hover:bg-blue-700"},warning:{container:"bg-amber-50 border-amber-200",title:"text-amber-800",message:"text-amber-700",icon:"⚠️",button:"bg-amber-600 hover:bg-amber-700"},error:{container:"bg-red-50 border-red-200",title:"text-red-800",message:"text-red-700",icon:"❌",button:"bg-red-600 hover:bg-red-700"},critical:{container:"bg-red-50 border-red-300",title:"text-red-900",message:"text-red-800",icon:"🚨",button:"bg-red-700 hover:bg-red-800"}},d=l[i]||l.error;return t.jsxs("div",{className:`p-4 border rounded-lg ${d.container} ${r}`,children:[t.jsxs("div",{className:"flex items-start space-x-3",children:[t.jsx("div",{className:"flex-shrink-0 text-xl",children:d.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:`font-semibold ${d.title} mb-1`,children:o.title}),t.jsx("div",{className:`text-sm ${d.message} mb-2`,children:o.message}),o.suggestion&&t.jsxs("div",{className:`text-xs ${d.message} opacity-90`,children:["💡 ",o.suggestion]})]}),s&&t.jsx("button",{onClick:s,className:"flex-shrink-0 text-gray-400 hover:text-gray-600 transition-colors","aria-label":"Dismiss error",children:t.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:t.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})})]}),n&&t.jsxs("div",{className:"mt-3 flex justify-end space-x-2",children:[s&&"info"===i&&t.jsx("button",{onClick:s,className:"px-3 py-1.5 text-xs text-gray-600 hover:text-gray-800 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:n,className:`px-4 py-2 text-sm font-medium text-white rounded-md transition-colors ${d.button}`,children:c})]}),!1]})},En="method",Fn="confirm",Dn="processing",Un="success",Tn="wallet",Bn="qr",Rn="Bricolage Grotesque, sans-serif",Ln=new a.QueryClient,Mn=({publicKey:e,apiKey:a,apiSecret:o,apiUrl:i,config:c,onSuccess:l,onError:d,onClose:m,isOpen:u,theme:p="light"})=>{const y=((e,t,s)=>{const[a,r]=n.useState("method"),[o,i]=n.useState([]),[c,l]=n.useState([]),[d,m]=n.useState(null),[u,h]=n.useState(null),[p,y]=n.useState(null),[g,b]=n.useState(null),[x,w]=n.useState(!1),[v,k]=n.useState(""),[N,C]=n.useState(!1),[P,j]=n.useState("Processing transaction..."),[I,S]=n.useState("wallet"),[A,E]=n.useState(null),F=n.useRef(new f(e,t,s));return{currentStep:a,networks:o,tokens:c,selectedNetwork:d,selectedToken:u,paymentMethod:p,paymentData:g,loading:x,error:v,processing:N,processingMessage:P,paymentType:I,actualTransactionHash:A,setCurrentStep:r,setSelectedNetwork:m,setSelectedToken:h,setPaymentMethod:y,setError:k,setProcessing:C,setProcessingMessage:j,setPaymentType:S,setActualTransactionHash:E,loadData:async()=>{var e,t;try{w(!0),k("");const[n,s]=await Promise.all([F.current.getNetworks(),F.current.getTokens()]),a=(null==(e=n.networks)?void 0:e.reduce((e,t)=>{if("solana"===t.shortName||"tron"===t.shortName||"algorand"===t.shortName)return e;if(!t.chainId||null===t.chainId)return e;const n=`${t.chainId}-${t.shortName}`;return e.some(e=>`${e.chainId}-${e.shortName}`===n)||e.push(t),e},[]))||[],r=(null==(t=s.stablecoins)?void 0:t.reduce((e,t)=>{var n,s,a;if("USDC"!==t.symbol&&"USDT"!==t.symbol)return e;if("solana"===(null==(n=t.Network)?void 0:n.shortName)||"tron"===(null==(s=t.Network)?void 0:s.shortName)||"algorand"===(null==(a=t.Network)?void 0:a.shortName))return e;const r=`${t.symbol}-${t.networkId}`;return e.some(e=>`${e.symbol}-${e.networkId}`===r)||e.push(t),e},[]))||[];i(a),l(r)}catch(n){console.error("Failed to load data:",n),k("Failed to load payment options. Using fallback data.")}finally{w(!1)}},createPayment:async e=>{try{w(!0),k("");const t={amount:e.amount,currency:u.symbol,network:d.shortName,customerEmail:e.customerEmail,callbackUrl:e.callbackUrl,metadata:{...e.metadata,merchantWalletAddresses:e.merchantWalletAddresses,paymentMethod:p,selectedNetwork:d.shortName,selectedToken:u.symbol,wagmiEnabled:!0}},n=await F.current.createPayment(t);b(n.payment),r("confirm")}catch(t){console.error("Payment creation failed:",t),k(t.message)}finally{w(!1)}},failPayment:async(e="Payment cancelled by user")=>{if(null==g?void 0:g.id)try{await F.current.failPayment(g.id,e)}catch(t){console.error("❌ Failed to notify backend of payment cancellation:",t)}},resetState:()=>{r("method"),m(null),h(null),y(null),b(null),k(""),C(!1),E(null),S("wallet")},resetTransactionState:()=>{k(""),C(!1),E(null),r("confirm")},api:F.current}})(i,e||a,e?null:o),b=(()=>{const[e,t]=n.useState(null),[a,o]=n.useState(null),[i,c]=n.useState(""),{connect:l,connectors:d}=s.useConnect(),{isConnected:m,address:u,chain:h}=s.useAccount(),{switchChain:p}=s.useSwitchChain();return n.useEffect(()=>{o(m&&u?{account:u,chainId:null==h?void 0:h.id,walletType:e}:null)},[m,u,h,e]),{selectedWalletType:e,connectedWallet:a,connectionError:i,isConnected:m,address:u,chain:h,connectors:d,handleWalletSelection:e=>{t(e),c("")},connectWallet:async(e,t=null)=>{var n,s,a;if(!e)return c("Please select a wallet first"),!1;try{if(c(""),await l({connector:e}),t){const i=w(t.shortName),l=(null==(n=e.name)?void 0:n.toLowerCase())||"",d=l.includes("zerion")||l.includes("trust")||l.includes("rabby")?5e3:500;await new Promise(e=>setTimeout(e,d));const m=r.getAccount(g).chainId;if(i&&m!==i)try{await p({chainId:i}),await new Promise(e=>setTimeout(e,1e3))}catch(o){return console.error("❌ Network switch failed:",o),4001===o.code||(null==(s=o.message)?void 0:s.includes("User rejected"))?c("Network switch was cancelled by user"):(null==(a=o.message)?void 0:a.includes("Unrecognized chain ID"))?c(`${t.name} network is not added to your wallet. Please add it manually.`):c(`Failed to switch to ${t.name}. Please switch manually in your wallet.`),!1}}return!0}catch(i){return console.error(`${e.name} wallet connection failed:`,i),4001===i.code||i.message.includes("User rejected")||i.message.includes("rejected")?c("User cancelled the connection request"):c(`Failed to connect to ${e.name}. Please try again.`),!1}},disconnectWallet:()=>{o(null),t(null),c("")},switchChain:p,ensureCorrectNetwork:async e=>{var t,n;if(!e)return console.warn("⚠️ No network specified for verification"),!0;try{const a=w(e.shortName),o=r.getAccount(g).chainId;if(a&&o!==a)try{return await p({chainId:a}),await new Promise(e=>setTimeout(e,1e3)),!0}catch(s){return console.error("❌ Network switch failed:",s),4001===s.code||(null==(t=s.message)?void 0:t.includes("User rejected"))?c("Network switch was cancelled. Please switch to the correct network in your wallet."):(null==(n=s.message)?void 0:n.includes("Unrecognized chain ID"))?c(`${e.name} network is not added to your wallet. Please add it manually.`):c(`Failed to switch to ${e.name}. Please switch manually in your wallet.`),!1}return!0}catch(B){return console.error("❌ Network verification failed:",B),c("Failed to verify network. Please check your wallet connection."),!1}},clearError:()=>{c("")},setSelectedWalletType:t,connect:l}})(),[x,v]=n.useState("metamask"),[k,N]=n.useState(!1),[C,P]=n.useState(()=>!("undefined"==typeof window||!window.sessionStorage)&&"true"===sessionStorage.getItem("coinley_mobile_payment_started")),[j,I]=n.useState(!1);n.useEffect(()=>{N(xn())},[]);const{currentStep:S,networks:A,tokens:E,selectedNetwork:F,selectedToken:D,paymentData:U,loading:T,error:B,paymentType:R,loadData:L,createPayment:M,failPayment:$,resetState:G,setSelectedNetwork:O,setSelectedToken:z,setPaymentType:W,setCurrentStep:H,setError:q}=y,{connectedWallet:V,address:Q,connectWallet:Z,handleWalletSelection:K}=b,Y=dn(U,D,F,Q,y.api,b),{executePaymentTransaction:_,processFinalPayment:J,transactionStep:X,transactionError:ee,currentTransactionHash:te}=Y;n.useEffect(()=>{S===Un&&"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started")},[S]),n.useEffect(()=>{if(u){L(),G();const e=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%",document.body.style.overflow="hidden"}else{const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}return()=>{if(u){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}}},[u]),n.useEffect(()=>{if("processing"===X||"approve"===X||"splitPayment"===X){const e=setTimeout(()=>{console.warn("⚠️ Transaction timeout - resetting state"),q("Transaction timed out. Please try again."),H(Fn),Y.resetTransaction()},12e4);return()=>clearTimeout(e)}},[X]);const ne=async()=>{await $(),m()};return u?t.jsxs("div",{className:"fixed inset-0 z-50",children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 transition-opacity",onClick:ne,"aria-hidden":"true"}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsxs("div",{className:"relative pt-4 w-full max-w-md max-h-[90vh] mx-auto shadow-xl bg-gray-100 rounded-3xl flex flex-col overflow-hidden",style:{zIndex:52},children:[t.jsxs("div",{className:"flex-shrink-0 bg-white flex justify-between items-center mb-3 mr-3 ml-3 py-3 px-2 rounded-full",children:[t.jsxs("div",{className:"flex-1 flex items-center gap-2 px-4",children:[t.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",children:t.jsx("img",{src:h,alt:"Coinley"})}),t.jsx("span",{className:"text-base font-semibold text-gray-800",style:{fontFamily:Rn},children:"Payment Details"})]}),S!==Un&&S!==Dn&&t.jsx("button",{onClick:ne,className:"text-gray-500 hover:text-gray-700 focus:outline-none",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 mr-2",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),c&&S!==Un&&t.jsx("div",{className:"flex-shrink-0 mb-3 px-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-xs text-gray-600",children:"Total Amount"}),t.jsxs("div",{className:"text-3xl font-bold text-[#7042D2] mt-1 leading-tight tracking-tight",style:{fontFamily:Rn},children:["$",(se=c.amount,parseFloat(se).toFixed(2))]}),t.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"No additional fees"}),t.jsx("div",{className:"text-xs text-gray-600 mt-2",children:"Payment to:"}),t.jsxs("div",{className:"text-sm font-semibold mt-0.5 flex gap-1.5 items-center justify-center",style:{fontFamily:Rn},children:[t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M15.3 7.50065L15.8 10.0007H4.2L4.7 7.50065H15.3ZM16.6667 3.33398H3.33333V5.00065H16.6667V3.33398ZM16.6667 5.83398H3.33333L2.5 10.0007V11.6673H3.33333V16.6673H11.6667V11.6673H15V16.6673H16.6667V11.6673H17.5V10.0007L16.6667 5.83398ZM5 15.0007V11.6673H10V15.0007H5Z",fill:"#7042D2"})}),c.merchantName||"Merchant"]})]})}),t.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain",children:[t.jsx(un,{currentStep:S,targetStep:En,children:t.jsxs("div",{className:"pb-4 pt-3 px-5 bg-white rounded-t-2xl",children:[t.jsx("h3",{className:"font-semibold text-center mb-3 text-sm",style:{fontFamily:Rn},children:"Choose Payment Method"}),t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:Rn},children:"Select Network"}),t.jsx(mn,{options:A,value:(null==F?void 0:F.id)||"",onChange:e=>{const t=A.find(t=>t.id===e);O(t),z(null)},placeholder:"Choose your network...",renderOption:e=>{var n,s;const a="object"==typeof(r=e)&&(null==r?void 0:r.logo)?r.logo:"object"==typeof r&&(null==r?void 0:r.shortName)?yn[r.shortName.toLowerCase()]:"string"==typeof r?yn[r.toLowerCase()]:null;var r;return t.jsxs("div",{className:"flex items-center space-x-3",children:[a?t.jsx("img",{src:a,alt:e.name,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:a?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(n=e.shortName)?void 0:n.slice(0,2).toUpperCase()})}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-gray-800",children:e.name}),t.jsx("div",{className:"text-sm text-gray-500",children:null==(s=e.shortName)?void 0:s.toUpperCase()})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.shortName}`,disabled:T})]}),F&&t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:Rn},children:"Select Token"}),t.jsx(mn,{options:E.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==F?void 0:F.shortName)||e.networkId===(null==F?void 0:F.id)}),value:(null==D?void 0:D.id)||"",onChange:e=>{const t=E.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==F?void 0:F.shortName)||e.networkId===(null==F?void 0:F.id)}).find(t=>t.id===e);z(t)},placeholder:"Choose your token...",renderOption:e=>{var n,s;const a=fn(e.symbol);return t.jsxs("div",{className:"flex items-center space-x-3",children:[a?t.jsx("img",{src:a,alt:e.symbol,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:a?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(n=e.symbol)?void 0:n.slice(0,2)})}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name," (",e.symbol,")"]}),t.jsxs("div",{className:"text-sm text-gray-500",children:[(null==(s=e.Network)?void 0:s.name)||"Unknown Network",e.isStablecoin&&t.jsx("span",{className:"ml-2 text-green-600",children:"• Stablecoin"})]})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.symbol}`,disabled:T})]}),F&&D&&t.jsx("button",{onClick:()=>M(c),disabled:T,className:"w-full bg-[#7042D2] text-white py-4 px-4 rounded-xl hover:bg-[#5b34b1] disabled:opacity-50 font-semibold transition-all duration-200 shadow-lg hover:shadow-xl",style:{fontFamily:Rn},children:T?"Creating Payment...":"Continue"})]})}),t.jsx(un,{currentStep:S,targetStep:Fn,children:F&&D&&U&&t.jsxs("div",{className:"pb-4 pt-4 px-4 bg-white rounded-t-2xl",children:[!k&&t.jsx("div",{className:"mb-4",children:t.jsxs("div",{className:"flex border-b border-gray-200",children:[t.jsx("button",{onClick:()=>W(Tn),className:"py-3 px-6 text-sm font-semibold transition-all duration-200 "+(R===Tn?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:Rn},children:"Connect Wallet"}),t.jsx("button",{onClick:()=>W(Bn),className:"py-3 px-6 text-sm font-semibold transition-all duration-200 "+(R===Bn?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:Rn},children:"QR Code"})]})}),k?t.jsx(Sn,{paymentData:U,selectedToken:D,selectedNetwork:F,config:c,onPaymentStarted:e=>{P(!0),"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.setItem("coinley_mobile_payment_started","true"),e.walletName},onError:e=>{console.error("❌ Mobile payment error:",e),q(e)}}):R===Tn?t.jsx(jn,{selectedNetwork:F,onWalletSelect:K,onConnect:async e=>{await Z(e,F)},connectedWallet:V,loading:T}):null,R===Bn&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-2",children:[t.jsx("div",{className:"text-xs font-medium text-gray-600 mb-1.5 text-center",style:{fontFamily:Rn},children:"Optimize QR for:"}),t.jsx("div",{className:"flex gap-1.5 justify-center flex-wrap",children:[{id:"metamask",name:"MetaMask",icon:"🦊"},{id:"trust",name:"Trust",icon:"🛡️"},{id:"coinbase",name:"Coinbase",icon:"💙"}].map(e=>t.jsxs("button",{onClick:()=>v(e.id),className:"flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all duration-200 "+(x===e.id?"bg-[#7042D2] text-white shadow-md":"bg-gray-100 text-gray-700 hover:bg-gray-200"),style:{fontFamily:Rn},children:[t.jsx("span",{className:"text-sm",children:e.icon}),t.jsx("span",{children:e.name})]},e.id))})]}),t.jsx(Pn,{amount:(null==U?void 0:U.totalAmount)||(null==U?void 0:U.amount)||(null==c?void 0:c.amount),currency:null==D?void 0:D.symbol,network:null==F?void 0:F.shortName,theme:p,paymentData:U,config:c,selectedToken:D,selectedNetwork:F,preferredWallet:x,compact:!0})]}),(B||ee)&&t.jsx("div",{className:"mt-4",children:t.jsx(An,{error:ee||B,onRetry:()=>{q(""),Y.resetTransaction(),"error"===X&&V&&_()},onDismiss:()=>{q(""),Y.resetTransaction()},context:"payment"})}),t.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:()=>H(En),className:"w-full py-2.5 px-3 bg-gray-200 hover:bg-gray-300 text-[#7042D2] font-semibold rounded-xl transition-all duration-200 text-sm",style:{fontFamily:Rn},children:"Back"}),t.jsx("button",{type:"button",onClick:async()=>{var e,t,n,s,a,r,o,i,c,d;if(k&&C){if(!(null==U?void 0:U.id))return void q("Payment ID not found. Please refresh and try again.");try{I(!0),H(Dn),q("");const a=await y.api.checkPaymentStatus(U.id);if("completed"===(null==(e=a.payment)?void 0:e.status))H(Un),l&&l({paymentId:U.id,transactionHash:a.payment.transactionHash,paymentDetails:a.payment});else if("pending"===(null==(t=a.payment)?void 0:t.status)){const e=await y.api.verifyQRPayment(U.id);if(e.success&&e.verified)H(Un),l&&l({paymentId:U.id,transactionHash:null==(n=e.onChainData)?void 0:n.transactionHash,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";q(`${t}. Please complete the payment in your wallet and try again.`),H(Fn)}}else"failed"===(null==(s=a.payment)?void 0:s.status)?(q("Payment failed. Please try creating a new payment."),H(Fn)):(q("Payment not found. Please verify the payment ID and try again."),H(Fn))}catch(m){console.error("❌ Mobile payment verification failed:",m),q(`Verification failed: ${m.message}. Please ensure payment was completed and try again.`),H(Fn)}finally{I(!1)}}else if(R!==Bn){if(V&&Q)try{H(Dn),q("");const e=await _();e&&(q(""),Y.setTransactionError(""),H(Un),l&&l({paymentId:U.id,transactionHash:e,paymentDetails:U}))}catch(m){console.error("Transaction failed:",m),H(Fn),(null==(c=m.message)?void 0:c.includes("User rejected"))||(null==(d=m.message)?void 0:d.includes("User denied"))||4001===m.code||"ACTION_REJECTED"===m.code?q("Transaction was cancelled by user. Please try again."):q(m.message||"Transaction failed. Please try again."),Y.resetTransaction()}}else{if(!(null==U?void 0:U.id))return void q("Payment ID not found. Please refresh and try again.");try{H(Dn),q("");const e=await y.api.checkPaymentStatus(U.id);if("completed"===(null==(a=e.payment)?void 0:a.status))H(Un),l&&l({paymentId:U.id,transactionHash:e.payment.transactionHash,paymentDetails:e.payment});else if("pending"===(null==(r=e.payment)?void 0:r.status)){const e=await y.api.verifyQRPayment(U.id);if(e.success&&e.verified)H(Un),l&&l({paymentId:U.id,transactionHash:null==(o=e.onChainData)?void 0:o.transactionHash,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";q(`${t}. Please complete the payment and try again.`),H(Fn)}}else"failed"===(null==(i=e.payment)?void 0:i.status)?(q("Payment failed. Please try creating a new payment."),H(Fn)):(q("Payment not found. Please verify the payment ID and try again."),H(Fn))}catch(m){console.error("❌ QR payment verification failed:",m),q(`Verification failed: ${m.message}. Please ensure payment was completed and try again.`),H(Fn)}}},className:"bg-green-600 text-white w-full py-2.5 px-3 font-semibold rounded-xl hover:bg-green-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 text-sm",disabled:R===Tn&&!V&&!k||k&&!C||"processing"===X||j,style:{fontFamily:Rn},children:j?"Verifying...":"processing"===X?"Processing...":k&&C?"I Have Paid":k?"Select Wallet":R===Bn?"I Have Paid":"Pay Now"})]})]})}),t.jsx(un,{currentStep:S,targetStep:Dn,children:t.jsx(hn,{status:"processing",message:"approve"===X?"Approving token spending...":"splitPayment"===X?"Processing payment split...":te?"Confirming transaction on blockchain...":"Processing your payment...",theme:p,transactionHash:te,selectedNetwork:F})}),t.jsx(un,{currentStep:S,targetStep:Un,children:t.jsx(hn,{status:"success",message:"Payment completed successfully!",theme:p,payment:U,transactionHash:te||(null==U?void 0:U.transactionHash),selectedPaymentMethod:D,selectedNetwork:F,merchantName:(null==c?void 0:c.merchantName)||"Merchant",onClose:m})}),(B||ee)&&t.jsxs("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg mx-6 mb-4",children:[t.jsx("p",{className:"text-red-800 text-sm",children:B||ee}),t.jsx("button",{onClick:()=>{q(""),Y.setTransactionError("")},className:"mt-2 text-red-600 hover:text-red-800 text-xs underline",children:"Dismiss"})]})]}),S!==Un&&t.jsxs("div",{className:"text-center text-xs text-gray-500 flex items-center justify-center gap-1 py-6 bg-white rounded-b-3xl",style:{fontFamily:Rn},children:[t.jsxs("p",{children:["Powered by ",t.jsx("span",{className:"text-[#7042D2] font-semibold",children:"Coinley"})," - Multi-Wallet Support"]}),t.jsxs("svg",{className:"inline w-4 h-4 text-green-500 ml-1",fill:"none",stroke:"currentColor",strokeWidth:"2",viewBox:"0 0 24 24",children:[t.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M9 12l2 2 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]})})]}):null;var se},$n=e=>t.jsx(s.WagmiProvider,{config:g,children:t.jsx(a.QueryClientProvider,{client:Ln,children:t.jsx(Mn,{...e})})}),Gn=n.createContext(null),On=n.forwardRef(({customerEmail:e="",merchantName:t="",onSuccess:s,onError:a,onClose:r,theme:o="light",autoOpen:i=!1,testMode:c=!1,debug:l=!1,merchantWalletAddresses:d={}},m)=>{const u=n.useContext(Gn);if(!u)throw new Error("CoinleyCheckout must be used within a CoinleyProvider");const{openPayment:h,closePayment:p}=u,y=t=>{try{if(!t.amount||t.amount<=0)throw new Error("Amount must be greater than 0");const n={...t,customerEmail:t.customerEmail||e,merchantWalletAddresses:{...d,...t.merchantWalletAddresses},metadata:{...t.metadata,testMode:c,checkoutVersion:"1.0.0"}};h(n,{onSuccess:s,onError:a,onClose:r})}catch(n){console.error("Failed to open Coinley checkout:",n),a&&a(n)}},g=()=>{p()};return n.useImperativeHandle(m,()=>({open:y,close:g})),null});On.displayName="CoinleyCheckout";const zn={ethereum:_t,bsc:Ot,polygon:en,arbitrum:Lt,optimism:Xt,avalanche:Mt},Wn=[{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],type:"function"}];const Hn=new class{constructor(){this.clients=new Map}getClient(e){if(!this.clients.has(e)){const t=zn[e];if(!t)throw new Error(`Unsupported network: ${e}`);const n=c.createPublicClient({chain:t,transport:c.http()});this.clients.set(e,n)}return this.clients.get(e)}async checkNativeBalance(e,t){try{const n=this.getClient(t),s=await n.getBalance({address:e}),a=c.formatUnits(s,18);return{balance:parseFloat(a),balanceWei:s.toString(),symbol:this.getNativeTokenSymbol(t),decimals:18}}catch(n){throw console.error("❌ Failed to check native balance:",n),new Error(`Failed to check native balance: ${n.message}`)}}async checkTokenBalance(e,t,n){try{const s=this.getClient(n),a=c.getContract({address:t,abi:Wn,client:s}),[r,o,i]=await Promise.all([a.read.balanceOf([e]),a.read.decimals().catch(()=>18),a.read.symbol().catch(()=>"TOKEN")]);return{balance:parseFloat(c.formatUnits(r,o)),balanceWei:r.toString(),symbol:i,decimals:o,tokenAddress:t}}catch(s){throw console.error("❌ Failed to check token balance:",s),new Error(`Failed to check token balance: ${s.message}`)}}async validateBalance(e,t,n,s,a=!0){try{let r,o=null;r=t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,s):await this.checkNativeBalance(e,s),t.contractAddress&&a&&(o=await this.checkNativeBalance(e,s));const i=r.balance>=n,c=i?0:n-r.balance;let l=0,d=!0,m=0;if(a)if(l=this.estimateGasFee(s,!!t.contractAddress),t.contractAddress)d=o.balance>=l,m=d?0:l-o.balance;else{const e=n+l;d=r.balance>=e,m=d?0:e-r.balance}const u={isValid:i&&d,tokenBalance:r,nativeBalance:o,requiredAmount:n,estimatedGasFee:l,hasEnoughTokens:i,hasEnoughForGas:d,tokenShortfall:c,gasShortfall:m,errors:[]};if(i||u.errors.push(`Insufficient ${t.symbol} balance. Need ${n} ${t.symbol}, have ${r.balance.toFixed(6)} ${t.symbol}`),!d){const e=(null==o?void 0:o.symbol)||this.getNativeTokenSymbol(s);t.contractAddress?u.errors.push(`Insufficient ${e} for gas fees. Need ~${l.toFixed(6)} ${e}, have ${o.balance.toFixed(6)} ${e}`):u.errors.push(`Insufficient ${e} for payment + gas. Need ${(n+l).toFixed(6)} ${e} total, have ${r.balance.toFixed(6)} ${e}`)}return u}catch(r){return console.error("❌ Balance validation failed:",r),{isValid:!1,errors:[`Failed to check balance: ${r.message}`],tokenBalance:null,nativeBalance:null}}}estimateGasFee(e,t=!1){return{ethereum:t?.001:5e-4,bsc:t?5e-4:3e-4,polygon:t?.01:.005,arbitrum:t?3e-4:2e-4,optimism:t?3e-4:2e-4,avalanche:t?.001:5e-4}[e]||.001}getNativeTokenSymbol(e){return{ethereum:"ETH",bsc:"BNB",polygon:"MATIC",arbitrum:"ETH",optimism:"ETH",avalanche:"AVAX"}[e]||"ETH"}async getBalance(e,t,n){return t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,n):await this.checkNativeBalance(e,n)}formatBalance(e,t,n=6){return null==e?"Unknown":0===e?`0 ${t}`:e<.001?`${e.toFixed(8)} ${t}`:e<1?`${e.toFixed(6)} ${t}`:`${e.toFixed(4)} ${t}`}async checkMultipleBalances(e,t,n){try{const s=t.map(t=>this.getBalance(e,t,n).catch(e=>({error:e.message,symbol:t.symbol,balance:0})));return await Promise.all(s)}catch(s){throw console.error("❌ Failed to check multiple balances:",s),s}}};class qn{constructor(e,t,n){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,this.apiKey=t,this.apiSecret=n}async request(e,t={}){const n=`${this.baseURL}${e}`,s={"Content-Type":"application/json","X-API-Key":this.apiKey,"X-API-Secret":this.apiSecret,...t.headers},a=await fetch(n,{...t,headers:s});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.error||`HTTP ${a.status}`)}return a.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"},{id:"137",name:"Polygon",shortName:"polygon",chainId:"0x89",type:"polygon"},{id:"42161",name:"Arbitrum",shortName:"arbitrum",chainId:"0xa4b1",type:"arbitrum"},{id:"10",name:"Optimism",shortName:"optimism",chainId:"0xa",type:"optimism"},{id:"43114",name:"Avalanche",shortName:"avalanche",chainId:"0xa86a",type:"avalanche"},{id:"42220",name:"Celo",shortName:"celo",chainId:"0xa4ec",type:"celo"},{id:"8453",name:"Base",shortName:"base",chainId:"0x2105",type:"base"}]}}}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"}},{id:"2",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E641a3FA62e50A9da1CE0647a2bFBC5A",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"3",name:"Binance USD",symbol:"BUSD",contractAddress:"0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"4",name:"USD Coin",symbol:"USDC",contractAddress:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"5",name:"USD Coin",symbol:"USDC",contractAddress:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"6",name:"Tether USD",symbol:"USDT",contractAddress:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"7",name:"Tether USD",symbol:"USDT",contractAddress:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"8",name:"USD Coin",symbol:"USDC",contractAddress:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"9",name:"Tether USD",symbol:"USDT",contractAddress:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"10",name:"USD Coin",symbol:"USDC",contractAddress:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"11",name:"Tether USD",symbol:"USDT",contractAddress:"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"12",name:"USD Coin",symbol:"USDC",contractAddress:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"13",name:"Tether USD",symbol:"USDT",contractAddress:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"14",name:"USD Coin",symbol:"USDC",contractAddress:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"15",name:"Tether USD",symbol:"USDT",contractAddress:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}},{id:"16",name:"USD Coin",symbol:"USDC",contractAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}async updatePaymentStatus(e,t,n=null){return await this.request(`/api/payments/${e}/status`,{method:"PUT",body:JSON.stringify({status:t,transactionHash:n})})}}class Vn{constructor(e={}){if(!e.apiKey)throw new Error("CoinleyVanilla: apiKey is required");if(!e.apiSecret)throw new Error("CoinleyVanilla: apiSecret is required");if(!e.apiUrl)throw new Error("CoinleyVanilla: apiUrl is required");this.config={apiKey:e.apiKey,apiSecret:e.apiSecret,apiUrl:e.apiUrl.replace(/\/$/,""),theme:e.theme||"light",debug:e.debug||!1,...e},this.isOpen=!1,this.root=null,this.container=null,this.callbacks={},this.currentPayment=null,this.config.debug}open(e,t={}){if(this.isOpen)console.warn("⚠️ CoinleyVanilla: Payment modal is already open");else try{this._validatePaymentConfig(e),this.callbacks=t,this.currentPayment=e,this._createContainer(),this.root=u.createRoot(this.container),this.isOpen=!0,this.root.render(n.createElement($n,{apiKey:this.config.apiKey,apiSecret:this.config.apiSecret,apiUrl:this.config.apiUrl,isOpen:!0,theme:this.config.theme,config:{amount:e.amount,customerEmail:e.customerEmail,merchantName:e.merchantName||"Merchant",callbackUrl:e.callbackUrl||this._getDefaultCallbackUrl(),merchantWalletAddresses:e.merchantWalletAddresses||{},preferredNetwork:e.preferredNetwork,preferredCurrency:e.preferredCurrency,metadata:{...e.metadata,source:"vanilla-sdk",sdkVersion:"2.0.0",timestamp:(new Date).toISOString()}},onSuccess:this._handleSuccess.bind(this),onError:this._handleError.bind(this),onClose:this._handleClose.bind(this)})),this.config.debug}catch(s){console.error("❌ CoinleyVanilla: Failed to open payment modal",s),t.onError&&t.onError(s.message||"Failed to open payment modal")}}close(){this.isOpen&&(this._cleanup(),this.config.debug)}isPaymentOpen(){return this.isOpen}updateConfig(e){this.config={...this.config,...e},this.config.debug}getConfig(){return{...this.config}}getCurrentPayment(){return this.currentPayment?{...this.currentPayment}:null}_validatePaymentConfig(e){if(!e)throw new Error("Payment configuration is required");if(!e.amount||"number"!=typeof e.amount||e.amount<=0)throw new Error("Valid amount (number > 0) is required");if(!e.customerEmail||"string"!=typeof e.customerEmail)throw new Error("Customer email is required");if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.customerEmail))throw new Error("Invalid email format");if(e.merchantWalletAddresses){if("object"!=typeof e.merchantWalletAddresses)throw new Error("merchantWalletAddresses must be an object");0===Object.keys(e.merchantWalletAddresses).length&&console.warn("⚠️ CoinleyVanilla: No merchant wallet addresses provided. Networks will be fetched from backend.")}}_createContainer(){this.container||(this.container=document.createElement("div"),this.container.id="coinley-payment-container",this.container.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 999999;\n ",document.body.appendChild(this.container))}_getDefaultCallbackUrl(){return"undefined"!=typeof window?`${window.location.origin}/api/webhooks/coinley`:""}_handleSuccess(e,t,n){this.config.debug,this.callbacks.onSuccess&&this.callbacks.onSuccess(e,t,n)}_handleError(e){this.config.debug&&console.error("❌ CoinleyVanilla: Payment error",e),this.callbacks.onError&&this.callbacks.onError(e)}_handleClose(){this._cleanup(),this.callbacks.onClose&&this.callbacks.onClose()}_cleanup(){if(this.isOpen=!1,this.root){try{this.root.unmount()}catch(e){console.error("Error unmounting React root:",e)}this.root=null}this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null),this.currentPayment=null}}function Qn(){document.querySelectorAll('script[src*="coinley-vanilla"]').forEach(e=>{const t=e.getAttribute("data-api-key"),n=e.getAttribute("data-api-secret"),s=e.getAttribute("data-api-url"),a=e.getAttribute("data-theme")||"light",r=e.hasAttribute("data-debug");if(t&&n&&s)try{window.coinley=new Vn({apiKey:t,apiSecret:n,apiUrl:s,theme:a,debug:r})}catch(o){console.error("❌ Failed to auto-initialize Coinley SDK:",o)}})}"undefined"!=typeof window&&(window.CoinleyVanilla=Vn,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Qn):Qn());class Zn{constructor(e="https://paymentscreen.vercel.app/"){this.basePaymentUrl=e.endsWith("/")?e:e+"/"}generatePaymentURL(e){const{merchant:t,amount:n,productAmount:s,platformFee:a,networkFee:r,token:o="USDC",network:i="Ethereum Mainnet",merchantAddress:c}=e;if(!t)throw new Error("Merchant name is required");if(!n)throw new Error("Amount is required");if(!c)throw new Error("Merchant address (smart contract) is required");const l=s||.95*n,d=a||.03*n,m=r||.02*n,u=new URLSearchParams({merchant:t,amount:n.toString(),productAmount:l.toString(),platformFee:d.toString(),networkFee:m.toString(),token:o,network:i,merchantAddress:c});return this.basePaymentUrl+"?"+u.toString()}async generateQRCode(e,t={}){const{width:n=300,margin:s=2,colorDark:a="#7c3aed",colorLight:r="#ffffff"}=t;try{const t=this.generatePaymentURL(e);return{qrCodeDataURL:await d.toDataURL(t,{width:n,margin:s,color:{dark:a,light:r}}),paymentURL:t,paymentData:{...e,qrCodeUrl:t}}}catch(o){throw new Error(`Failed to generate QR code: ${o.message}`)}}async generateQRCodeToCanvas(e,t,n={}){const{width:s=300,margin:a=2,colorDark:r="#7c3aed",colorLight:o="#ffffff"}=n;try{const n=this.generatePaymentURL(e);return await d.toCanvas(t,n,{width:s,margin:a,color:{dark:r,light:o}}),n}catch(i){throw new Error(`Failed to generate QR code to canvas: ${i.message}`)}}validatePaymentData(e){const t=[],n=[];e.merchant||t.push("Merchant name is required"),(!e.amount||e.amount<=0)&&t.push("Valid amount is required"),e.merchantAddress||t.push("Merchant address (smart contract) is required"),e.merchantAddress&&!/^0x[a-fA-F0-9]{40}$/.test(e.merchantAddress)&&t.push("Invalid Ethereum address format for merchantAddress"),e.amount>1e4&&n.push("Large payment amount detected");return(e.platformFee||0)+(e.networkFee||0)>.1*e.amount&&n.push("High fees detected (>10% of total amount)"),{isValid:0===t.length,errors:t,warnings:n}}async createPaymentQR(e){const{merchantName:t,amount:n,productAmount:s,platformFee:a,networkFee:r,token:o,network:i,merchantWalletAddresses:c,selectedNetwork:l="ethereum",...d}=e,m={merchant:t||"Coinley Merchant",amount:n,productAmount:s,platformFee:a,networkFee:r,token:o||"USDC",network:i||"Ethereum Mainnet",merchantAddress:(null==c?void 0:c[l])||(null==c?void 0:c.ethereum)||(null==c?void 0:c.splitPaymentContract),...d},u=this.validatePaymentData(m);if(!u.isValid)throw new Error(`Payment validation failed: ${u.errors.join(", ")}`);return{...await this.generateQRCode(m),validation:u,instructions:{userAction:"Scan this QR code with your mobile wallet to pay",expectedFlow:"QR Scan → Payment Screen → Wallet Connect → Split Payment → Confirmation",supportedWallets:["MetaMask","Trust Wallet","Coinbase Wallet","WalletConnect compatible wallets"]}}}}const Kn=new Zn,Yn={formatAmount:(e,t=2)=>e.toFixed(t),truncateAddress:(e,t=6,n=4)=>e?e.length<=t+n?e:`${e.slice(0,t)}...${e.slice(-n)}`:"",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 _n extends Error{constructor(e,t){super(e),this.name="CoinleyError",this.code=t}}const Jn={react:'\nimport { CoinleyProvider, CoinleyCheckout } from \'coinley-test\';\n\n// New recommended way - using publicKey only\n<CoinleyProvider\n publicKey="pk_your-public-key"\n apiUrl="https://api.coinley.io"\n>\n <CoinleyCheckout\n ref={checkoutRef}\n onSuccess={(paymentId, txHash, details) => console.log(\'Success!\')}\n onError={(error) => console.error(\'Error:\', error)}\n onClose={() => console.log(\'Closed\')}\n />\n</CoinleyProvider>\n\n// Legacy way (still supported) - using apiKey + apiSecret\n<CoinleyProvider\n apiKey="your-api-key"\n apiSecret="your-api-secret"\n apiUrl="https://api.coinley.io"\n>\n ...\n</CoinleyProvider>\n ',vanilla:'\n\x3c!-- Include via CDN --\x3e\n<script src="https://unpkg.com/coinley-test@latest/vanilla"><\/script>\n<link rel="stylesheet" href="https://unpkg.com/coinley-test@latest/vanilla/style.css">\n\n<script>\n// New recommended way - using publicKey only\nconst coinley = new CoinleyVanilla({\n publicKey: "pk_your-public-key",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Legacy way (still supported)\nconst coinleyLegacy = new CoinleyVanilla({\n apiKey: "your-api-key",\n apiSecret: "your-api-secret",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Use in checkout\ncoinley.open({\n amount: 100,\n customerEmail: "customer@example.com",\n merchantName: "Your Store",\n merchantWalletAddresses: {\n ethereum: "0x...",\n bsc: "0x..."\n }\n}, {\n onSuccess: (paymentId, txHash, details) => console.log(\'Success!\'),\n onError: (error) => console.error(\'Error:\', error),\n onClose: () => console.log(\'Closed\')\n});\n<\/script>\n '};e.CoinleyCheckout=On,e.CoinleyError=_n,e.CoinleyProvider=({publicKey:e,apiKey:s,apiSecret:a,apiUrl:r,theme:o="light",debug:i=!1,children:c})=>{const[l,d]=n.useState(!1),[m,u]=n.useState(null),[h,p]=n.useState({}),[y,g]=n.useState(""),f=()=>{d(!1),u(null),h.onClose&&h.onClose()},b={openPayment:(e,t)=>{u(e),t&&p(t),d(!0)},closePayment:f};return t.jsxs(Gn.Provider,{value:b,children:[c,l&&m&&t.jsx($n,{publicKey:e,apiKey:s,apiSecret:a,apiUrl:r,isOpen:l,config:m,theme:o,debug:i,merchantName:y,onSuccess:h.onSuccess,onError:h.onError,onClose:f})]})},e.CoinleyVanilla=Vn,e.DEFAULT_CONFIG={theme:"light",debug:!1,testMode:!1,autoOpen:!1},e.EnhancedSimpleCoinleyPayment=$n,e.PaymentAPI=class{constructor(e,t,n=null){t&&t.startsWith("pk_")?(this.publicKey=t,this.apiKey=null,this.apiSecret=null):(this.publicKey=null,this.apiKey=t,this.apiSecret=n),this.api=m.create({baseURL:e.endsWith("/")?e.slice(0,-1):e,timeout:3e4,headers:{"Content-Type":"application/json"}}),this.api.interceptors.request.use(e=>{if(this.publicKey)e.headers["x-public-key"]=this.publicKey;else{e.headers["x-api-key"]=this.apiKey,e.headers["x-api-secret"]=this.apiSecret;const t=this.generateMerchantToken();t&&(e.headers.Authorization=`Bearer ${t}`)}return e},e=>(console.error("Request interceptor error:",e),Promise.reject(e))),this.api.interceptors.response.use(e=>e,e=>{var t,n,s,a,r;if(console.error("API Error:",{status:null==(t=e.response)?void 0:t.status,data:null==(n=e.response)?void 0:n.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==(a=e.response)?void 0:a.status))throw new Error("API endpoint not found. Please check your API URL.");if((null==(r=e.response)?void 0:r.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 request(e,t={}){var n,s;try{return(await this.api({url:e,method:t.method||"GET",data:t.data||t.body?JSON.parse(t.body||"{}"):void 0,...t})).data}catch(a){if(null==(s=null==(n=a.response)?void 0:n.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Request failed")}}async createPayment(e){var t,n;try{return(await this.api.post("/api/payments/create",e)).data}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to create payment")}}async getPayment(e){var t,n;try{return(await this.api.get(`/api/payments/${e}`)).data}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.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,n;try{return(await this.api.post("/api/payments/verify-qr",{paymentId:e})).data}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to verify payment")}}async processPayment(e,t,n,s){var a;try{return(await this.api.post("/api/payments/process",{paymentId:e,transactionHash:t,network:n,senderAddress:s})).data}catch(r){if(console.error("❌ PaymentAPI: PaymentSplitter transaction failed:",r),null==(a=r.response)?void 0:a.data){const e=r.response.data,t=e.error||e.message||"Payment processing failed",n=new Error(t);throw n.isAlreadyCompleted=e.isAlreadyCompleted||!1,n.verificationAttempts=e.verificationAttempts||0,n.statusCode=r.response.status,n.originalData=e,n}throw new Error(r.message||"Failed to process PaymentSplitter transaction")}}async getContractInfo(e){var t,n;try{return(await this.api.get(`/api/payments/contract/${e}`)).data.contractInfo}catch(s){if(console.error("❌ PaymentAPI: Failed to get contract info:",s),null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to get contract information")}}async getPaymentSplitterStatus(e){var t,n;try{return(await this.api.get(`/api/payments/splitter-status/${e}`)).data.paymentSplitterStatus}catch(s){if(console.error("❌ PaymentAPI: Failed to get PaymentSplitter status:",s),null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to get PaymentSplitter status")}}async checkPaymentSplitterHealth(){try{return(await this.api.get("/api/payments/health")).data.paymentSplitterHealth}catch(e){return console.error("PaymentSplitter health check failed:",e),{error:e.message}}}async healthCheck(){try{return 200===(await this.api.get("/api/health")).status}catch(e){return console.error("Health check failed:",e),!1}}},e.PaymentQRGenerator=Zn,e.QRCodePayment=({apiKey:e,apiSecret:s,apiUrl:a,config:r,onSuccess:o,onError:i,onClose:c,isOpen:l,theme:m="light",mode:u="splitpayment",splitPaymentUrl:h="https://paymentscreen.vercel.app/"})=>{var p;const[y,g]=n.useState("network"),[f,b]=n.useState([]),[x,w]=n.useState([]),[v,k]=n.useState(null),[N,C]=n.useState(null),[P,j]=n.useState(null),[I,S]=n.useState(!1),[A,E]=n.useState(""),[F,D]=n.useState(""),[U,T]=n.useState(""),[B,R]=n.useState(""),[L,M]=n.useState(!1),[$,G]=n.useState(""),[O,z]=n.useState(!1),[W,H]=n.useState(null),q=n.useRef(new qn(a,e,s)),V=n.useRef(null);n.useEffect(()=>(l&&(Z(),Q()),()=>{V.current&&clearInterval(V.current)}),[l]);const Q=()=>{g("network"),k(null),C(null),j(null),E(""),D(""),T(""),R(""),M(!1),G(""),z(!1),H(null),V.current&&clearInterval(V.current)},Z=async()=>{try{S(!0),E("");const[e,t]=await Promise.all([q.current.getNetworks(),q.current.getTokens()]);b(e.networks||[]),w(t.stablecoins||[])}catch(e){console.error("Failed to load data:",e),E("Failed to load payment options.")}finally{S(!1)}},K=async e=>{if(!N||!v||!P)return!1;try{const t=await Hn.validateBalance(e,N,P.totalAmount,v.shortName,!0);return H(t),!!t.isValid||(E(`Insufficient balance: ${t.errors.join(", ")}`),!1)}catch(t){return console.error("❌ QR balance check failed:",t),E(`Failed to check balance: ${t.message}`),!1}};if(!l)return null;const Y="dark"===m;return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:t.jsxs("div",{className:"rounded-lg shadow-xl max-w-md w-full mx-4 "+(Y?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[t.jsxs("div",{className:"p-4 border-b flex justify-between items-center "+(Y?"border-gray-700":"border-gray-200"),children:[t.jsxs("div",{className:"text-center flex-1",children:[t.jsx("h2",{className:"text-lg font-semibold",children:"splitpayment"===u?"Split Payment QR":"QR Code Payment"}),r.amount&&t.jsxs("p",{className:"text-2xl font-bold text-purple-600",children:["$",r.amount.toFixed(2)]}),t.jsx("p",{className:"text-xs text-blue-600",children:"splitpayment"===u?"📱 Scan to redirect to payment screen":"📱 Scan with mobile wallet"})]}),t.jsx("button",{onClick:c,className:"ml-4 text-gray-500 hover:text-gray-700 "+(Y?"hover:text-gray-300":""),children:"✕"})]}),t.jsxs("div",{className:"p-4 min-h-[400px]",children:[A&&t.jsxs("div",{className:"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200",children:[A,t.jsx("button",{onClick:()=>E(""),className:"ml-2 text-red-500 hover:text-red-700",children:"✕"})]}),"network"===y&&t.jsxs("div",{className:"space-y-4",children:[t.jsx("h3",{className:"font-medium text-center",children:"Select Network"}),t.jsx("div",{className:"space-y-2",children:f.map(e=>{var n;const s=null==(n=r.merchantWalletAddresses)?void 0:n[e.shortName];return t.jsxs("button",{onClick:()=>{k(e),g("token")},disabled:!s,className:"w-full p-3 border rounded-lg text-left transition-colors "+(s?"hover:border-purple-500 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"):"opacity-50 cursor-not-allowed "+(Y?"border-gray-700":"border-gray-100")),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsxs("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:[e.shortName.toUpperCase(),!s&&" (No merchant address configured)"]})]},e.id)})})]}),"token"===y&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("button",{onClick:()=>g("network"),className:""+(Y?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),t.jsxs("h3",{className:"font-medium",children:["Select Token on ",null==v?void 0:v.name]})]}),t.jsx("div",{className:"space-y-2",children:x.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==v?void 0:v.shortName)}).map(e=>t.jsxs("button",{onClick:()=>{C(e),(async e=>{var t,n;try{S(!0),E("");const s={amount:r.amount,currency:e.symbol,network:v.shortName,customerEmail:r.customerEmail,callbackUrl:r.callbackUrl,metadata:{...r.metadata,merchantWalletAddresses:r.merchantWalletAddresses,paymentMethod:"split_payment_qr",selectedNetwork:v.shortName,selectedToken:e.symbol}},a=await q.current.createPayment(s);j(a.payment);const o=(null==(t=r.merchantWalletAddresses)?void 0:t.splitPaymentContract)||(null==(n=r.merchantWalletAddresses)?void 0:n[v.shortName]);if(!o)throw new Error("Split payment contract address not found in config");const i=new URLSearchParams({merchant:r.merchantName||"Coinley Merchant",amount:a.payment.totalAmount.toString(),productAmount:(.95*a.payment.totalAmount).toFixed(2),platformFee:(.03*a.payment.totalAmount).toFixed(2),networkFee:(.02*a.payment.totalAmount).toFixed(2),token:e.symbol,network:v.name,merchantAddress:o,paymentId:a.payment.id}),c=h+"?"+i.toString();D(c);const l=await d.toDataURL(c,{width:256,margin:2,color:{dark:"#7c3aed",light:"#ffffff"}});T(l),g("scan")}catch(s){console.error("❌ Failed to generate split payment QR code:",s),E(s.message||"Failed to generate split payment QR code")}finally{S(!1)}})(e)},disabled:I,className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors disabled:opacity-50 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsx("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:e.symbol})]},e.id))})]}),"scan"===y&&t.jsx("div",{className:"space-y-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("h3",{className:"font-medium mb-4",children:"splitpayment"===u?"Scan QR Code to Open Payment Screen":"Scan QR Code with Mobile Wallet"}),U?t.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[t.jsx("div",{className:"p-4 rounded-lg "+(Y?"bg-gray-800":"bg-gray-50"),children:t.jsx("img",{src:U,alt:"Payment QR Code",className:"mx-auto",style:{width:"200px",height:"200px"}})}),t.jsxs("div",{className:"text-sm space-y-1 "+(Y?"text-gray-300":"text-gray-600"),children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Amount:"}),t.jsxs("span",{className:"font-medium",children:[null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Network:"}),t.jsx("span",{className:"font-medium",children:null==v?void 0:v.name})]}),"splitpayment"===u&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Merchant:"}),t.jsx("span",{className:"font-medium",children:r.merchantName||"Coinley Merchant"})]})]}),t.jsx("div",{className:"p-3 rounded-lg text-xs "+(Y?"bg-blue-900 text-blue-200":"bg-blue-50 text-blue-600"),children:"splitpayment"===u?t.jsxs(t.Fragment,{children:["📱 Scan this QR code with your mobile wallet to open the payment screen.",t.jsx("br",{}),"The payment screen will auto-connect your wallet and execute the split payment."]}):"📱 Open your mobile wallet and scan this QR code to connect and pay"}),"splitpayment"===u?t.jsx("button",{onClick:()=>window.open(F,"_blank"),className:"w-full bg-purple-600 text-white py-2 px-4 rounded hover:bg-purple-700 text-sm",children:"🔗 Test Payment Screen (Opens in new tab)"}):t.jsx("button",{onClick:async()=>{try{S(!0),E("");const e="0x742d35Cc6634C0532925a3b8D9a5C7C47C77E4";G(e),M(!0),await K(e),g("confirm")}catch(e){console.error("❌ Wallet simulation failed:",e),E("Failed to simulate wallet connection")}finally{S(!1)}},disabled:I,className:"w-full bg-gray-600 text-white py-2 px-4 rounded hover:bg-gray-700 disabled:opacity-50 text-sm",children:I?"Connecting...":"🧪 Simulate Wallet Scan (Test)"})]}):t.jsxs("div",{className:"flex items-center justify-center py-8",children:[t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"}),t.jsx("span",{className:"ml-2",children:"Generating QR Code..."})]})]})}),"confirm"===y&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4",children:t.jsx("span",{className:"text-2xl",children:"📱"})}),t.jsx("h3",{className:"font-medium",children:"Mobile Wallet Connected"}),t.jsx("p",{className:"text-sm mt-2 "+(Y?"text-gray-300":"text-gray-600"),children:"Ready to complete payment"})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-200",children:[t.jsx("p",{className:"text-green-600 text-sm font-medium",children:"✅ Wallet Connected"}),t.jsxs("p",{className:"font-mono text-xs text-green-700 mt-1",children:[null==$?void 0:$.slice(0,6),"...",null==$?void 0:$.slice(-4)]})]}),W&&t.jsx("div",{className:"p-3 rounded-lg border "+(W.isValid?"bg-green-50 border-green-200":"bg-red-50 border-red-200"),children:t.jsxs("div",{className:"space-y-2 text-sm",children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Required:"}),t.jsxs("span",{className:"font-medium",children:[null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Your Balance:"}),t.jsx("span",{className:"font-medium "+(W.hasEnoughTokens?"text-green-600":"text-red-600"),children:Hn.formatBalance(null==(p=W.tokenBalance)?void 0:p.balance,null==N?void 0:N.symbol)})]}),W.nativeBalance&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Gas Balance:"}),t.jsx("span",{className:"font-medium "+(W.hasEnoughForGas?"text-green-600":"text-red-600"),children:Hn.formatBalance(W.nativeBalance.balance,W.nativeBalance.symbol)})]})]})}),t.jsx("button",{onClick:async()=>{try{z(!0),E("");const e=`0x${Math.random().toString(16).substring(2,66)}`;await new Promise(e=>setTimeout(e,3e3)),g("success"),null==o||o(P.id,e,{network:v.name,token:N.symbol,amount:P.totalAmount,method:"qr_code",walletAddress:$})}catch(e){console.error("❌ QR transaction failed:",e),E("Transaction confirmation failed")}finally{z(!1)}},disabled:O||!(null==W?void 0:W.isValid),className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium",children:O?"Processing Payment...":(null==W?void 0:W.isValid)?`Confirm Payment of ${null==P?void 0:P.totalAmount} ${null==N?void 0:N.symbol}`:"Insufficient Balance"})]})]}),"success"===y&&t.jsxs("div",{className:"text-center space-y-4",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:t.jsx("span",{className:"text-2xl",children:"✅"})}),t.jsx("h3",{className:"font-medium text-green-600",children:"Payment Successful!"}),t.jsx("p",{className:"text-sm "+(Y?"text-gray-300":"text-gray-600"),children:"Transaction completed via QR code scan"}),t.jsx("button",{onClick:c,className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 font-medium",children:"Close"})]}),I&&"scan"!==y&&"confirm"!==y&&t.jsx("div",{className:"flex items-center justify-center py-8",children:t.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]=n.useState(e);return n.useEffect(()=>{document.documentElement.setAttribute("data-coinley-theme",a)},[a]),t.jsx("div",{className:`coinley-theme-${a}`,children:s})},e.USAGE_EXAMPLES=Jn,e.VERSION="0.0.26",e.generatePaymentQR=(e,t)=>Kn.generateQRCode(e,t),e.generatePaymentURL=e=>Kn.generatePaymentURL(e),e.paymentQR=Kn,e.useCoinley=()=>{const e=n.useContext(Gn);if(!e)throw new Error("useCoinley must be used within a CoinleyProvider");return e},e.utils=Yn,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("react"),require("wagmi"),require("@tanstack/react-query"),require("@wagmi/core"),require("@wagmi/core/chains"),require("@wagmi/connectors"),require("viem"),require("react-dom"),require("qrcode"),require("axios"),require("react-dom/client")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","react","wagmi","@tanstack/react-query","@wagmi/core","@wagmi/core/chains","@wagmi/connectors","viem","react-dom","qrcode","axios","react-dom/client"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CoinleyTest={},e.React,e.React,e.Wagmi,e.ReactQuery,e.WagmiCore,e.chains,e.connectors,e.Viem,e.ReactDOM,e.QRCode,e.axios,e.ReactDOM)}(this,function(e,t,n,s,a,r,i,o,c,l,d,m,u){"use strict";const h="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABxCAYAAAAj+QZ8AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAzrSURBVHgB7V3dcRs5Em4MtXWPq41gZ1+v7mwrgh3rArAUgagITNcFYDmAK9ERSBuBfQGsxY3Aku26V/MiOO7j1nqAQwMgRQ4xQONnhqOfr8q2TA4H1HzoRqO70c1g4JhUH/dhNKqgrhfT2cEMOoQaqxidyx+P5J8F8PpYjnkNPYLBgPGq+vxSFOJM/rhvXpp39ZAkGaUk40r+WK69jKT8JMdbQE8oYKDAByTJmMItGQj10OR7zyA3itFr2CQD1NhFMYYeMVhCHA8C1co7pV4yYXL4aSz/GVvfFFBBjxguIcCeOt4szYxOhiG2/V7M+T2yY7iEMOaTgIl8mBWkoth7Cduqah2u97JjuIQIUXqvYWlSohZyUEaDE/88/M+P0BMGrLIIYFAZ/R+HTGovJ+42IRqvYxZ485kKBob7QEgZZZoWoyMgrg//+vDX/0JPuA+ESLCXEApG/kxvm0LEkK2secDVZYjFpRZzIWibSyHm0COGSwjnYWoiyOIqjujXskcJUWCBqgItLuriPipOgAombqBH7EEGTKovUvz/xIdxnc8Rx8IdiHpxn7ouCVJXGnPIBD1h9p5BIU6kS6ZkBXt//uvf365fk0SIcvJJv5LUL6Wcdvq1w09z+c9MeknfSHLmEAteX8t7B30EBHsBHkLkPSsI+h482bOs3froERAT+UdLMcPlSch91M0P0w9Pz5bXpqksRcaW6Yj/H8v3vkpyLvRuOBzGxd6F2voZwpBEyKT6XMln8dF4BCzfjW2oz2hCjAu89FxmiPkctyNmMWprdOS5J11dSQsrVgXjxJAT8lyqp2aMpTnGxv1TJCRgdyzO5Jf7Giwtgv8GwWhfH5T0hK0fUQu6UeUf8UfvxY1Jl0LIHMJQBksL5zMIhXCqpLDAFpNrYSAwymnIKEkf4PUv6/+NJsQs2BHirKTlHUVaTAw9cB1xqaQijJDACYGTzUQ5adAqcbb+UuI+RPwCcTgyodjSe6UQ/4ZAtLrLi4DYhn5Y5DVscvjlguLK3xyDvWm+lEYI5+8hHiWJFMEvIRA1/3ZgfYMV9OgfYzPKZWrxfv5JLtx8DCFQhD+5bL6cRIgSN+IXb4GXlCi1VbQEt0IWdA40yRztXaG5DaEQ/Nj2crrrpP72BtJAkJRg1bhlAZr9Cc0y1LPXK/1KTYVZbcsB3rapw2RC1AwW0WvJEktS7A8sWDWyH61jkD/ul3q1xwhVUwj0HnN+1vZ2Huei4Ghvp/qwSumxfWd7I4NqRND3TdLt43rbmO7+PYYNgj93bTazEKIG4PUppELHyM+t76WrRhoEzFw+uMk/Ph0FW1O3N3/l8+9lc7/Lgd6jboR0TF5VNyeW++eQEj8EtKpf7SmGC4i78VvpRPTuUfLGQ1A3CpHkjEOIgk2ti3zXUtJiiq6gc38DXEar+15LMkgqLishSnWhOZce9tyX68mF5f4pUjL3XmHZqC1hVGkJocBnIdcN6uXZI4ZKR2obO22Rx/VE6esG6m+n/nsLW/jX/Rnp5GuTDpP7Fb6IGzJCPMadhHCVjc1rnBVppAg4b5rCinBeHzs/x7fd9uqhuNz59TfrPY3qDA8f3JIxD/lYZzH1TKRgztXEcu8ZWiztH6vtD17wlt23w/qxH1NwI5IMNRx0iDyk2POntMUiLDpftIeOOZ9ufxd5fYv1Y6RjDCFIIAPRywkq9YuxQvp8WAkxkKS2HWdT+VgFpvWw7zG24Dv2Jq8/kv6nl3rH7L4eQ9AQQojcw4BQJ7yiJ2AvhCAMKe+CQqgrKBs+bmecAIxyAlldKUk7g0R4s070ovpdadJ8DL6TM+DPoHizEeGDyeHNmZwHYYukiDA3E0HMGUAsD4fOIAP2LF/EnKtjGAqtQG2EOCzTfDT0/+UM0jFhte8QN+rnur526U+cRXIMuZ8oLgJUWG/nM9bg3wBqFXWalO7UwEplbeYORexGN+6qSLp26Wijws7ktf4sQvQvXT0hb65ywOw92twk0oSG0+mvfhd9KBQhLUeCc2EOjsQ5EjFc/vIul0YHUBOUFR8bUrxQ/jpprXV1VFoTcvgJ3d5H0D0uncRgEvSoeCGlqzIvL1xmaddYfScFft114QIEM9LxFfrFZXKq6T0FbgzT1os4YEbjR2lx9W7KDh3M1Pf4H+wKHVgqdxmFdpknx8TjgRkb1BytBwDtyxIq6N6J1UBEKd0Z7+ARmhDj0k53l6dAiGd6F/+wsfL2rjyzPR9y3ARhk3jPseF+V6RguHF3a0rZZxmLIaLV26uca9o7W0Kf4PUP0x4Lhg0NXve78ukI8boXYnbgsxoayPEQRQz6m27dGnmRGGm7LwgOUK38OwxO4oJNFjxuDldIihiazdwzGT+p1NkLnQlOdcUsVFY75+/7cNrdFWQP4Zq0nRI0MeiW2SSIq4yQxaM0POJOoCsJ0VJSjMqtC3g9x5j8dPa35Bzg+4hkQnSlAv7MxOCpiQGIOeQowXHPEEWIJkFgXZEx5ImnPAasDOj7kJxJEHagg/PgIe/SEbS8rGYlm26Aaw5meRzDA4ZTQizF8LvHA/dlWSVEp+aMLgTryE3iwKj4y/ew22DZTmHJXFQLNkbvdpH8ADX/43d4wNiIh7yqvpyY+k47IUPi8qEv6itCMP4hivC6IlnhOR/+EKAIMalAO04y8J/hfgjQEhJQdrsb7C5ddGjQi7oOPMFuICXjkYwVstTtjYKOEGJQarY6FKR8YsvSSgx37rOHpsZM9vvNNKqgfRxWKf2mqDCOW0G7ZTedfnjyCnYAU8zyRE6Mt31NDL2GpFWGo0IdLcA2dMCLmar8o01sXL9cZvaktSBN1xjt4bgTU4P4nFATOBnLzMWZ/YhxFqwRIc1q9FchEWFV2CZ9PIwtbJapnaiM/Rx9rxy4zVzUJ0hPM2UuGrVUP5fqRpXSZrB3Ysqnxh0M6rmfoML2uXZdaC22MDQBVueiOV+H8Y4K/Lv2hfkjg03YSYDPmuXrjMqZQBouJbnpNbkCoc612/Zo6oDrt+Pca4s/UW4zaWEdc/zLWexL9bHdu4qrS7gFJyE4VojbBR2o1IfpMHqyt4LtrHBABwdJrYTcdmhQ43iDXJbrvQ+05QDoGvLtpTqpddLNqV7xe8s46x0arMVqNrB1vf+w0KoOWGtYgJ3nWleyE2LUlK2NRRpsprmNdKHWvrbvZkvCsBZLa0JLkcsSxRLq6aTklxAsZ5RnzbiFpUa6+eXLrWtdSeGjkf29tmJpDZgKRI66kumkZCUkqXyqC42yfqZlats47VahcL5H2vipIjjOMoOq2UBkocyMhFD7ykahGSfRRcVaH177oR9nf13/+rMEVp9zF/scx5KST0K0Ps+PRh3dqKJiZLCXJCmhFfscx6ivLIS06vMcEFbp6Ar7VCkxxT49ZzLD15RkQjz6PA1aOmabY/mlo713LaV7KE1KEF2Qki4hHn2eBNEoX95Pu+39EL8ZlRRbtW4bkggxMzbOWeiFtZhl5f+YY7FVmfeUodkLCACFFFOt27sdSO1jWEEX0oH7jkb9QrNPKP0fdvaunQMFuh9iBQEgkLJP8QqkEcI6OOjfVprbsQPfgLt3Ldn5qI7pBSKAlNZJnEZI7h25uidvO/xJU428fdNmnI5zICEupL1GSpvqbO2Tgkjt9JlXXalSftsHQI36II7lXSeorvL92OjgihSA99YLVJ8Uu+XVU6dPAlx1FQty//OFNzbBxW9ARYTaWgKlUYYLjtsdkuLMRng8IUWLoy4UusL0gbPIJSt+Btq9CA87oPuzYLRxHdDGSUudep1EsYF4QqgmpAuqYICq3tD6kIL619JapdIJoXWf9kJ5iTHJo7nYW0pSpaislLDlQkXZrp74S2mMlGlNA6FVqmlb4b1uDVkMl7XFvlFpadMzkNILN/QX0xDq5O0BOeRJlY6QVqkhXaiLIgshCCRlevV0DJvZPUjGaow0sxe73VDThjQRz0lSsQ7q+hEyOYKaDjN6u1Yi5GJ/KScFtoc9bVqWGc6pOytTL1Lrmci4AlZM9etxDseU7pzB98WGXldPD6AnJCdbm9k+lsScgSpEY2qb6JomQR0Umghqlwr1DEKAXagpnoY+6oStIVv2uyFmDnlB1d/hR+GwCzUbUVw/+6E5XynotOVROogLKrWz8yZQgkkP2ZwM7gXDJoTSkJ7Y2bkJPeNpxT5r/sdP0BMGLiHMX6FUQHy7V+oxjFxeCcpQMGQwRljQ48+29NZfNwADlxAvLpOzz/vqQk3E3SYkw7n2oUnJsAkRwmEFiXzn/gYkJQOXEGFP51Eue07zhREwJCkZupVldxYWLH/VB1cXat5fdaJhE8JriwUl3nTRrk4T3Bbdq1NCDUEYNCFm87Z8SAtzUukMOoK94bHo7Yw6orMjbTmxDOD05U/SBz2l2wab3ncgjS78H0eagrHjdQciAAAAAElFTkSuQmCC",p="YWG990wOlIikc1tU7-WWTepfU8d1f4dp",y="qtIcCe_-8t4rIWktnWJm0",g=r.createConfig({chains:[i.mainnet,i.bsc,i.polygon,i.arbitrum,i.optimism,i.avalanche,i.celo,i.base],connectors:[o.injected(),o.metaMask({dappMetadata:{name:"Coinley Payment",icon:h}}),o.coinbaseWallet({appName:"Coinley Payment",appLogoUrl:h})],transports:{[i.mainnet.id]:r.fallback([r.http(`https://eth-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://eth-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://cloudflare-eth.com",{timeout:1e4,retryCount:1}),r.http("https://eth.llamarpc.com",{timeout:1e4,retryCount:1}),r.http("https://ethereum.publicnode.com",{timeout:1e4,retryCount:1})]),[i.bsc.id]:r.fallback([r.http(`https://bnb-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://bnb-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://bsc-dataseed.bnbchain.org",{timeout:1e4,retryCount:1}),r.http("https://bsc-dataseed-public.bnbchain.org",{timeout:1e4,retryCount:1}),r.http("https://bsc.nodereal.io",{timeout:1e4,retryCount:1})]),[i.polygon.id]:r.fallback([r.http(`https://polygon-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://polygon-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://polygon.llamarpc.com",{timeout:1e4,retryCount:1}),r.http("https://polygon-rpc.com",{timeout:1e4,retryCount:1}),r.http("https://polygon.drpc.org",{timeout:1e4,retryCount:1})]),[i.arbitrum.id]:r.fallback([r.http(`https://arb-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://arb-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://arb1.arbitrum.io/rpc",{timeout:1e4,retryCount:1}),r.http("https://arbitrum.llamarpc.com",{timeout:1e4,retryCount:1})]),[i.optimism.id]:r.fallback([r.http(`https://opt-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://opt-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://mainnet.optimism.io",{timeout:1e4,retryCount:1}),r.http("https://optimism.llamarpc.com",{timeout:1e4,retryCount:1})]),[i.avalanche.id]:r.fallback([r.http(`https://avax-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://avax-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://api.avax.network/ext/bc/C/rpc",{timeout:1e4,retryCount:1}),r.http("https://avalanche.public-rpc.com",{timeout:1e4,retryCount:1})]),[i.celo.id]:r.fallback([r.http(`https://celo-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://celo-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://forno.celo.org",{timeout:1e4,retryCount:1}),r.http("https://celo.drpc.org",{timeout:1e4,retryCount:1})]),[i.base.id]:r.fallback([r.http(`https://base-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://base-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://mainnet.base.org",{timeout:1e4,retryCount:1}),r.http("https://base.llamarpc.com",{timeout:1e4,retryCount:1}),r.http("https://base.meowrpc.com",{timeout:1e4,retryCount:1})])}});let f=class{constructor(e,t,n=null){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,t&&t.startsWith("pk_")?(this.publicKey=t,this.apiKey=null,this.apiSecret=null):(this.publicKey=null,this.apiKey=t,this.apiSecret=n)}async request(e,t={}){const n=`${this.baseURL}${e}`,s={"Content-Type":"application/json",...t.headers};this.publicKey?s["X-Public-Key"]=this.publicKey:(s["X-API-Key"]=this.apiKey,s["X-API-Secret"]=this.apiSecret);const a=t.timeout||6e4,r=new AbortController,i=setTimeout(()=>r.abort(),a);try{const e=await fetch(n,{...t,headers:s,signal:r.signal});if(clearTimeout(i),!e.ok){const t=await e.json().catch(()=>({}));throw new Error(t.error||`HTTP ${e.status}`)}return e.json()}catch(o){if(clearTimeout(i),"AbortError"===o.name)throw new Error(`Request timeout after ${a/1e3}s: ${e}`);throw o}}async getNetworks(){try{return await this.request("/api/networks")}catch(e){return{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"},{id:"137",name:"Polygon",shortName:"polygon",chainId:"0x89",type:"polygon"},{id:"42161",name:"Arbitrum",shortName:"arbitrum",chainId:"0xa4b1",type:"arbitrum"},{id:"10",name:"Optimism",shortName:"optimism",chainId:"0xa",type:"optimism"},{id:"43114",name:"Avalanche",shortName:"avalanche",chainId:"0xa86a",type:"avalanche"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(e){return{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"2",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"3",name:"Tether USD",symbol:"USDT",contractAddress:"0x55d398326f99059fF775485246999027B3197955",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"4",name:"USD Coin",symbol:"USDC",contractAddress:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"5",name:"Tether USD",symbol:"USDT",contractAddress:"0xc2132D05D31c914a87c6611C10748AEb04B58e8F",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"6",name:"USD Coin",symbol:"USDC",contractAddress:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"7",name:"Tether USD",symbol:"USDT",contractAddress:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"8",name:"USD Coin",symbol:"USDC",contractAddress:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"9",name:"Tether USD",symbol:"USDT",contractAddress:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"10",name:"USD Coin",symbol:"USDC",contractAddress:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"11",name:"Tether USD",symbol:"USDT",contractAddress:"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"12",name:"USD Coin",symbol:"USDC",contractAddress:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"13",name:"Tether USD",symbol:"USDT",contractAddress:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"14",name:"USD Coin",symbol:"USDC",contractAddress:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"15",name:"Tether USD",symbol:"USDT",contractAddress:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}},{id:"16",name:"USD Coin",symbol:"USDC",contractAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}async verifyQRPayment(e){return await this.request("/api/payments/verify-qr",{method:"POST",body:JSON.stringify({paymentId:e})})}async checkPaymentStatus(e){return await this.request(`/api/payments/status/${e}`)}async getContractInfo(e){try{const t=await this.request(`/api/payments/contract/${e}`);if(!t.success)throw new Error("Contract not supported on this network");return t.contractInfo}catch(t){throw new Error(t.message||"Failed to get contract information")}}async processPayment(e,t,n,s){try{return await this.request("/api/payments/process",{method:"POST",body:JSON.stringify({paymentId:e,transactionHash:t,network:n,senderAddress:s}),timeout:9e4})}catch(a){throw a}}async failPayment(e,t="Payment cancelled by user"){return await this.request("/api/payments/fail",{method:"POST",body:JSON.stringify({paymentId:e,reason:t,status:"failed"})})}};const b={ethereum:1,bsc:56,polygon:137,arbitrum:42161,optimism:10,avalanche:43114,celo:42220,base:8453},x=e=>"number"==typeof e?e:"string"==typeof e?e.startsWith("0x")?parseInt(e,16):parseInt(e,10):1,w=e=>b[e]||1;function v(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}const k="2.39.0";let N={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:n})=>t?`${e??"https://viem.sh"}${t}${n?`#${n}`:""}`:void 0,version:`viem@${k}`};class C extends Error{constructor(e,t={}){var n;const s=t.cause instanceof C?t.cause.details:(null==(a=t.cause)?void 0:a.message)?t.cause.message:t.details;var a;const r=t.cause instanceof C&&t.cause.docsPath||t.docsPath,i=null==(n=N.getDocsUrl)?void 0:n.call(N,{...t,docsPath:r});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...s?[`Details: ${s}`]:[],...N.version?[`Version: ${N.version}`]:[]].join("\n"),t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=k}walk(e){return P(this,e)}}function P(e,t){return(null==t?void 0:t(e))?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?P(e.cause,t):t?null:e}class j extends C{constructor({max:e,min:t,signed:n,size:s,value:a}){super(`Number "${a}" is not in safe ${s?`${8*s}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class I extends C{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function S(e,{strict:t=!0}={}){return!!e&&("string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")))}function A(e){return S(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function E(e,{dir:t="left"}={}){let n="string"==typeof e?e.replace("0x",""):e,s=0;for(let a=0;a<n.length-1&&"0"===n["left"===t?a:n.length-a-1].toString();a++)s++;return n="left"===t?n.slice(s):n.slice(0,n.length-s),"string"==typeof e?(1===n.length&&"right"===t&&(n=`${n}0`),`0x${n.length%2==1?`0${n}`:n}`):n}class F extends C{constructor({offset:e,position:t,size:n}){super(`Slice ${"start"===t?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}}class U extends C{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function D(e,{dir:t,size:n=32}={}){return"string"==typeof e?function(e,{dir:t,size:n=32}={}){if(null===n)return e;const s=e.replace("0x","");if(s.length>2*n)throw new U({size:Math.ceil(s.length/2),targetSize:n,type:"hex"});return`0x${s["right"===t?"padEnd":"padStart"](2*n,"0")}`}(e,{dir:t,size:n}):function(e,{dir:t,size:n=32}={}){if(null===n)return e;if(e.length>n)throw new U({size:e.length,targetSize:n,type:"bytes"});const s=new Uint8Array(n);for(let a=0;a<n;a++){const r="right"===t;s[r?a:n-a-1]=e[r?a:e.length-a-1]}return s}(e,{dir:t,size:n})}const T=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function B(e,t={}){return"number"==typeof e||"bigint"==typeof e?M(e,t):"string"==typeof e?function(e,t={}){const n=R.encode(e);return L(n,t)}(e,t):"boolean"==typeof e?function(e,t={}){const n=`0x${Number(e)}`;if("number"==typeof t.size)return q(n,{size:t.size}),D(n,{size:t.size});return n}(e,t):L(e,t)}function L(e,t={}){let n="";for(let a=0;a<e.length;a++)n+=T[e[a]];const s=`0x${n}`;return"number"==typeof t.size?(q(s,{size:t.size}),D(s,{dir:"right",size:t.size})):s}function M(e,t={}){const{signed:n,size:s}=t,a=BigInt(e);let r;s?r=n?(1n<<8n*BigInt(s)-1n)-1n:2n**(8n*BigInt(s))-1n:"number"==typeof e&&(r=BigInt(Number.MAX_SAFE_INTEGER));const i="bigint"==typeof r&&n?-r-1n:0;if(r&&a>r||a<i){const t="bigint"==typeof e?"n":"";throw new j({max:r?`${r}${t}`:void 0,min:`${i}${t}`,signed:n,size:s,value:`${e}${t}`})}const o=`0x${(n&&a<0?(1n<<BigInt(8*s))+BigInt(a):a).toString(16)}`;return s?D(o,{size:s}):o}const R=new TextEncoder;const $=new TextEncoder;function G(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){const n=M(e,t);return W(n)}(e,t):"boolean"==typeof e?function(e,t={}){const n=new Uint8Array(1);if(n[0]=Number(e),"number"==typeof t.size)return q(n,{size:t.size}),D(n,{size:t.size});return n}(e,t):S(e)?W(e,t):H(e,t)}const O={zero:48,nine:57,A:65,F:70,a:97,f:102};function z(e){return e>=O.zero&&e<=O.nine?e-O.zero:e>=O.A&&e<=O.F?e-(O.A-10):e>=O.a&&e<=O.f?e-(O.a-10):void 0}function W(e,t={}){let n=e;t.size&&(q(n,{size:t.size}),n=D(n,{dir:"right",size:t.size}));let s=n.slice(2);s.length%2&&(s=`0${s}`);const a=s.length/2,r=new Uint8Array(a);for(let i=0,o=0;i<a;i++){const e=z(s.charCodeAt(o++)),t=z(s.charCodeAt(o++));if(void 0===e||void 0===t)throw new C(`Invalid byte sequence ("${s[o-2]}${s[o-1]}" in "${s}").`);r[i]=16*e+t}return r}function H(e,t={}){const n=$.encode(e);return"number"==typeof t.size?(q(n,{size:t.size}),D(n,{dir:"right",size:t.size})):n}function q(e,{size:t}){if(A(e)>t)throw new I({givenSize:A(e),maxSize:t})}function V(e,t={}){const{signed:n}=t;t.size&&q(e,{size:t.size});const s=BigInt(e);if(!n)return s;const a=(e.length-2)/2;return s<=(1n<<8n*BigInt(a)-1n)-1n?s:s-BigInt(`0x${"f".padStart(2*a,"f")}`)-1n}function Q(e,t={}){return Number(V(e,t))}function K(e,t){return({exclude:n,format:s})=>({exclude:n,format:(e,a)=>{const r=t(e,a);if(n)for(const t of n)delete r[t];return{...r,...s(e,a)}},type:e})}const Z={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Y(e,t){const n={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?Q(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Q(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Z[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(n.authorizationList=e.authorizationList.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))),n.yParity=(()=>{if(e.yParity)return Number(e.yParity);if("bigint"==typeof n.v){if(0n===n.v||27n===n.v)return 0;if(1n===n.v||28n===n.v)return 1;if(n.v>=35n)return n.v%2n==0n?1:0}})(),"legacy"===n.type&&(delete n.accessList,delete n.maxFeePerBlobGas,delete n.maxFeePerGas,delete n.maxPriorityFeePerGas,delete n.yParity),"eip2930"===n.type&&(delete n.maxFeePerBlobGas,delete n.maxFeePerGas,delete n.maxPriorityFeePerGas),"eip1559"===n.type&&delete n.maxFeePerBlobGas,n}const _=K("transaction",Y);function J(e,t){const n=(e.transactions??[]).map(e=>"string"==typeof e?e:Y(e));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:n,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const X=K("block",J);const ee={"0x0":"reverted","0x1":"success"};function te(e,t){const n={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(e=>function(e,{args:t,eventName:n}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...n?{args:t,eventName:n}:{}}}(e)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Q(e.transactionIndex):null,status:e.status?ee[e.status]:null,type:e.type?Z[e.type]||e.type:null};return e.blobGasPrice&&(n.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(n.blobGasUsed=BigInt(e.blobGasUsed)),n}const ne=K("transactionReceipt",te),se={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function ae(e,t){const n={};return void 0!==e.authorizationList&&(n.authorizationList=e.authorizationList.map(e=>({address:e.address,r:e.r?M(BigInt(e.r)):e.r,s:e.s?M(BigInt(e.s)):e.s,chainId:M(e.chainId),nonce:M(e.nonce),...void 0!==e.yParity?{yParity:M(e.yParity)}:{},...void 0!==e.v&&void 0===e.yParity?{v:M(e.v)}:{}}))),void 0!==e.accessList&&(n.accessList=e.accessList),void 0!==e.blobVersionedHashes&&(n.blobVersionedHashes=e.blobVersionedHashes),void 0!==e.blobs&&("string"!=typeof e.blobs[0]?n.blobs=e.blobs.map(e=>L(e)):n.blobs=e.blobs),void 0!==e.data&&(n.data=e.data),e.account&&(n.from=e.account.address),void 0!==e.from&&(n.from=e.from),void 0!==e.gas&&(n.gas=M(e.gas)),void 0!==e.gasPrice&&(n.gasPrice=M(e.gasPrice)),void 0!==e.maxFeePerBlobGas&&(n.maxFeePerBlobGas=M(e.maxFeePerBlobGas)),void 0!==e.maxFeePerGas&&(n.maxFeePerGas=M(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=M(e.maxPriorityFeePerGas)),void 0!==e.nonce&&(n.nonce=M(e.nonce)),void 0!==e.to&&(n.to=e.to),void 0!==e.type&&(n.type=se[e.type]),void 0!==e.value&&(n.value=M(e.value)),n}const re=K("transactionRequest",ae);const ie=2n**256n-1n;function oe(e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}class ce extends C{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class le extends C{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}}class de extends C{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}}const me={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new de({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new le({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new ce({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new ce({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const n=t??this.position;return this.assertPosition(n+e-1),this.bytes.subarray(n,n+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,255&e),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const n=this.inspectBytes(e);return this.position+=t??e,n},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function ue(e,{recursiveReadLimit:t=8192}={}){const n=Object.create(me);return n.bytes=e,n.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),n.positionReadCount=new Map,n.recursiveReadLimit=t,n}function he(e,t="hex"){const n=pe(e),s=ue(new Uint8Array(n.length));return n.encode(s),"hex"===t?L(s.bytes):s.bytes}function pe(e){return Array.isArray(e)?function(e){const t=e.reduce((e,t)=>e+t.length,0),n=ye(t);return{length:t<=55?1+t:1+n+t,encode(s){t<=55?s.pushByte(192+t):(s.pushByte(247+n),1===n?s.pushUint8(t):2===n?s.pushUint16(t):3===n?s.pushUint24(t):s.pushUint32(t));for(const{encode:t}of e)t(s)}}}(e.map(e=>pe(e))):function(e){const t="string"==typeof e?W(e):e,n=ye(t.length),s=1===t.length&&t[0]<128?1:t.length<=55?1+t.length:1+n+t.length;return{length:s,encode(e){1===t.length&&t[0]<128?e.pushBytes(t):t.length<=55?(e.pushByte(128+t.length),e.pushBytes(t)):(e.pushByte(183+n),1===n?e.pushUint8(t.length):2===n?e.pushUint16(t.length):3===n?e.pushUint24(t.length):e.pushUint32(t.length),e.pushBytes(t))}}}(e)}function ye(e){if(e<256)return 1;if(e<65536)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new C("Length is too large.")}const ge={ether:-9,wei:9};function fe(e,t="wei"){return function(e,t){let n=e.toString();const s=n.startsWith("-");s&&(n=n.slice(1)),n=n.padStart(t,"0");let[a,r]=[n.slice(0,n.length-t),n.slice(n.length-t)];return r=r.replace(/(0+)$/,""),`${s?"-":""}${a||"0"}${r?`.${r}`:""}`}(e,ge[t])}function be(e){const t=Object.entries(e).map(([e,t])=>void 0===t||!1===t?null:[e,t]).filter(Boolean),n=t.reduce((e,[t])=>Math.max(e,t.length),0);return t.map(([e,t])=>` ${`${e}:`.padEnd(n+1)} ${t}`).join("\n")}class xe extends C{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class we extends C{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",be(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class ve extends C{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}function ke(e){const{kzg:t}=e,n=e.to??("string"==typeof e.blobs[0]?"hex":"bytes"),s="string"==typeof e.blobs[0]?e.blobs.map(e=>W(e)):e.blobs,a=[];for(const r of s)a.push(Uint8Array.from(t.blobToKzgCommitment(r)));return"bytes"===n?a:a.map(e=>L(e))}function Ne(e){const{kzg:t}=e,n=e.to??("string"==typeof e.blobs[0]?"hex":"bytes"),s="string"==typeof e.blobs[0]?e.blobs.map(e=>W(e)):e.blobs,a="string"==typeof e.commitments[0]?e.commitments.map(e=>W(e)):e.commitments,r=[];for(let i=0;i<s.length;i++){const e=s[i],n=a[i];r.push(Uint8Array.from(t.computeBlobKzgProof(e,n)))}return"bytes"===n?r:r.map(e=>L(e))}
|
|
2
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ce(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Pe(e,...t){if(!((n=e)instanceof Uint8Array||ArrayBuffer.isView(n)&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");var n;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function je(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ie(e,t){Pe(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Se(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ae(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ee(e,t){return e<<32-t|e>>>t}function Fe(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Ue=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=Fe(e[t]);return e};function De(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),Pe(e),e}class Te{}function Be(e){const t=t=>e().update(De(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Le(e,t,n){return e&t^~e&n}function Me(e,t,n){return e&t^e&n^t&n}class Re extends Te{constructor(e,t,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ae(this.buffer)}update(e){je(this),Pe(e=De(e));const{view:t,buffer:n,blockLen:s}=this,a=e.length;for(let r=0;r<a;){const i=Math.min(s-this.pos,a-r);if(i===s){const t=Ae(e);for(;s<=a-r;r+=s)this.process(t,r);continue}n.set(e.subarray(r,r+i),this.pos),this.pos+=i,r+=i,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){je(this),Ie(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:s,isLE:a}=this;let{pos:r}=this;t[r++]=128,Se(this.buffer.subarray(r)),this.padOffset>s-r&&(this.process(n,0),r=0);for(let d=r;d<s;d++)t[d]=0;!function(e,t,n,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,s);const a=BigInt(32),r=BigInt(4294967295),i=Number(n>>a&r),o=Number(n&r),c=s?4:0,l=s?0:4;e.setUint32(t+c,i,s),e.setUint32(t+l,o,s)}(n,s-8,BigInt(8*this.length),a),this.process(n,0);const i=Ae(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)i.setUint32(4*d,l[d],a)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:s,finished:a,destroyed:r,pos:i}=this;return e.destroyed=r,e.finished=a,e.length=s,e.pos=i,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const $e=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ge=BigInt(2**32-1),Oe=BigInt(32);function ze(e,t=!1){return t?{h:Number(e&Ge),l:Number(e>>Oe&Ge)}:{h:0|Number(e>>Oe&Ge),l:0|Number(e&Ge)}}const We=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),He=new Uint32Array(64);class qe extends Re{constructor(e=32){super(64,e,8,!1),this.A=0|$e[0],this.B=0|$e[1],this.C=0|$e[2],this.D=0|$e[3],this.E=0|$e[4],this.F=0|$e[5],this.G=0|$e[6],this.H=0|$e[7]}get(){const{A:e,B:t,C:n,D:s,E:a,F:r,G:i,H:o}=this;return[e,t,n,s,a,r,i,o]}set(e,t,n,s,a,r,i,o){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|s,this.E=0|a,this.F=0|r,this.G=0|i,this.H=0|o}process(e,t){for(let d=0;d<16;d++,t+=4)He[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){const e=He[d-15],t=He[d-2],n=Ee(e,7)^Ee(e,18)^e>>>3,s=Ee(t,17)^Ee(t,19)^t>>>10;He[d]=s+He[d-7]+n+He[d-16]|0}let{A:n,B:s,C:a,D:r,E:i,F:o,G:c,H:l}=this;for(let d=0;d<64;d++){const e=l+(Ee(i,6)^Ee(i,11)^Ee(i,25))+Le(i,o,c)+We[d]+He[d]|0,t=(Ee(n,2)^Ee(n,13)^Ee(n,22))+Me(n,s,a)|0;l=c,c=o,o=i,i=r+e|0,r=a,a=s,s=n,n=e+t|0}n=n+this.A|0,s=s+this.B|0,a=a+this.C|0,r=r+this.D|0,i=i+this.E|0,o=o+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,s,a,r,i,o,c,l)}roundClean(){Se(He)}destroy(){this.set(0,0,0,0,0,0,0,0),Se(this.buffer)}}const Ve=Be(()=>new qe);function Qe(e){const{commitment:t,version:n=1}=e,s=e.to??("string"==typeof t?"hex":"bytes"),a=Ve(S(r=t,{strict:!1})?G(r):r);var r;return a.set([n],0),"bytes"===s?a:L(a)}const Ke=4096,Ze=131072,Ye=761855;class _e extends C{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class Je extends C{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class Xe extends C{constructor({hash:e,size:t}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${t}`],name:"InvalidVersionedHashSizeError"})}}class et extends C{constructor({hash:e,version:t}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:["Expected: 1",`Received: ${t}`],name:"InvalidVersionedHashVersionError"})}}function tt(e){const{data:t,kzg:n,to:s}=e,a=e.blobs??function(e){const t=e.to??("string"==typeof e.data?"hex":"bytes"),n="string"==typeof e.data?W(e.data):e.data,s=A(n);if(!s)throw new Je;if(s>Ye)throw new _e({maxSize:Ye,size:s});const a=[];let r=!0,i=0;for(;r;){const e=ue(new Uint8Array(Ze));let t=0;for(;t<Ke;){const s=n.slice(i,i+31);if(e.pushByte(0),e.pushBytes(s),s.length<31){e.pushByte(128),r=!1;break}t++,i+=31}a.push(e)}return"bytes"===t?a.map(e=>e.bytes):a.map(e=>L(e.bytes))}({data:t,to:s}),r=e.commitments??ke({blobs:a,kzg:n,to:s}),i=e.proofs??Ne({blobs:a,commitments:r,kzg:n,to:s}),o=[];for(let c=0;c<a.length;c++)o.push({blob:a[c],commitment:r[c],proof:i[c]});return o}class nt extends C{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class st extends C{constructor({chainId:e}){super("number"==typeof e?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}class at extends C{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${fe(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(at,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class rt extends C{constructor({cause:e,maxPriorityFeePerGas:t,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${fe(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${fe(n)} gwei`:""}).`].join("\n"),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(rt,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class it extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const ot=BigInt(0),ct=BigInt(1),lt=BigInt(2),dt=BigInt(7),mt=BigInt(256),ut=BigInt(113),ht=[],pt=[],yt=[];for(let Xn=0,es=ct,ts=1,ns=0;Xn<24;Xn++){[ts,ns]=[ns,(2*ts+3*ns)%5],ht.push(2*(5*ns+ts)),pt.push((Xn+1)*(Xn+2)/2%64);let e=ot;for(let t=0;t<7;t++)es=(es<<ct^(es>>dt)*ut)%mt,es<&&(e^=ct<<(ct<<BigInt(t))-ct);yt.push(e)}const gt=function(e,t=!1){const n=e.length;let s=new Uint32Array(n),a=new Uint32Array(n);for(let r=0;r<n;r++){const{h:n,l:i}=ze(e[r],t);[s[r],a[r]]=[n,i]}return[s,a]}(yt,!0),ft=gt[0],bt=gt[1],xt=(e,t,n)=>n>32?((e,t,n)=>t<<n-32|e>>>64-n)(e,t,n):((e,t,n)=>e<<n|t>>>32-n)(e,t,n),wt=(e,t,n)=>n>32?((e,t,n)=>e<<n-32|t>>>64-n)(e,t,n):((e,t,n)=>t<<n|e>>>32-n)(e,t,n);class vt extends Te{constructor(e,t,n,s=!1,a=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.rounds=a,Ce(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var r;this.state=new Uint8Array(200),this.state32=(r=this.state,new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)))}clone(){return this._cloneInto()}keccak(){Ue(this.state32),function(e,t=24){const n=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let s=0;s<10;s++)n[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){const t=(s+8)%10,a=(s+2)%10,r=n[a],i=n[a+1],o=xt(r,i,1)^n[t],c=wt(r,i,1)^n[t+1];for(let n=0;n<50;n+=10)e[s+n]^=o,e[s+n+1]^=c}let t=e[2],a=e[3];for(let n=0;n<24;n++){const s=pt[n],r=xt(t,a,s),i=wt(t,a,s),o=ht[n];t=e[o],a=e[o+1],e[o]=r,e[o+1]=i}for(let s=0;s<50;s+=10){for(let t=0;t<10;t++)n[t]=e[s+t];for(let t=0;t<10;t++)e[s+t]^=~n[(t+2)%10]&n[(t+4)%10]}e[0]^=ft[s],e[1]^=bt[s]}Se(n)}(this.state32,this.rounds),Ue(this.state32),this.posOut=0,this.pos=0}update(e){je(this),Pe(e=De(e));const{blockLen:t,state:n}=this,s=e.length;for(let a=0;a<s;){const r=Math.min(t-this.pos,s-a);for(let t=0;t<r;t++)n[this.pos++]^=e[a++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,128&t&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){je(this,!1),Pe(e),this.finish();const t=this.state,{blockLen:n}=this;for(let s=0,a=e.length;s<a;){this.posOut>=n&&this.keccak();const r=Math.min(n-this.posOut,a-s);e.set(t.subarray(this.posOut,this.posOut+r),s),this.posOut+=r,s+=r}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ce(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ie(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Se(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:a,enableXOF:r}=this;return e||(e=new vt(t,n,s,r,a)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=a,e.suffix=n,e.outputLen=s,e.enableXOF=r,e.destroyed=this.destroyed,e}}const kt=(()=>{return e=1,t=136,n=32,Be(()=>new vt(t,e,n));var e,t,n})();const Nt=new it(8192);function Ct(e,t){if(Nt.has(`${e}.${t}`))return Nt.get(`${e}.${t}`);const n=e.substring(2).toLowerCase(),s=(a=H(n),kt(S(a,{strict:!1})?G(a):a));var a;const r=n.split("");for(let o=0;o<40;o+=2)s[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(15&s[o>>1])>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const i=`0x${r.join("")}`;return Nt.set(`${e}.${t}`,i),i}const Pt=/^0x[a-fA-F0-9]{40}$/,jt=new it(8192);function It(e,t){const{strict:n=!0}=t??{},s=`${e}.${n}`;if(jt.has(s))return jt.get(s);const a=!(!Pt.test(e)||e.toLowerCase()!==e&&n&&Ct(e)!==e);return jt.set(s,a),a}function St(e,t,n,{strict:s}={}){return S(e,{strict:!1})?function(e,t,n,{strict:s}={}){const a=`0x${e.replace("0x","").slice(2*t,2*n)}`;s&&At(a,t,n);return a}(e,t,n,{strict:s}):function(e,t,n,{strict:s}={}){const a=e.slice(t,n);s&&At(a,t,n);return a}(e,t,n,{strict:s})}function At(e,t,n){if(A(e)!==n-t)throw new F({offset:n,position:"end",size:A(e)})}function Et(e){const{chainId:t,maxPriorityFeePerGas:n,maxFeePerGas:s,to:a}=e;if(t<=0)throw new st({chainId:t});if(a&&!It(a))throw new nt({address:a});if(s&&s>ie)throw new at({maxFeePerGas:s});if(n&&s&&n>s)throw new rt({maxFeePerGas:s,maxPriorityFeePerGas:n})}function Ft(e){if(!e||0===e.length)return[];const t=[];for(let n=0;n<e.length;n++){const{address:s,storageKeys:a}=e[n];for(let e=0;e<a.length;e++)if(a[e].length-2!=64)throw new ve({storageKey:a[e]});if(!It(s,{strict:!1}))throw new nt({address:s});t.push([s,a])}return t}function Ut(e,t){const n=function(e){if(e.type)return e.type;if(void 0!==e.authorizationList)return"eip7702";if(void 0!==e.blobs||void 0!==e.blobVersionedHashes||void 0!==e.maxFeePerBlobGas||void 0!==e.sidecars)return"eip4844";if(void 0!==e.maxFeePerGas||void 0!==e.maxPriorityFeePerGas)return"eip1559";if(void 0!==e.gasPrice)return void 0!==e.accessList?"eip2930":"legacy";throw new we({transaction:e})}(e);return"eip1559"===n?function(e,t){const{chainId:n,gas:s,nonce:a,to:r,value:i,maxFeePerGas:o,maxPriorityFeePerGas:c,accessList:l,data:d}=e;Et(e);const m=Ft(l),u=[M(n),a?M(a):"0x",c?M(c):"0x",o?M(o):"0x",s?M(s):"0x",r??"0x",i?M(i):"0x",d??"0x",m,...Dt(e,t)];return oe(["0x02",he(u)])}(e,t):"eip2930"===n?function(e,t){const{chainId:n,gas:s,data:a,nonce:r,to:i,value:o,accessList:c,gasPrice:l}=e;!function(e){const{chainId:t,maxPriorityFeePerGas:n,gasPrice:s,maxFeePerGas:a,to:r}=e;if(t<=0)throw new st({chainId:t});if(r&&!It(r))throw new nt({address:r});if(n||a)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(s&&s>ie)throw new at({maxFeePerGas:s})}(e);const d=Ft(c),m=[M(n),r?M(r):"0x",l?M(l):"0x",s?M(s):"0x",i??"0x",o?M(o):"0x",a??"0x",d,...Dt(e,t)];return oe(["0x01",he(m)])}(e,t):"eip4844"===n?function(e,t){const{chainId:n,gas:s,nonce:a,to:r,value:i,maxFeePerBlobGas:o,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:d,data:m}=e;!function(e){const{blobVersionedHashes:t}=e;if(t){if(0===t.length)throw new Je;for(const e of t){const t=A(e),n=Q(St(e,0,1));if(32!==t)throw new Xe({hash:e,size:t});if(1!==n)throw new et({hash:e,version:n})}}Et(e)}(e);let u=e.blobVersionedHashes,h=e.sidecars;if(e.blobs&&(void 0===u||void 0===h)){const t="string"==typeof e.blobs[0]?e.blobs:e.blobs.map(e=>L(e)),n=e.kzg,s=ke({blobs:t,kzg:n});if(void 0===u&&(u=function(e){const{commitments:t,version:n}=e,s=e.to??("string"==typeof t[0]?"hex":"bytes"),a=[];for(const r of t)a.push(Qe({commitment:r,to:s,version:n}));return a}({commitments:s})),void 0===h){h=tt({blobs:t,commitments:s,proofs:Ne({blobs:t,commitments:s,kzg:n})})}}const p=Ft(d),y=[M(n),a?M(a):"0x",l?M(l):"0x",c?M(c):"0x",s?M(s):"0x",r??"0x",i?M(i):"0x",m??"0x",p,o?M(o):"0x",u??[],...Dt(e,t)],g=[],f=[],b=[];if(h)for(let x=0;x<h.length;x++){const{blob:e,commitment:t,proof:n}=h[x];g.push(e),f.push(t),b.push(n)}return oe(["0x03",he(h?[y,g,f,b]:y)])}(e,t):"eip7702"===n?function(e,t){const{authorizationList:n,chainId:s,gas:a,nonce:r,to:i,value:o,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:d,data:m}=e;!function(e){const{authorizationList:t}=e;if(t)for(const n of t){const{chainId:e}=n,t=n.address;if(!It(t))throw new nt({address:t});if(e<0)throw new st({chainId:e})}Et(e)}(e);const u=Ft(d),h=function(e){if(!e||0===e.length)return[];const t=[];for(const n of e){const{chainId:e,nonce:s,...a}=n,r=n.address;t.push([e?B(e):"0x",r,s?B(s):"0x",...Dt({},a)])}return t}(n);return oe(["0x04",he([M(s),r?M(r):"0x",l?M(l):"0x",c?M(c):"0x",a?M(a):"0x",i??"0x",o?M(o):"0x",m??"0x",u,h,...Dt(e,t)])])}(e,t):function(e,t){const{chainId:n=0,gas:s,data:a,nonce:r,to:i,value:o,gasPrice:c}=e;!function(e){const{chainId:t,maxPriorityFeePerGas:n,gasPrice:s,maxFeePerGas:a,to:r}=e;if(r&&!It(r))throw new nt({address:r});if(void 0!==t&&t<=0)throw new st({chainId:t});if(n||a)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(s&&s>ie)throw new at({maxFeePerGas:s})}(e);let l=[r?M(r):"0x",c?M(c):"0x",s?M(s):"0x",i??"0x",o?M(o):"0x",a??"0x"];if(t){const e=(()=>{if(t.v>=35n){return(t.v-35n)/2n>0?t.v:27n+(35n===t.v?0n:1n)}if(n>0)return BigInt(2*n)+BigInt(35n+t.v-27n);const e=27n+(27n===t.v?0n:1n);if(t.v!==e)throw new xe({v:t.v});return e})(),s=E(t.r),a=E(t.s);l=[...l,M(e),"0x00"===s?"0x":s,"0x00"===a?"0x":a]}else n>0&&(l=[...l,M(n),"0x","0x"]);return he(l)}(e,t)}function Dt(e,t){const n=t??e,{v:s,yParity:a}=n;if(void 0===n.r)return[];if(void 0===n.s)return[];if(void 0===s&&void 0===a)return[];const r=E(n.r),i=E(n.s);return["number"==typeof a?a?M(1):"0x":0n===s?"0x":1n===s?M(1):27n===s?"0x":M(1),"0x00"===r?"0x":r,"0x00"===i?"0x":i]}const Tt={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}};function Bt(e,t){return function(e){return"deposit"===e.type||void 0!==e.sourceHash}(e)?function(e){!function(e){const{from:t,to:n}=e;if(t&&!It(t))throw new nt({address:t});if(n&&!It(n))throw new nt({address:n})}(e);const{sourceHash:t,data:n,from:s,gas:a,isSystemTx:r,mint:i,to:o,value:c}=e;return oe(["0x7e",he([t,s,o??"0x",i?B(i):"0x",c?B(c):"0x",a?B(a):"0x",r?"0x1":"0x",n??"0x"])])}(e):Ut(e,t)}const Lt={blockTime:2e3,contracts:Tt,formatters:{block:X({format(e){var t;return{transactions:null==(t=e.transactions)?void 0:t.map(e=>{if("string"==typeof e)return e;const t=Y(e);return"0x7e"===t.typeHex&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?V(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}),stateRoot:e.stateRoot}}}),transaction:_({format(e){const t={};return"0x7e"===e.type&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?V(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:ne({format:e=>({l1GasPrice:e.l1GasPrice?V(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?V(e.l1GasUsed):null,l1Fee:e.l1Fee?V(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null})})},serializers:{transaction:Bt}},Mt=v({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:250,rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),Rt=v({id:43114,name:"Avalanche",blockTime:1700,nativeCurrency:{decimals:18,name:"Avalanche",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax.network/ext/bc/C/rpc"]}},blockExplorers:{default:{name:"SnowTrace",url:"https://snowtrace.io",apiUrl:"https://api.snowtrace.io"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:11907934}}}),$t=1,Gt=v({...Lt,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...Lt.contracts,disputeGameFactory:{[$t]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[$t]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[$t]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[$t]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:1}),Ot=v({id:56,name:"BNB Smart Chain",blockTime:750,nativeCurrency:{decimals:18,name:"BNB",symbol:"BNB"},rpcUrls:{default:{http:["https://56.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com",apiUrl:"https://api.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:15921452}}}),zt={estimateFeesPerGas:async e=>{var t;if(!(null==(t=e.request)?void 0:t.feeCurrency))return null;const[n,s]=await Promise.all([Wt(e.client,e.request.feeCurrency),Ht(e.client,e.request.feeCurrency)]);return{maxFeePerGas:e.multiply(n-s)+s,maxPriorityFeePerGas:s}}};async function Wt(e,t){const n=await e.request({method:"eth_gasPrice",params:[t]});return BigInt(n)}async function Ht(e,t){const n=await e.request({method:"eth_maxPriorityFeePerGas",params:[t]});return BigInt(n)}function qt(e){return 0===e||0n===e||null==e||"0"===e||""===e||"string"==typeof e&&("0x"===E(e).toLowerCase()||"0x00"===E(e).toLowerCase())}function Vt(e){return!qt(e)}function Qt(e){return"cip64"===e.type||function(e){return void 0!==e.maxFeePerGas&&void 0!==e.maxPriorityFeePerGas}(e)&&Vt(e.feeCurrency)}const Kt={transaction:function(e,t){return Qt(e)?function(e,t){!function(e){const{chainId:t,maxPriorityFeePerGas:n,gasPrice:s,maxFeePerGas:a,to:r,feeCurrency:i}=e;if(t<=0)throw new st({chainId:t});if(r&&!It(r))throw new nt({address:r});if(s)throw new C("`gasPrice` is not a valid CIP-64 Transaction attribute.");if(Vt(a)&&a>Zt)throw new at({maxFeePerGas:a});if(Vt(n)&&Vt(a)&&n>a)throw new rt({maxFeePerGas:a,maxPriorityFeePerGas:n});if(Vt(i)&&!It(i))throw new C("`feeCurrency` MUST be a token address for CIP-64 transactions.");if(qt(i))throw new C("`feeCurrency` must be provided for CIP-64 transactions.")}(e);const{chainId:n,gas:s,nonce:a,to:r,value:i,maxFeePerGas:o,maxPriorityFeePerGas:c,accessList:l,feeCurrency:d,data:m}=e,u=[B(n),a?B(a):"0x",c?B(c):"0x",o?B(o):"0x",s?B(s):"0x",r??"0x",i?B(i):"0x",m??"0x",Ft(l),d,...Dt(e,t)];return oe(["0x7b",he(u)])}(e,t):Bt(e,t)}};const Zt=ie;const Yt=v({...{blockTime:1e3,contracts:Tt,formatters:{block:X({format(e){var t;return{transactions:null==(t=e.transactions)?void 0:t.map(e=>{if("string"==typeof e)return e;return{...Y(e),...e.gatewayFee?{gatewayFee:V(e.gatewayFee),gatewayFeeRecipient:e.gatewayFeeRecipient}:{},feeCurrency:e.feeCurrency}})}}}),transaction:_({format(e){if("0x7e"===e.type)return{isSystemTx:e.isSystemTx,mint:e.mint?V(e.mint):void 0,sourceHash:e.sourceHash,type:"deposit"};const t={feeCurrency:e.feeCurrency};return"0x7b"===e.type?t.type="cip64":("0x7c"===e.type&&(t.type="cip42"),t.gatewayFee=e.gatewayFee?V(e.gatewayFee):null,t.gatewayFeeRecipient=e.gatewayFeeRecipient),t}}),transactionRequest:re({format(e){const t={};return e.feeCurrency&&(t.feeCurrency=e.feeCurrency),Qt(e)&&(t.type="0x7b"),t}})},serializers:Kt,fees:zt},id:42220,name:"Celo",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://forno.celo.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://celoscan.io",apiUrl:"https://api.celoscan.io/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:13112599}},testnet:!1}),_t=v({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),Jt=1,Xt=v({...Lt,id:10,name:"OP Mainnet",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.optimism.io"]}},blockExplorers:{default:{name:"Optimism Explorer",url:"https://optimistic.etherscan.io",apiUrl:"https://api-optimistic.etherscan.io/api"}},contracts:{...Lt.contracts,disputeGameFactory:{[Jt]:{address:"0xe5965Ab5962eDc7477C8520243A95517CD252fA9"}},l2OutputOracle:{[Jt]:{address:"0xdfe97868233d1aa22e815a266982f2cf17685a27"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:4286263},portal:{[Jt]:{address:"0xbEb5Fc579115071764c7423A4f12eDde41f106Ed"}},l1StandardBridge:{[Jt]:{address:"0x99C9fc46f92E8a1c0deC1b1747d010903E884bE1"}}},sourceId:1}),en=v({id:137,name:"Polygon",blockTime:2e3,nativeCurrency:{name:"POL",symbol:"POL",decimals:18},rpcUrls:{default:{http:["https://polygon-rpc.com"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://polygonscan.com",apiUrl:"https://api.polygonscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:25770160}}}),tn=(e,t,n=!1)=>{if(!e||"string"!=typeof e)throw new Error(`Missing ${t} address`);if(!e.startsWith("0x"))throw new Error(`Invalid ${t} address format: must start with 0x`);if(42!==e.length)throw new Error(`Invalid ${t} address length: expected 42 characters, got ${e.length}`);if("0x0000000000000000000000000000000000000000"===e&&!n)throw new Error(`Invalid ${t} address: cannot be zero address`)},nn=e=>{const t=(e=>{tn(e.token,"token"),tn(e.recipient1,"recipient1"),tn(e.recipient2,"recipient2");const t=0n===BigInt(e.recipient3Percentage||0);if(tn(e.recipient3,"recipient3",t),!e.paymentId||"string"!=typeof e.paymentId||0===e.paymentId.length)throw new Error("Invalid payment ID: must be a non-empty string");let n,s,a,r;try{n=BigInt(e.amount||0),s=BigInt(e.recipient1Percentage||0),a=BigInt(e.recipient2Percentage||0),r=BigInt(e.recipient3Percentage||0)}catch(o){throw new Error("Invalid numeric values: cannot convert to BigInt")}if(n<=0n)throw new Error(`Invalid amount: ${e.amount} (must be greater than 0)`);const i=s+a+r;if(10000n!==i)throw new Error(`Invalid percentages: total is ${i} but must equal 10000 basis points (100%). Individual: ${s}, ${a}, ${r}`);return{amount:n,percentage1:s,percentage2:a,percentage3:r}})(e);return{token:e.token,amount:t.amount,paymentId:e.paymentId,recipient1:e.recipient1,recipient2:e.recipient2,recipient3:e.recipient3,recipient1Percentage:t.percentage1,recipient2Percentage:t.percentage2,recipient3Percentage:t.percentage3}},sn=[{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[],payable:!1,stateMutability:"nonpayable",type:"function"}],an=[{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"}],rn=e=>{var t,n;const s=(null==(t=null==e?void 0:e.message)?void 0:t.toLowerCase())||(null==(n=null==e?void 0:e.toString())?void 0:n.toLowerCase())||"",a=(null==e?void 0:e.code)||(null==e?void 0:e.reason)||"";return s.includes("user rejected")||s.includes("user denied")||s.includes("user cancelled")||s.includes("rejected by user")||4001===a||"ACTION_REJECTED"===a?{type:"user_rejected",title:"Transaction Cancelled",message:"You cancelled the transaction. No charges were made.",suggestion:'Click "Pay Now" to try again when you\'re ready.'}:s.includes("insufficient funds")||s.includes("insufficient balance")||s.includes("insufficient eth")||s.includes("insufficient matic")||s.includes("insufficient bnb")||-32e3===a?{type:"insufficient_funds",title:"Insufficient Funds",message:"You don't have enough tokens or gas fees in your wallet.",suggestion:"Add more funds to your wallet and try again."}:s.includes("network error")||s.includes("rpc error")||s.includes("connection failed")||s.includes("timeout")||s.includes("request failed")?{type:"network_error",title:"Network Error",message:"Unable to connect to the blockchain network.",suggestion:"Check your internet connection and try again."}:s.includes("wrong network")||s.includes("unsupported network")||s.includes("chain mismatch")||4902===a?{type:"wrong_network",title:"Wrong Network",message:"Please switch to the correct network in your wallet.",suggestion:"Your wallet should prompt you to switch networks."}:s.includes("wallet not connected")||s.includes("no provider")||s.includes("wallet disconnected")||4900===a?{type:"wallet_disconnected",title:"Wallet Disconnected",message:"Your wallet is not connected.",suggestion:"Please reconnect your wallet and try again."}:s.includes("gas estimation failed")||s.includes("execution reverted")||s.includes("out of gas")?{type:"gas_error",title:"Transaction Failed",message:"The transaction couldn't be processed.",suggestion:"This might be a temporary issue. Please try again."}:s.includes("approve")&&s.includes("failed")?{type:"approval_failed",title:"Token Approval Failed",message:"Failed to approve token spending.",suggestion:"Please try the approval step again."}:s.includes("transaction failed")||s.includes("revert")||s.includes("contract call failed")?{type:"transaction_failed",title:"Transaction Failed",message:"The blockchain transaction was unsuccessful.",suggestion:"Please check your wallet and try again."}:s.includes("popup")||s.includes("blocked")?{type:"popup_blocked",title:"Wallet Popup Blocked",message:"Your browser blocked the wallet popup.",suggestion:"Please allow popups for this site and try again."}:s.includes("rate limit")||s.includes("too many requests")?{type:"rate_limited",title:"Too Many Requests",message:"Please wait a moment before trying again.",suggestion:"Wait 30 seconds and retry your transaction."}:s.includes("payment not yet confirmed")||s.includes("not yet confirmed on-chain")||s.includes("payment not found on-chain")||s.includes("please complete the payment")?{type:"payment_pending",title:"Payment Pending",message:"Your payment is still being confirmed on the blockchain.",suggestion:"Please wait a moment and try again, or check if your transaction completed successfully."}:s.includes("deep link")||s.includes("app not installed")||s.includes("wallet app")?{type:"mobile_wallet_error",title:"Wallet App Issue",message:"Unable to open or connect to your wallet app.",suggestion:"Make sure your wallet app is installed and try again."}:{type:"unknown_error",title:"Something Went Wrong",message:"An unexpected error occurred.",suggestion:"Please try again or contact support if the problem persists."}},on=(e,t="")=>({timestamp:(new Date).toISOString(),context:t,userFriendly:rn(e),technical:{message:(null==e?void 0:e.message)||"Unknown error",code:null==e?void 0:e.code,reason:null==e?void 0:e.reason,stack:null==e?void 0:e.stack,name:null==e?void 0:e.name}}),cn=async(e,t)=>{try{const n=await r.estimateFeesPerGas(e,{chainId:t}),s=120n,a=100n;return{maxFeePerGas:n.maxFeePerGas?n.maxFeePerGas*s/a:void 0,maxPriorityFeePerGas:n.maxPriorityFeePerGas?n.maxPriorityFeePerGas*s/a:void 0}}catch(n){return{}}},ln="YWG990wOlIikc1tU7-WWTepfU8d1f4dp",dn=(e,t,a,i,o,l)=>{const[d,m]=n.useState("idle"),[u,h]=n.useState(""),[p,y]=n.useState(null),{data:f,isPending:b,error:w,sendTransaction:v}=s.useSendTransaction(),{isLoading:k,isSuccess:N}=s.useWaitForTransactionReceipt({hash:f}),C=async()=>{var e,t,n,s,a,i,c;try{m("splitPayment");const u=window.coinleyPendingSplitPayment;if(!u)throw new Error("Missing split payment data");const{contractCall:h,selectedToken:p,paymentData:f,selectedNetwork:b}=u,w=b.chainId||10,v=await o.getContractInfo(w),{abi:k}=v,N=nn(h.params),C=x(w),P=1===C,j=P||43114===C;try{const{request:e}=await r.simulateContract(g,{address:h.contractAddress,abi:k,functionName:"splitPayment",args:[N]})}catch(l){const a=l.data||(null==(e=l.cause)?void 0:e.data);a&&("string"==typeof a&&a.startsWith("0x08c379a0")||"string"==typeof a&&a.startsWith("0x4e487b71"));l.reason||(null==(t=l.cause)?void 0:t.reason)||(null==(n=l.cause)?void 0:n.shortMessage)||(null==(s=l.data)||s.message);if(!j){const{userFriendlyMessage:e}=(e=>{if(!e.message)return{revertReason:"Transaction will revert",userFriendlyMessage:"Transaction simulation failed"};const t=e.message.toLowerCase();return t.includes("abi encoding params/values length mismatch")?{revertReason:"Smart contract parameter mismatch. This is likely a technical issue.",userFriendlyMessage:"Technical error: Contract parameters mismatch. Please try again or contact support."}:t.includes("payment id already used")?{revertReason:"This payment ID has already been used.",userFriendlyMessage:"This payment has already been processed. Please check your transaction history."}:t.includes("percentages must equal 100")?{revertReason:"Payment split percentages are incorrect.",userFriendlyMessage:"Internal error: Payment split configuration is invalid. Please contact support."}:t.includes("token transfer failed")||t.includes("transfer amount exceeds")?{revertReason:"Insufficient token balance or approval.",userFriendlyMessage:"Insufficient balance or token approval. Please check your wallet balance."}:t.includes("amount must be greater than 0")?{revertReason:"Payment amount is invalid.",userFriendlyMessage:"Invalid payment amount. Please try again."}:t.includes("invalid recipient")||t.includes("zero address")?{revertReason:"One of the payment recipients has an invalid address.",userFriendlyMessage:"Payment configuration error: Invalid recipient address. Please contact support."}:t.includes("insufficient gas")||t.includes("out of gas")?{revertReason:"Insufficient gas for transaction.",userFriendlyMessage:"Not enough gas to process transaction. Please increase gas limit or check ETH balance."}:t.includes("nonce")?{revertReason:"Transaction nonce conflict.",userFriendlyMessage:"Transaction ordering conflict. Please try again in a moment."}:{revertReason:e.message,userFriendlyMessage:`Transaction simulation failed: ${e.message.substring(0,100)}${e.message.length>100?"...":""}`}})(l);throw new Error(e)}}const I=await cn(g,w),S="arbitrum"===b.shortName,A=S?2:0;let E;for(let e=0;e<=A;e++)try{if(e>0){const t=2e3*e;await new Promise(e=>setTimeout(e,t))}E=await r.writeContract(g,{address:h.contractAddress,abi:k,functionName:"splitPayment",args:[N],...I});break}catch(d){const t=(null==(a=d.message)?void 0:a.includes("Internal JSON-RPC error"))||(null==(i=d.message)?void 0:i.includes("-32603"))||(null==(c=d.message)?void 0:c.includes("nonce"));if(e===A||!t&&!S)throw d}return y(E),m("processing"),window.coinleyPendingSplitPayment=null,E}catch(u){on(u,"split_payment_transaction");const e=rn(u);throw h(e),m("error"),u}},P=async t=>{try{if(m("processing"),!o||!o.processPayment)throw new Error("API instance not available or missing processPayment method");await new Promise(e=>setTimeout(e,8e3));const n=await o.processPayment(e.id,t,a.shortName,i);return m("success"),n}catch(n){on(n,"final_payment_processing");const e=rn(n);throw h(e),m("error"),n}};return{transactionStep:d,transactionError:u,currentTransactionHash:p,txPending:b,isConfirming:k,isConfirmed:N,executePaymentTransaction:async()=>{var n,s;if(!i||!(null==e?void 0:e.contractCall))throw new Error("Missing wallet connection or payment data");const o=e.contractCall;if(!o.contractAddress)throw new Error("PaymentSplitter contract data missing from payment response");if((null==l?void 0:l.ensureCorrectNetwork)&&a){if(!(await l.ensureCorrectNetwork(a)))throw new Error("Network verification failed. Please ensure you are on the correct network.")}if(!t.contractAddress)throw new Error("Native token transactions not yet supported with PaymentSplitter. Please use ERC-20 tokens.");{const l=t.decimals||6,k=o.approvalAmount||Math.floor(e.totalAmount*Math.pow(10,l));try{let e,n="unknown";try{e=await r.readContract(g,{address:o.tokenAddress,abi:an,functionName:"balanceOf",args:[i]}),n="wallet-rpc"}catch(d){const t=(null==a?void 0:a.chainId)||(null==a?void 0:a.id);if(!t)throw d;{const s=(e=>{const t={1:_t,56:Ot,137:en,42161:Mt,10:Xt,43114:Rt,42220:Yt,8453:Gt}[e],n={1:[`https://eth-mainnet.g.alchemy.com/v2/${ln}`,"https://cloudflare-eth.com","https://eth.llamarpc.com","https://ethereum.publicnode.com"],56:[`https://bnb-mainnet.g.alchemy.com/v2/${ln}`,"https://bsc-dataseed.bnbchain.org","https://bsc-dataseed-public.bnbchain.org","https://bsc.nodereal.io"],137:[`https://polygon-mainnet.g.alchemy.com/v2/${ln}`,"https://polygon.llamarpc.com","https://polygon-rpc.com","https://polygon.drpc.org"],42161:[`https://arb-mainnet.g.alchemy.com/v2/${ln}`,"https://arb1.arbitrum.io/rpc","https://arbitrum.llamarpc.com"],10:[`https://opt-mainnet.g.alchemy.com/v2/${ln}`,"https://mainnet.optimism.io","https://optimism.llamarpc.com"],43114:[`https://avax-mainnet.g.alchemy.com/v2/${ln}`,"https://api.avax.network/ext/bc/C/rpc","https://avalanche.public-rpc.com"],42220:[`https://celo-mainnet.g.alchemy.com/v2/${ln}`,"https://forno.celo.org","https://celo.drpc.org"],8453:[`https://base-mainnet.g.alchemy.com/v2/${ln}`,"https://mainnet.base.org","https://base.llamarpc.com","https://base.meowrpc.com"]}[e];if(!t||!n)return null;const s=n.map(e=>c.http(e,{timeout:1e4,retryCount:1}));return c.createPublicClient({chain:t,transport:c.fallback(s)})})(x(t));if(!s)throw d;try{e=await s.readContract({address:o.tokenAddress,abi:an,functionName:"balanceOf",args:[i]}),n="fallback-rpc"}catch(u){throw d}}}const s=BigInt(k);if(e<s){const n=`Insufficient ${t.symbol} balance. You have ${(Number(e)/Math.pow(10,l)).toFixed(6)} ${t.symbol} but need ${(Number(s)/Math.pow(10,l)).toFixed(6)} ${t.symbol}`;throw new Error(n)}}catch(p){if(p.message.includes("Insufficient"))throw p}m("approve"),window.coinleyPendingSplitPayment={contractCall:o,selectedToken:t,paymentData:e,selectedNetwork:a};try{const e="0xdac17f958d2ee523a2206206994597c13d831ec7"===o.tokenAddress.toLowerCase()||"USDT"===t.symbol.toUpperCase();let n,s=c.erc20Abi;e&&(s=sn);try{n=BigInt(k)}catch(f){throw new Error(`Invalid amount value: ${k}`)}let l=0n,d=0;const u=3;for(;d<u;)try{l=await r.readContract(g,{address:o.tokenAddress,abi:c.erc20Abi,functionName:"allowance",args:[i,o.contractAddress]});break}catch(b){d++,d<u?await new Promise(e=>setTimeout(e,2e3)):l=0n}if(l>=n){m("splitPayment");const e=await C();return e&&await P(e),e}if(e&&l>0n){const e=await cn(g,a.chainId),t=await r.writeContract(g,{address:o.tokenAddress,abi:c.erc20Abi,functionName:"approve",args:[o.contractAddress,0n],...e});await r.waitForTransactionReceipt(g,{hash:t,confirmations:1,timeout:12e4})}const h=await cn(g,a.chainId),p=await r.writeContract(g,{address:o.tokenAddress,abi:c.erc20Abi,functionName:"approve",args:[o.contractAddress,n],...h});y(p);await r.waitForTransactionReceipt(g,{hash:p,confirmations:1,timeout:12e4});await new Promise(e=>setTimeout(e,3e3));let x=0;const v=3;let N=!1;for(;x<v&&!N;){try{if(await r.readContract(g,{address:o.tokenAddress,abi:c.erc20Abi,functionName:"allowance",args:[i,o.contractAddress]})>=n){N=!0;break}x<v-1&&await new Promise(e=>setTimeout(e,2e3))}catch(w){x<v-1&&await new Promise(e=>setTimeout(e,2e3))}x++}const j=await C();return j&&await P(j),j}catch(v){on(v,"approve_transaction");const e=rn(v);if(h(e),m("idle"),(null==(n=v.message)?void 0:n.includes("User rejected"))||(null==(s=v.message)?void 0:s.includes("User denied"))||4001===v.code)throw new Error("Transaction was cancelled by user");throw new Error(`Approve failed: ${v.message}`)}}},executeSplitPayment:C,processFinalPayment:P,resetTransaction:()=>{m("idle"),h(""),y(null),window.coinleyPendingSplitPayment=null},setTransactionError:h,setTransactionStep:m}},mn=({options:e=[],value:s,onChange:a,placeholder:r,renderOption:i,getOptionKey:o,getOptionValue:c,getSearchableText:d,disabled:m=!1})=>{const[u,h]=n.useState(!1),[p,y]=n.useState(""),[g,f]=n.useState({top:0,left:0,width:400,maxHeight:450}),b=n.useRef(null),x=n.useRef(null),w=e.filter(e=>(d?d(e):"").toLowerCase().includes(p.toLowerCase())),v=e.find(e=>c(e)===s),k=()=>{if(x.current){const e=window.innerWidth,t=window.innerHeight,n=Math.min(400,e-40),s=Math.min(450,t-100);f({top:t/2-s/2,left:e/2-n/2,width:n,maxHeight:s})}};n.useEffect(()=>{const e=e=>{b.current&&!b.current.contains(e.target)&&x.current&&!x.current.contains(e.target)&&(h(!1),y(""))},t=()=>{u&&k()};if(u){k();const n=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${n}px`,document.body.style.width="100%",document.addEventListener("mousedown",e),window.addEventListener("resize",t)}return()=>{if(u){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",window.scrollTo(0,-1*parseInt(e||"0"))}document.removeEventListener("mousedown",e),window.removeEventListener("resize",t)}},[u]);const N=u&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-30 transition-opacity",style:{zIndex:999998},onClick:()=>{h(!1),y("")}}),t.jsxs("div",{ref:b,className:"fixed bg-white border-2 border-gray-200 rounded-3xl shadow-2xl overflow-hidden",style:{top:g.top,left:g.left,width:g.width,maxHeight:g.maxHeight,zIndex:999999,transform:"translateZ(0)",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(0, 0, 0, 0.05)"},children:[t.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 bg-gradient-to-r from-[#7042D2]/10 to-purple-50",children:[t.jsx("h3",{className:"text-lg font-semibold text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:r||"Select Option"}),t.jsx("button",{onClick:()=>{h(!1),y("")},className:"text-gray-500 hover:text-gray-700 transition-colors p-1 rounded-full hover:bg-gray-100",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),t.jsx("div",{className:"p-4 border-b border-gray-200 bg-gray-50",children:t.jsx("input",{type:"text",placeholder:"Search networks and tokens...",value:p,onChange:e=>y(e.target.value),className:"w-full p-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#7042D2]/20 focus:border-[#7042D2] text-sm",style:{fontFamily:"Bricolage Grotesque, sans-serif"},autoFocus:!0})}),t.jsx("div",{className:"overflow-y-auto custom-scrollbar",style:{maxHeight:(g.maxHeight||450)-180+"px",minHeight:"200px"},children:0===w.length?t.jsxs("div",{className:"p-8 text-gray-500 text-center",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"text-4xl mb-3",children:"🔍"}),t.jsx("div",{className:"text-lg mb-2",children:"No options found"}),t.jsx("div",{className:"text-sm text-gray-400",children:"Try a different search term"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"px-4 py-3 bg-gray-50 border-b border-gray-100 text-sm text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("span",{className:"font-semibold",children:w.length})," option",1!==w.length?"s":""," available"]}),t.jsx("div",{className:"p-2",children:w.map(e=>t.jsx("button",{type:"button",onClick:()=>{a(c(e)),h(!1),y("")},className:"w-full p-4 text-left hover:bg-[#7042D2]/10 transition-all duration-200 rounded-xl mb-2 last:mb-0 "+(c(e)===s?"bg-[#7042D2]/20 text-[#7042D2] border-2 border-[#7042D2]/30":"text-gray-800 border-2 border-transparent hover:border-[#7042D2]/20"),style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:i(e)},o(e)))})]})}),t.jsx("div",{className:"p-3 bg-gradient-to-r from-gray-50 to-gray-100 border-t border-gray-200 text-center",children:t.jsx("div",{className:"text-xs text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:w.length>5?"↕️ Scroll to see more options":"✨ Select your preferred option"})})]})]});return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"relative",children:t.jsx("button",{ref:x,type:"button",onClick:()=>{m||(u||k(),h(!u))},disabled:m,className:`w-full p-4 border-2 rounded-2xl bg-gradient-to-r from-white to-gray-50 text-left focus:outline-none focus:ring-3 focus:ring-[#7042D2]/20 focus:border-[#7042D2] transition-all duration-300 ease-out shadow-lg hover:shadow-xl ${m?"opacity-50 cursor-not-allowed":"hover:border-[#7042D2]/50 cursor-pointer"} ${u?"border-[#7042D2] ring-3 ring-[#7042D2]/20":"border-gray-200"}`,style:{minHeight:"60px",fontFamily:"Bricolage Grotesque, sans-serif",fontSize:"16px",fontWeight:"500"},children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("div",{className:"flex items-center space-x-3",children:v?i(v):t.jsx("span",{className:"text-gray-500",children:r})}),t.jsx("div",{className:"transform transition-transform duration-200 "+(u?"rotate-180":""),children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 text-[#7042D2]",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]})})}),"undefined"!=typeof document&&document.body&&l.createPortal(N,document.body),t.jsx("style",{jsx:!0,children:"\n .custom-scrollbar {\n scrollbar-width: thin;\n scrollbar-color: #7042D2 #f1f1f1;\n }\n .custom-scrollbar::-webkit-scrollbar {\n width: 12px;\n }\n .custom-scrollbar::-webkit-scrollbar-track {\n background: #f8f9fa;\n border-radius: 10px;\n margin: 4px;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb {\n background: linear-gradient(180deg, #7042D2 0%, #5b34b1 100%);\n border-radius: 10px;\n border: 2px solid #f8f9fa;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb:hover {\n background: linear-gradient(180deg, #5b34b1 0%, #4c2a93 100%);\n }\n .custom-scrollbar::-webkit-scrollbar-corner {\n background: #f8f9fa;\n }\n "})]})},un=({currentStep:e,targetStep:s,children:a,className:r="",duration:i=300})=>{const[o,c]=n.useState(e===s),[l,d]=n.useState(e===s);return n.useEffect(()=>{e===s?(d(!0),setTimeout(()=>c(!0),10)):(c(!1),setTimeout(()=>d(!1),i))},[e,s,i]),l?t.jsx("div",{className:`\n transition-all duration-300 ease-out\n ${o?"transform translate-y-0 opacity-100":"transform translate-y-full opacity-0"}\n ${r}\n `,style:{transitionDuration:`${i}ms`},children:a}):null},hn=({status:e,message:s,theme:a="light",payment:r=null,transactionHash:i=null,selectedPaymentMethod:o=null,selectedNetwork:c=null,merchantName:l="Merchant",onClose:d=null})=>{const[m,u]=n.useState(!1),[h,p]=n.useState(0);n.useEffect(()=>{if("processing"===e){const e=setInterval(()=>{p(e=>e>=90?e:e+15*Math.random())},500);return()=>clearInterval(e)}},[e]);const y=async()=>{if(i)try{await navigator.clipboard.writeText(i),u(!0),setTimeout(()=>u(!1),2e3)}catch(e){}},g=()=>{switch(e){case"processing":return t.jsxs("div",{className:"relative",children:[t.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-t-[#7042D2] border-blue-500/20"}),t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx("div",{className:"w-6 h-6 bg-[#7042D2] rounded-full animate-pulse"})})]});case"success":return t.jsx("div",{className:"rounded-full h-16 w-16 bg-green-500 flex items-center justify-center animate-bounce",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-10 w-10 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})});case"error":return t.jsx("div",{className:"rounded-full h-12 w-12 bg-red-100 flex items-center justify-center",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8 text-red-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})});default:return null}};return"processing"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Processing Payment"}),t.jsx("p",{className:"text-center text-gray-600 mb-6",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Your transaction has been sent to the blockchain and is being processed..."}),t.jsxs("div",{className:"w-full max-w-xs mb-4",children:[t.jsx("div",{className:"bg-gray-200 rounded-full h-3",children:t.jsx("div",{className:"bg-[#7042D2] h-3 rounded-full transition-all duration-500 ease-out",style:{width:`${h}%`}})}),t.jsxs("div",{className:"text-center mt-2 text-sm text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Processing... ",Math.round(h),"%"]})]}),t.jsxs("div",{className:"text-center space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Transaction submitted"})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-yellow-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Confirming on blockchain..."})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-gray-300 rounded-full"}),t.jsx("span",{className:"text-sm text-gray-400",children:"Finalizing payment..."})]})]}),t.jsx("div",{className:"mt-6 p-3 bg-blue-50 rounded-lg border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-800 text-center",children:"Please don't close this window. This usually takes 10-30 seconds."})})]}):"success"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-2xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Payment Successful!"}),r&&o&&t.jsxs("p",{className:"text-center max-w-[235px] mb-6 text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Your payment of ",t.jsxs("span",{className:"text-[#7042D2] font-semibold",children:[r.totalAmount||r.amount," ",o.currency]})," has been completed."]}),i&&t.jsxs("div",{className:"w-full mb-6 px-4",children:[t.jsx("p",{className:"text-sm font-medium mb-2 text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Transaction Details"}),t.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border cursor-pointer transition-colors bg-gray-50 border-gray-200 hover:bg-gray-100 mb-3",onClick:y,children:[t.jsx("span",{className:"font-mono text-sm text-gray-700",children:(f=i,f?f.length<=16?f:`${f.slice(0,8)}...${f.slice(-8)}`:"")}),t.jsxs("div",{className:"flex items-center",children:[m?t.jsx("span",{className:"text-green-500 text-xs font-medium mr-2",children:"Copied!"}):null,t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-gray-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})]})]}),(()=>{const e=((e,t)=>{if(!e||!t)return null;const n="string"==typeof t?t:t.shortName||t.name;return{ethereum:`https://etherscan.io/tx/${e}`,bsc:`https://bscscan.com/tx/${e}`,polygon:`https://polygonscan.com/tx/${e}`,arbitrum:`https://arbiscan.io/tx/${e}`,optimism:`https://optimistic.etherscan.io/tx/${e}`,avalanche:`https://snowtrace.io/tx/${e}`,celo:`https://celoscan.io/tx/${e}`,base:`https://basescan.org/tx/${e}`}[null==n?void 0:n.toLowerCase()]||null})(i,c),n=(e=>{if(!e)return"Explorer";const t="string"==typeof e?e:e.shortName||e.name;return{ethereum:"Etherscan",bsc:"BscScan",polygon:"PolygonScan",arbitrum:"Arbiscan",optimism:"Optimistic Etherscan",avalanche:"SnowTrace",celo:"CeloScan",base:"BaseScan"}[null==t?void 0:t.toLowerCase()]||"Explorer"})(c);return c&&e&&t.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 w-full p-3 rounded-lg border border-[#7042D2] bg-white hover:bg-purple-50 transition-colors group",children:[t.jsxs("span",{className:"text-sm font-medium text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["View on ",n]}),t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-[#7042D2] group-hover:translate-x-1 transition-transform",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})()]}),d&&t.jsx("button",{onClick:d,className:"w-full py-3 px-4 bg-[#7042D2] text-white font-semibold rounded-2xl text-lg shadow-md hover:bg-[#5b34b1] transition-colors",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Close"})]}):t.jsxs("div",{className:"flex flex-col items-center justify-center py-6",children:[t.jsx("div",{className:"mb-4",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-2 text-gray-900",children:"processing"===e?"Processing Payment":"error"===e?"Payment Failed":"Unknown Status"}),t.jsx("p",{className:"text-center text-gray-600",children:s})]});var f},pn={bitcoin:1,ethereum:1027,bsc:1839,polygon:3890,cardano:2010,avalanche:5805,fantom:3513,arbitrum:11841,optimism:11840,USDT:825,USDC:3408,BUSD:4687,DAI:4943,FRAX:6952,TUSD:2563,USDP:5992,USDD:5994,FDUSD:26081,PYUSD:28295,WBTC:3717,LINK:1975,UNI:7083,AAVE:7278,COMP:5692,YFI:5864,MKR:1518,SUSHI:6758,CRV:6538,SNX:2586,UMA:5617,BAL:5728,MANA:1966,SAND:6210,APE:18876,LDO:8e3,GRT:6719,ENS:13855,RPL:2943,SHIB:5994,MATIC:3890,BNB:1839,ADA:2010,SOL:5426,DOT:6636,AVAX:5805,TRX:1958,ALGO:4030,FTM:3513,ARB:11841,OP:11840,"1INCH":8104,DYDX:11156,ICP:8916,FIL:2280,CAKE:7186,RUNE:4157,ALPHA:7232,BNT:1727,KNC:1982,ZRX:1896,REN:2539,LRC:1934,WETH:2396,WMATIC:3890,WBNB:1839,UST:7129,USTC:7129,LUSD:8115,MIM:9681,FEI:8642,TRIBE:8741,RAI:8525,SUSD:2927},yn={ethereum:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bsc:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",polygon:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arbitrum:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avalanche:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",celo:"https://s2.coinmarketcap.com/static/img/coins/64x64/5567.png",optimism:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png",base:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",eth:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bnb:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",trx:"https://s2.coinmarketcap.com/static/img/coins/64x64/1958.png",algo:"https://s2.coinmarketcap.com/static/img/coins/64x64/4030.png",sol:"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png",matic:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arb:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avax:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",op:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png"},gn={metamask:"https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg",coinbase:"https://avatars.githubusercontent.com/u/18060234?s=280&v=4",rabby:"https://rabby.io/logo-128.png",zerion:"https://app.zerion.io/favicon-32x32.png",phantom:"https://phantom.app/favicons/apple-touch-icon.png",trust:"https://trustwallet.com/favicon-196x196.png",okx:"https://static.okx.com/cdn/assets/imgs/248/58E63FEA47A2B7D7.png",binance:"https://bin.bnbstatic.com/static/images/common/favicon.ico",cryptocom:"https://crypto.com/favicon.ico",hot:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiNGRjZBNkEiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmg0djhoLTR2LTJoMnYtNGgtMnYtMnptNiAwaDJ2MmgtdjdoLTJ2LTIiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg==",backpack:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiMwMEQ0QUEiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMGg4djJoLTJ2NmgtdjhoLTZWMTB6bTIgMnY0aDJWMTJ6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4=","1inch":"https://1inch.io/favicon.svg",default:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiM2MzY2RjEiIHN0cm9rZT0iI0Y5RkFGQiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmgxMnY4SDEweiIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIxLjUiIHJ4PSIxIi8+CjxjaXJjbGUgY3g9IjE4IiBjeT0iMTYiIHI9IjEiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg=="},fn=e=>(e=>{if(!e)return null;const t=pn[e.toUpperCase()];return t?`https://s2.coinmarketcap.com/static/img/coins/64x64/${t}.png`:null})(e),bn=(e,t)=>{const n=e.toLowerCase(),s=t.toLowerCase();for(const[a,r]of Object.entries(gn))if(n.includes(a)||s.includes(a))return r;return gn.default},xn=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),wn=e=>{switch(e){case"trust":return window.ethereum&&!0===window.ethereum.isTrust;case"metaMask":return window.ethereum&&!0===window.ethereum.isMetaMask;case"injected":return window.ethereum&&!window.ethereum.isMetaMask&&!window.ethereum.isCoinbaseWallet;default:return!1}},vn=(e,t)=>{if(!t)return[];if(!["ethereum","bsc","polygon","arbitrum","optimism","avalanche","celo","base"].includes(t.shortName))return[];return[...(e||[]).map(e=>(e=>({type:e.id,name:e.name,icon:bn(e.name,e.id),description:`Connect using ${e.name}`,isInstalled:!0,connector:e,isWagmi:!0}))(e)),...xn()?[{type:"trust",name:"Trust Wallet",icon:"🛡️",description:"Multi-chain wallet with transaction deep links",isInstalled:!1,connector:null,isWagmi:!1,mobileOnly:!0,hasTransactionDeepLinks:!0}]:[]]},kn=(e,t,n,s,a="metamask",r=null)=>{if(!e)return null;try{const t="https://paymentscreen.vercel.app",s=new URLSearchParams,r=(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId);if(!r)return null;s.set("paymentId",r),s.set("preferredWallet",a),s.set("isMobile","true");const i=`${t}?${s.toString()}`;let o;switch(a){case"metamask":o=`https://metamask.app.link/dapp/${i.replace("https://","")}`;break;case"trust":const e=(null==n?void 0:n.chainId)||1;o=`https://link.trustwallet.com/open_url?coin_id=${(e=>{const t="string"==typeof e&&e.startsWith("0x")?parseInt(e,16):parseInt(e);return[1,56,137,42161,10,43114,42220,8453].includes(t)?60:{}[t]||60})(e)}&url=${encodeURIComponent(i)}`;break;case"coinbase":o=`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(i)}`;break;default:o=i}return o}catch(i){return null}},Nn=(e,t)=>{if(!t)return null;try{switch(e){case"metamask":return t.includes("metamask.app.link")?t:`https://metamask.app.link/dapp/${t.replace("https://","")}`;case"trust":return t.includes("link.trustwallet.com")?t:`https://link.trustwallet.com/open_url?coin_id=60&url=${encodeURIComponent(t)}`;case"coinbase":return t.includes("go.cb-w.com")?t:`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(t)}`;default:return t}}catch(n){return t}},Cn=Object.freeze(Object.defineProperty({__proto__:null,generateMobilePaymentDeepLink:Nn,generateQRPaymentURI:kn},Symbol.toStringTag,{value:"Module"})),Pn=({walletAddress:e,amount:s,currency:a,network:r,theme:i="light",paymentData:o=null,onPaymentDetected:c=null,config:l=null,selectedToken:m=null,selectedNetwork:u=null,preferredWallet:h="metamask",compact:p=!1})=>{const[y,g]=n.useState(""),[f,b]=n.useState(""),[x,w]=n.useState(!0),[v,k]=n.useState(!1),[N,C]=n.useState(!1),P=n.useRef(null);return n.useEffect(()=>{(async()=>{if(null==o?void 0:o.id){w(!0);try{if(!m||!m.contractAddress)throw new Error("Cannot generate QR code: Token contract address required");if(!u||!u.chainId)throw new Error("Cannot generate QR code: Network chain ID required");const e=kn(o,0,u,0,h);if(e.includes("metamask.app.link")||e.includes("link.trustwallet.com")||e.includes("go.cb-w.com"),!e)throw new Error("Failed to generate Coinley payment URL");g(e);const t=xn(),n=await d.toDataURL(e,{width:p?140:t?350:280,margin:2,errorCorrectionLevel:"M",color:{dark:"dark"===i?"#FFFFFF":"#000000",light:"dark"===i?"#000000":"#FFFFFF"}});b(n),w(!1)}catch(e){w(!1)}}else w(!1)})()},[o,s,a,r,i,m,u,l,h]),n.useEffect(()=>()=>{P.current&&clearInterval(P.current)},[]),t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"flex gap-3 items-start w-full mb-2",children:[t.jsx("div",{className:"p-1.5 rounded-lg bg-white shadow-sm border flex-shrink-0",children:x?t.jsx("div",{className:"flex items-center justify-center",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600 mx-auto mb-1"}),t.jsx("div",{className:"text-xs text-gray-600",children:"Generating..."})]})}):f?t.jsx("img",{src:f,alt:"Payment QR Code",className:"rounded-lg",style:{width:140,height:140}}):t.jsx("div",{className:"flex items-center justify-center bg-gray-100 rounded-lg",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center p-2",children:[t.jsx("div",{className:"text-lg mb-1",children:"⚠️"}),t.jsx("div",{className:"text-xs text-gray-600",children:(null==o?void 0:o.id)?"QR Failed":"Payment not created"})]})})}),t.jsxs("div",{className:"flex-1 flex flex-col justify-center",children:[t.jsxs("div",{className:"p-2 bg-gray-50 rounded-lg mb-2",children:[t.jsxs("div",{className:"flex justify-between items-center mb-1",children:[t.jsx("span",{className:"text-xs font-medium text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"text-sm font-bold text-[#7042D2]",children:[s," ",a]})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-xs text-gray-500",children:"Network:"}),t.jsx("span",{className:"text-xs font-medium text-gray-700",children:r})]})]}),N?t.jsxs("div",{className:"flex items-center justify-center text-xs font-semibold text-green-600 p-1.5 bg-green-50 rounded-lg",children:[t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3.5 w-3.5 mr-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"Payment Received!"]}):t.jsx("div",{className:"p-1.5 rounded-lg bg-blue-50 border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-700 text-center leading-tight",children:"📱 Scan with phone camera"})})]})]})})},jn=({selectedNetwork:e,onWalletSelect:a,onConnect:r,connectedWallet:i,loading:o,paymentData:c=null,selectedToken:l=null,api:d=null})=>{const[m,u]=n.useState(null),{connectors:h}=s.useConnect(),{isConnected:p,address:y}=s.useAccount(),g=vn(h,e),f=async(t,n)=>{if(xn())if(c)try{const{generateQRPaymentURI:s,generateMobilePaymentDeepLink:a}=await Promise.resolve().then(()=>Cn),r=s(c,l,e,(null==d?void 0:d.config)||{},n);if(!r)throw new Error("Failed to generate payment URL");const i=a(n,r);if(!i)throw new Error(`Failed to generate ${t.name} deep link`);window.location.href=i}catch(s){alert(`Failed to open ${t.name}: ${s.message}`)}else alert("Please create a payment first before selecting a mobile wallet.");else alert(`Please install ${t.name} mobile app or use the browser extension if available.`)};return e?0===g.length?t.jsxs("div",{className:"text-center p-4",children:[t.jsxs("p",{className:"text-gray-500 mb-4",children:["No compatible wallets found for ",e.name]}),t.jsx("div",{className:"p-3 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-sm text-amber-800",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"font-medium mb-2",children:"Install a compatible wallet:"}),t.jsxs("div",{className:"space-y-1 text-xs",children:[t.jsxs("div",{children:["• ",t.jsx("a",{href:"https://metamask.io/download/",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install MetaMask Wallet"})]}),t.jsxs("div",{children:["• ",t.jsx("a",{href:"https://www.coinbase.com/wallet",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Coinbase Wallet"})]})]})]})})]}):t.jsxs("div",{className:"space-y-4",children:[t.jsxs("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Select Wallet for ",e.name]}),t.jsx(mn,{options:g,value:(null==i?void 0:i.walletType)||m||"",onChange:async e=>{u(e);const t=g.find(t=>t.type===e);t&&(a(e),t.isWagmi&&t.connector?await r(t.connector):t.isWagmi||await f(t,e))},placeholder:"Choose your wallet...",renderOption:e=>{var n,s;return t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsxs("div",{className:"w-8 h-8 flex items-center justify-center",children:[e.icon.startsWith("http")||e.icon.startsWith("data:")?t.jsx("img",{src:e.icon,alt:e.name,className:"w-6 h-6 rounded-full object-contain",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="block"}}):t.jsx("div",{className:"text-2xl",children:e.icon}),t.jsx("div",{className:"text-xl",style:{display:"none"},children:"🔗"})]}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800 flex items-center",children:[e.name,wn(e.type)&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full",children:"DETECTED"}),(null==i?void 0:i.walletType)===e.type&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full",children:"CONNECTED"})]}),t.jsx("div",{className:"text-sm text-gray-500",children:(null==i?void 0:i.walletType)===e.type?`Connected • ${null==(n=i.account)?void 0:n.slice(0,6)}...${null==(s=i.account)?void 0:s.slice(-4)}`:e.description})]}),o&&m===e.type&&t.jsx("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-[#7042D2]"})]})},getOptionKey:e=>e.type,getOptionValue:e=>e.type,getSearchableText:e=>`${e.name} ${e.description}`,disabled:o})]}):t.jsx("div",{className:"text-center p-4",children:t.jsx("p",{className:"text-gray-500",children:"Please select a network first"})})},In=(()=>{if("undefined"!=typeof process&&process.env)return!1;if("undefined"!=typeof window){const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||e.includes("192.168.")}return!1})()||(()=>{if("undefined"!=typeof window){const e=new URLSearchParams(window.location.search);return"true"===e.get("debug")||"true"===e.get("debugMode")}return!1})(),Sn=({paymentData:e,selectedToken:s,selectedNetwork:a,config:r,onPaymentStarted:i=()=>{},onError:o=()=>{}})=>{var c,l;const[d,m]=n.useState(null),[u,h]=n.useState(!1),[p,y]=n.useState([]),[g,f]=n.useState(!1),[b,x]=n.useState(0);n.useEffect(()=>{var t,n,r;(null==e?void 0:e.id)&&(null==s?void 0:s.contractAddress)&&(null==a?void 0:a.chainId)&&((null==(t=null==e?void 0:e.contractCall)?void 0:t.contractAddress)||(null==e?void 0:e.contractAddress))?w("success","✅ Payment data complete",{paymentId:e.id,tokenContract:s.contractAddress,chainId:a.chainId,paymentContract:(null==(r=null==e?void 0:e.contractCall)?void 0:r.contractAddress)||(null==e?void 0:e.contractAddress)}):(w("debug","⏳ Waiting for complete payment data",{hasPaymentId:!!(null==e?void 0:e.id),hasTokenContract:!!(null==s?void 0:s.contractAddress),hasChainId:!!(null==a?void 0:a.chainId),hasPaymentContract:!(!(null==(n=null==e?void 0:e.contractCall)?void 0:n.contractAddress)&&!(null==e?void 0:e.contractAddress)),checkCount:b}),x(e=>e+1))},[e,s,a,b]);const w=(e,t,n=null)=>{const s=(new Date).toLocaleTimeString(),a={id:Date.now()+Math.random(),type:e,message:t,data:n,timestamp:s};In&&(y(e=>[...e,a].slice(-20)),e.toUpperCase())},v=[{id:"metamask",name:"MetaMask",icon:"🦊",description:"Connect with MetaMask mobile"},{id:"trust",name:"Trust Wallet",icon:"🛡️",description:"Connect with Trust Wallet"},{id:"coinbase",name:"Coinbase Wallet",icon:"💙",description:"Connect with Coinbase Wallet"}];if(!e)return t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"⚠️ Payment Required"}),t.jsx("div",{className:"text-sm text-amber-700",children:"Please create a payment before selecting a wallet"})]})});const k=(null==e?void 0:e.id)&&(null==s?void 0:s.contractAddress)&&(null==a?void 0:a.chainId)&&((null==(c=null==e?void 0:e.contractCall)?void 0:c.contractAddress)||(null==e?void 0:e.contractAddress));return t.jsx("div",{className:"space-y-4",children:k?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Select Mobile Wallet"}),t.jsx(mn,{options:v,value:d||"",onChange:async t=>{const n=v.find(e=>e.id===t);if(n){m(t),h(!0);try{if(w("info",`🚀 Mobile wallet selected: ${n.name}`),!e)throw new Error("Payment data not available. Please create payment first.");w("debug","🔍 Payment Data Check",{hasPaymentData:!!e,hasSelectedToken:!!s,hasSelectedNetwork:!!a,hasConfig:!!r,paymentId:(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId),tokenAddress:null==s?void 0:s.contractAddress,networkChainId:null==a?void 0:a.chainId,amount:(null==e?void 0:e.totalAmount)||(null==e?void 0:e.amount)||(null==r?void 0:r.amount)});const o=kn(e,0,a,0,t);if(!o)throw new Error("Failed to generate payment URL");w("success","📱 Generated payment URL",{url:o,length:o.length});const c=Nn(t,o);if(!c)throw new Error(`Failed to generate ${n.name} deep link`);w("success",`🔗 Deep link generated for ${n.name}`,{deepLink:c}),i({walletType:t,walletName:n.name,paymentUrl:o,deepLink:c}),setTimeout(()=>{w("info",`📱 Opening ${n.name}...`),window.location.href=c},500)}catch(c){w("error","❌ Mobile wallet connection failed",{error:c.message,walletId:t,hasPaymentData:!!e,hasSelectedToken:!!s,hasSelectedNetwork:!!a}),o(c.message),h(!1),m(null)}}},placeholder:"Choose your wallet...",renderOption:e=>t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsx("div",{className:"w-8 h-8 flex items-center justify-center",children:t.jsx("div",{className:"text-2xl",children:e.icon})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name,d===e.id&&u&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full animate-pulse",children:"Opening..."})]}),t.jsx("div",{className:"text-sm text-gray-500",children:e.description})]})]}),getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.description}`,disabled:u}),t.jsx("div",{className:"text-xs text-gray-500 mt-2",children:"Select a wallet to open it with your payment details"})]}),u&&d&&t.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-lg animate-pulse",children:t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-blue-600 border-t-transparent"}),t.jsxs("div",{className:"text-sm text-blue-700",children:["Opening ",null==(l=v.find(e=>e.id===d))?void 0:l.name,"..."]})]})}),t.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[t.jsxs("div",{className:"flex justify-between items-center text-sm",children:[t.jsx("span",{className:"text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"font-semibold text-gray-800",children:[e.totalAmount," ",(null==s?void 0:s.symbol)||"USDC"]})]}),t.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[t.jsx("span",{className:"text-gray-600",children:"Network:"}),t.jsx("span",{className:"text-gray-800",children:(null==a?void 0:a.name)||"Ethereum"})]})]}),t.jsx("div",{className:"p-3 bg-purple-50 border border-purple-200 rounded-lg",children:t.jsxs("div",{className:"text-xs text-purple-700",children:[t.jsx("div",{className:"font-medium mb-1",children:"📱 Mobile Payment"}),t.jsx("div",{children:"Your selected wallet app will open with payment details pre-filled"})]})}),In&&t.jsxs("div",{className:"mt-4",children:[t.jsxs("button",{onClick:()=>f(!g),className:"w-full text-xs py-2 px-3 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition-colors",children:[g?"🔽 Hide Debug Info":"🔧 Show Debug Info"," (",p.length," logs)"]}),g&&t.jsxs("div",{className:"mt-2 p-3 bg-gray-900 text-green-400 rounded-lg text-xs font-mono max-h-80 overflow-y-auto",children:[t.jsx("div",{className:"text-white mb-2 font-bold",children:"📱 Mobile Debug Panel"}),0===p.length?t.jsx("div",{className:"text-gray-400",children:"No debug logs yet. Try selecting a wallet..."}):p.map(e=>t.jsxs("div",{className:"mb-3 pb-2 border-b border-gray-700",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("span",{className:"px-2 py-1 rounded text-xs font-bold "+("error"===e.type?"bg-red-600 text-white":"success"===e.type?"bg-green-600 text-white":"debug"===e.type?"bg-blue-600 text-white":"bg-gray-600 text-white"),children:e.type.toUpperCase()}),t.jsx("span",{className:"text-gray-400",children:e.timestamp})]}),t.jsx("div",{className:"text-yellow-300 mb-1",children:e.message}),e.data&&t.jsx("div",{className:"text-gray-300 text-xs",children:t.jsxs("details",{children:[t.jsx("summary",{className:"cursor-pointer text-blue-300 hover:text-blue-200",children:"📊 Data"}),t.jsx("pre",{className:"mt-1 p-2 bg-gray-800 rounded overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(e.data,null,2)})]})})]},e.id)),t.jsx("button",{onClick:()=>y([]),className:"mt-2 px-3 py-1 bg-red-600 text-white rounded text-xs hover:bg-red-700",children:"Clear Logs"})]})]})]}):t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"⏳ Preparing Payment..."}),t.jsx("div",{className:"text-sm text-amber-700",children:"Payment is being prepared. Please wait a moment..."}),t.jsx("div",{className:"mt-3",children:t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-amber-600 border-t-transparent mx-auto"})})]})})})},An=({error:e,onRetry:n,onDismiss:s,context:a="payment",className:r=""})=>{if(!e)return null;const i=rn(e),o=(e=>{switch(e){case"user_rejected":return"info";case"insufficient_funds":case"wrong_network":case"wallet_disconnected":case"payment_pending":return"warning";case"network_error":case"gas_error":case"rate_limited":return"error";default:return"critical"}})(i.type),c=(e=>{switch(e){case"user_rejected":default:return"Try Again";case"insufficient_funds":return"Add Funds & Retry";case"wrong_network":return"Switch Network & Retry";case"wallet_disconnected":return"Reconnect Wallet";case"payment_pending":return"Check Again";case"network_error":case"rate_limited":return"Retry";case"popup_blocked":return"Allow Popups & Retry";case"mobile_wallet_error":return"Open Wallet App"}})(i.type),l={info:{container:"bg-blue-50 border-blue-200",title:"text-blue-800",message:"text-blue-700",icon:"ℹ️",button:"bg-blue-600 hover:bg-blue-700"},warning:{container:"bg-amber-50 border-amber-200",title:"text-amber-800",message:"text-amber-700",icon:"⚠️",button:"bg-amber-600 hover:bg-amber-700"},error:{container:"bg-red-50 border-red-200",title:"text-red-800",message:"text-red-700",icon:"❌",button:"bg-red-600 hover:bg-red-700"},critical:{container:"bg-red-50 border-red-300",title:"text-red-900",message:"text-red-800",icon:"🚨",button:"bg-red-700 hover:bg-red-800"}},d=l[o]||l.error;return t.jsxs("div",{className:`p-4 border rounded-lg ${d.container} ${r}`,children:[t.jsxs("div",{className:"flex items-start space-x-3",children:[t.jsx("div",{className:"flex-shrink-0 text-xl",children:d.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:`font-semibold ${d.title} mb-1`,children:i.title}),t.jsx("div",{className:`text-sm ${d.message} mb-2`,children:i.message}),i.suggestion&&t.jsxs("div",{className:`text-xs ${d.message} opacity-90`,children:["💡 ",i.suggestion]})]}),s&&t.jsx("button",{onClick:s,className:"flex-shrink-0 text-gray-400 hover:text-gray-600 transition-colors","aria-label":"Dismiss error",children:t.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:t.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})})]}),n&&t.jsxs("div",{className:"mt-3 flex justify-end space-x-2",children:[s&&"info"===o&&t.jsx("button",{onClick:s,className:"px-3 py-1.5 text-xs text-gray-600 hover:text-gray-800 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:n,className:`px-4 py-2 text-sm font-medium text-white rounded-md transition-colors ${d.button}`,children:c})]}),!1]})},En="method",Fn="confirm",Un="processing",Dn="success",Tn="wallet",Bn="qr",Ln="Bricolage Grotesque, sans-serif",Mn=new a.QueryClient,Rn=({publicKey:e,apiKey:a,apiSecret:i,apiUrl:o,config:c,onSuccess:l,onError:d,onClose:m,isOpen:u,theme:p="light"})=>{const y=((e,t,s)=>{const[a,r]=n.useState("method"),[i,o]=n.useState([]),[c,l]=n.useState([]),[d,m]=n.useState(null),[u,h]=n.useState(null),[p,y]=n.useState(null),[g,b]=n.useState(null),[x,w]=n.useState(!1),[v,k]=n.useState(""),[N,C]=n.useState(!1),[P,j]=n.useState("Processing transaction..."),[I,S]=n.useState("wallet"),[A,E]=n.useState(null),F=n.useRef(new f(e,t,s));return{currentStep:a,networks:i,tokens:c,selectedNetwork:d,selectedToken:u,paymentMethod:p,paymentData:g,loading:x,error:v,processing:N,processingMessage:P,paymentType:I,actualTransactionHash:A,setCurrentStep:r,setSelectedNetwork:m,setSelectedToken:h,setPaymentMethod:y,setError:k,setProcessing:C,setProcessingMessage:j,setPaymentType:S,setActualTransactionHash:E,loadData:async()=>{var e,t;try{w(!0),k("");const[n,s]=await Promise.all([F.current.getNetworks(),F.current.getTokens()]),a=(null==(e=n.networks)?void 0:e.reduce((e,t)=>{if("solana"===t.shortName||"tron"===t.shortName||"algorand"===t.shortName)return e;if(!t.chainId||null===t.chainId)return e;const n=`${t.chainId}-${t.shortName}`;return e.some(e=>`${e.chainId}-${e.shortName}`===n)||e.push(t),e},[]))||[],r=(null==(t=s.stablecoins)?void 0:t.reduce((e,t)=>{var n,s,a;if("USDC"!==t.symbol&&"USDT"!==t.symbol)return e;if("solana"===(null==(n=t.Network)?void 0:n.shortName)||"tron"===(null==(s=t.Network)?void 0:s.shortName)||"algorand"===(null==(a=t.Network)?void 0:a.shortName))return e;const r=`${t.symbol}-${t.networkId}`;return e.some(e=>`${e.symbol}-${e.networkId}`===r)||e.push(t),e},[]))||[];o(a),l(r)}catch(n){k("Failed to load payment options. Using fallback data.")}finally{w(!1)}},createPayment:async e=>{try{w(!0),k("");const t={amount:e.amount,currency:u.symbol,network:d.shortName,customerEmail:e.customerEmail,callbackUrl:e.callbackUrl,metadata:{...e.metadata,merchantWalletAddresses:e.merchantWalletAddresses,paymentMethod:p,selectedNetwork:d.shortName,selectedToken:u.symbol,wagmiEnabled:!0}},n=await F.current.createPayment(t);b(n.payment),r("confirm")}catch(t){k(t.message)}finally{w(!1)}},failPayment:async(e="Payment cancelled by user")=>{if(null==g?void 0:g.id)try{await F.current.failPayment(g.id,e)}catch(t){}},resetState:()=>{r("method"),m(null),h(null),y(null),b(null),k(""),C(!1),E(null),S("wallet")},resetTransactionState:()=>{k(""),C(!1),E(null),r("confirm")},api:F.current}})(o,e||a,e?null:i),b=(()=>{const[e,t]=n.useState(null),[a,i]=n.useState(null),[o,c]=n.useState(""),{connect:l,connectors:d}=s.useConnect(),{isConnected:m,address:u,chain:h}=s.useAccount(),{switchChain:p}=s.useSwitchChain();return n.useEffect(()=>{i(m&&u?{account:u,chainId:null==h?void 0:h.id,walletType:e}:null)},[m,u,h,e]),{selectedWalletType:e,connectedWallet:a,connectionError:o,isConnected:m,address:u,chain:h,connectors:d,handleWalletSelection:e=>{t(e),c("")},connectWallet:async(e,t=null)=>{var n,s,a;if(!e)return c("Please select a wallet first"),!1;try{if(c(""),await l({connector:e}),t){const o=w(t.shortName),l=(null==(n=e.name)?void 0:n.toLowerCase())||"",d=l.includes("zerion")||l.includes("trust")||l.includes("rabby")?5e3:500;await new Promise(e=>setTimeout(e,d));const m=r.getAccount(g).chainId;if(o&&m!==o)try{await p({chainId:o}),await new Promise(e=>setTimeout(e,1e3))}catch(i){return 4001===i.code||(null==(s=i.message)?void 0:s.includes("User rejected"))?c("Network switch was cancelled by user"):(null==(a=i.message)?void 0:a.includes("Unrecognized chain ID"))?c(`${t.name} network is not added to your wallet. Please add it manually.`):c(`Failed to switch to ${t.name}. Please switch manually in your wallet.`),!1}}return!0}catch(o){return 4001===o.code||o.message.includes("User rejected")||o.message.includes("rejected")?c("User cancelled the connection request"):c(`Failed to connect to ${e.name}. Please try again.`),!1}},disconnectWallet:()=>{i(null),t(null),c("")},switchChain:p,ensureCorrectNetwork:async e=>{var t,n;if(!e)return!0;try{const a=w(e.shortName),i=r.getAccount(g).chainId;if(a&&i!==a)try{return await p({chainId:a}),await new Promise(e=>setTimeout(e,1e3)),!0}catch(s){return 4001===s.code||(null==(t=s.message)?void 0:t.includes("User rejected"))?c("Network switch was cancelled. Please switch to the correct network in your wallet."):(null==(n=s.message)?void 0:n.includes("Unrecognized chain ID"))?c(`${e.name} network is not added to your wallet. Please add it manually.`):c(`Failed to switch to ${e.name}. Please switch manually in your wallet.`),!1}return!0}catch(B){return c("Failed to verify network. Please check your wallet connection."),!1}},clearError:()=>{c("")},setSelectedWalletType:t,connect:l}})(),[x,v]=n.useState("metamask"),[k,N]=n.useState(!1),[C,P]=n.useState(()=>!("undefined"==typeof window||!window.sessionStorage)&&"true"===sessionStorage.getItem("coinley_mobile_payment_started")),[j,I]=n.useState(!1);n.useEffect(()=>{N(xn())},[]);const{currentStep:S,networks:A,tokens:E,selectedNetwork:F,selectedToken:U,paymentData:D,loading:T,error:B,paymentType:L,loadData:M,createPayment:R,failPayment:$,resetState:G,setSelectedNetwork:O,setSelectedToken:z,setPaymentType:W,setCurrentStep:H,setError:q}=y,{connectedWallet:V,address:Q,connectWallet:K,handleWalletSelection:Z}=b,Y=dn(D,U,F,Q,y.api,b),{executePaymentTransaction:_,processFinalPayment:J,transactionStep:X,transactionError:ee,currentTransactionHash:te}=Y;n.useEffect(()=>{S===Dn&&"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started")},[S]),n.useEffect(()=>{if(u){M(),G();const e=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%",document.body.style.overflow="hidden"}else{const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}return()=>{if(u){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}}},[u]),n.useEffect(()=>{if("processing"===X||"approve"===X||"splitPayment"===X){const e=setTimeout(()=>{q("Transaction timed out. Please try again."),H(Fn),Y.resetTransaction()},12e4);return()=>clearTimeout(e)}},[X]);const ne=async()=>{await $(),m()};return u?t.jsxs("div",{className:"fixed inset-0 z-50",children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 transition-opacity",onClick:ne,"aria-hidden":"true"}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsxs("div",{className:"relative pt-4 w-full max-w-md max-h-[90vh] mx-auto shadow-xl bg-gray-100 rounded-3xl flex flex-col overflow-hidden",style:{zIndex:52},children:[t.jsxs("div",{className:"flex-shrink-0 bg-white flex justify-between items-center mb-3 mr-3 ml-3 py-3 px-2 rounded-full",children:[t.jsxs("div",{className:"flex-1 flex items-center gap-2 px-4",children:[t.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",children:t.jsx("img",{src:h,alt:"Coinley"})}),t.jsx("span",{className:"text-base font-semibold text-gray-800",style:{fontFamily:Ln},children:"Payment Details"})]}),S!==Dn&&S!==Un&&t.jsx("button",{onClick:ne,className:"text-gray-500 hover:text-gray-700 focus:outline-none",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 mr-2",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),c&&S!==Dn&&t.jsx("div",{className:"flex-shrink-0 mb-3 px-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-xs text-gray-600",children:"Total Amount"}),t.jsxs("div",{className:"text-3xl font-bold text-[#7042D2] mt-1 leading-tight tracking-tight",style:{fontFamily:Ln},children:["$",(se=c.amount,parseFloat(se).toFixed(2))]}),t.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"No additional fees"}),t.jsx("div",{className:"text-xs text-gray-600 mt-2",children:"Payment to:"}),t.jsxs("div",{className:"text-sm font-semibold mt-0.5 flex gap-1.5 items-center justify-center",style:{fontFamily:Ln},children:[t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M15.3 7.50065L15.8 10.0007H4.2L4.7 7.50065H15.3ZM16.6667 3.33398H3.33333V5.00065H16.6667V3.33398ZM16.6667 5.83398H3.33333L2.5 10.0007V11.6673H3.33333V16.6673H11.6667V11.6673H15V16.6673H16.6667V11.6673H17.5V10.0007L16.6667 5.83398ZM5 15.0007V11.6673H10V15.0007H5Z",fill:"#7042D2"})}),c.merchantName||"Merchant"]})]})}),t.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain",children:[t.jsx(un,{currentStep:S,targetStep:En,children:t.jsxs("div",{className:"pb-4 pt-3 px-5 bg-white rounded-t-2xl",children:[t.jsx("h3",{className:"font-semibold text-center mb-3 text-sm",style:{fontFamily:Ln},children:"Choose Payment Method"}),t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:Ln},children:"Select Network"}),t.jsx(mn,{options:A,value:(null==F?void 0:F.id)||"",onChange:e=>{const t=A.find(t=>t.id===e);O(t),z(null)},placeholder:"Choose your network...",renderOption:e=>{var n,s;const a="object"==typeof(r=e)&&(null==r?void 0:r.logo)?r.logo:"object"==typeof r&&(null==r?void 0:r.shortName)?yn[r.shortName.toLowerCase()]:"string"==typeof r?yn[r.toLowerCase()]:null;var r;return t.jsxs("div",{className:"flex items-center space-x-3",children:[a?t.jsx("img",{src:a,alt:e.name,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:a?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(n=e.shortName)?void 0:n.slice(0,2).toUpperCase()})}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-gray-800",children:e.name}),t.jsx("div",{className:"text-sm text-gray-500",children:null==(s=e.shortName)?void 0:s.toUpperCase()})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.shortName}`,disabled:T})]}),F&&t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:Ln},children:"Select Token"}),t.jsx(mn,{options:E.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==F?void 0:F.shortName)||e.networkId===(null==F?void 0:F.id)}),value:(null==U?void 0:U.id)||"",onChange:e=>{const t=E.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==F?void 0:F.shortName)||e.networkId===(null==F?void 0:F.id)}).find(t=>t.id===e);z(t)},placeholder:"Choose your token...",renderOption:e=>{var n,s;const a=fn(e.symbol);return t.jsxs("div",{className:"flex items-center space-x-3",children:[a?t.jsx("img",{src:a,alt:e.symbol,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:a?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(n=e.symbol)?void 0:n.slice(0,2)})}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name," (",e.symbol,")"]}),t.jsxs("div",{className:"text-sm text-gray-500",children:[(null==(s=e.Network)?void 0:s.name)||"Unknown Network",e.isStablecoin&&t.jsx("span",{className:"ml-2 text-green-600",children:"• Stablecoin"})]})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.symbol}`,disabled:T})]}),F&&U&&t.jsx("button",{onClick:()=>R(c),disabled:T,className:"w-full bg-[#7042D2] text-white py-4 px-4 rounded-xl hover:bg-[#5b34b1] disabled:opacity-50 font-semibold transition-all duration-200 shadow-lg hover:shadow-xl",style:{fontFamily:Ln},children:T?"Creating Payment...":"Continue"})]})}),t.jsx(un,{currentStep:S,targetStep:Fn,children:F&&U&&D&&t.jsxs("div",{className:"pb-4 pt-4 px-4 bg-white rounded-t-2xl",children:[!k&&t.jsx("div",{className:"mb-4",children:t.jsxs("div",{className:"flex border-b border-gray-200",children:[t.jsx("button",{onClick:()=>W(Tn),className:"py-3 px-6 text-sm font-semibold transition-all duration-200 "+(L===Tn?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:Ln},children:"Connect Wallet"}),t.jsx("button",{onClick:()=>W(Bn),className:"py-3 px-6 text-sm font-semibold transition-all duration-200 "+(L===Bn?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:Ln},children:"QR Code"})]})}),k?t.jsx(Sn,{paymentData:D,selectedToken:U,selectedNetwork:F,config:c,onPaymentStarted:e=>{P(!0),"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.setItem("coinley_mobile_payment_started","true"),e.walletName},onError:e=>{q(e)}}):L===Tn?t.jsx(jn,{selectedNetwork:F,onWalletSelect:Z,onConnect:async e=>{await K(e,F)},connectedWallet:V,loading:T}):null,L===Bn&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-2",children:[t.jsx("div",{className:"text-xs font-medium text-gray-600 mb-1.5 text-center",style:{fontFamily:Ln},children:"Optimize QR for:"}),t.jsx("div",{className:"flex gap-1.5 justify-center flex-wrap",children:[{id:"metamask",name:"MetaMask",icon:"🦊"},{id:"trust",name:"Trust",icon:"🛡️"},{id:"coinbase",name:"Coinbase",icon:"💙"}].map(e=>t.jsxs("button",{onClick:()=>v(e.id),className:"flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all duration-200 "+(x===e.id?"bg-[#7042D2] text-white shadow-md":"bg-gray-100 text-gray-700 hover:bg-gray-200"),style:{fontFamily:Ln},children:[t.jsx("span",{className:"text-sm",children:e.icon}),t.jsx("span",{children:e.name})]},e.id))})]}),t.jsx(Pn,{amount:(null==D?void 0:D.totalAmount)||(null==D?void 0:D.amount)||(null==c?void 0:c.amount),currency:null==U?void 0:U.symbol,network:null==F?void 0:F.shortName,theme:p,paymentData:D,config:c,selectedToken:U,selectedNetwork:F,preferredWallet:x,compact:!0})]}),(B||ee)&&t.jsx("div",{className:"mt-4",children:t.jsx(An,{error:ee||B,onRetry:()=>{q(""),Y.resetTransaction(),"error"===X&&V&&_()},onDismiss:()=>{q(""),Y.resetTransaction()},context:"payment"})}),t.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:()=>H(En),className:"w-full py-2.5 px-3 bg-gray-200 hover:bg-gray-300 text-[#7042D2] font-semibold rounded-xl transition-all duration-200 text-sm",style:{fontFamily:Ln},children:"Back"}),t.jsx("button",{type:"button",onClick:async()=>{var e,t,n,s,a,r,i,o,c,d;if(k&&C){if(!(null==D?void 0:D.id))return void q("Payment ID not found. Please refresh and try again.");try{I(!0),H(Un),q("");const a=await y.api.checkPaymentStatus(D.id);if("completed"===(null==(e=a.payment)?void 0:e.status))H(Dn),l&&l({paymentId:D.id,transactionHash:a.payment.transactionHash,paymentDetails:a.payment});else if("pending"===(null==(t=a.payment)?void 0:t.status)){const e=await y.api.verifyQRPayment(D.id);if(e.success&&e.verified)H(Dn),l&&l({paymentId:D.id,transactionHash:null==(n=e.onChainData)?void 0:n.transactionHash,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";q(`${t}. Please complete the payment in your wallet and try again.`),H(Fn)}}else"failed"===(null==(s=a.payment)?void 0:s.status)?(q("Payment failed. Please try creating a new payment."),H(Fn)):(q("Payment not found. Please verify the payment ID and try again."),H(Fn))}catch(m){q(`Verification failed: ${m.message}. Please ensure payment was completed and try again.`),H(Fn)}finally{I(!1)}}else if(L!==Bn){if(V&&Q)try{H(Un),q("");const e=await _();e&&(q(""),Y.setTransactionError(""),H(Dn),l&&l({paymentId:D.id,transactionHash:e,paymentDetails:D}))}catch(m){H(Fn),(null==(c=m.message)?void 0:c.includes("User rejected"))||(null==(d=m.message)?void 0:d.includes("User denied"))||4001===m.code||"ACTION_REJECTED"===m.code?q("Transaction was cancelled by user. Please try again."):q(m.message||"Transaction failed. Please try again."),Y.resetTransaction()}}else{if(!(null==D?void 0:D.id))return void q("Payment ID not found. Please refresh and try again.");try{H(Un),q("");const e=await y.api.checkPaymentStatus(D.id);if("completed"===(null==(a=e.payment)?void 0:a.status))H(Dn),l&&l({paymentId:D.id,transactionHash:e.payment.transactionHash,paymentDetails:e.payment});else if("pending"===(null==(r=e.payment)?void 0:r.status)){const e=await y.api.verifyQRPayment(D.id);if(e.success&&e.verified)H(Dn),l&&l({paymentId:D.id,transactionHash:null==(i=e.onChainData)?void 0:i.transactionHash,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";q(`${t}. Please complete the payment and try again.`),H(Fn)}}else"failed"===(null==(o=e.payment)?void 0:o.status)?(q("Payment failed. Please try creating a new payment."),H(Fn)):(q("Payment not found. Please verify the payment ID and try again."),H(Fn))}catch(m){q(`Verification failed: ${m.message}. Please ensure payment was completed and try again.`),H(Fn)}}},className:"bg-green-600 text-white w-full py-2.5 px-3 font-semibold rounded-xl hover:bg-green-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 text-sm",disabled:L===Tn&&!V&&!k||k&&!C||"processing"===X||j,style:{fontFamily:Ln},children:j?"Verifying...":"processing"===X?"Processing...":k&&C?"I Have Paid":k?"Select Wallet":L===Bn?"I Have Paid":"Pay Now"})]})]})}),t.jsx(un,{currentStep:S,targetStep:Un,children:t.jsx(hn,{status:"processing",message:"approve"===X?"Approving token spending...":"splitPayment"===X?"Processing payment split...":te?"Confirming transaction on blockchain...":"Processing your payment...",theme:p,transactionHash:te,selectedNetwork:F})}),t.jsx(un,{currentStep:S,targetStep:Dn,children:t.jsx(hn,{status:"success",message:"Payment completed successfully!",theme:p,payment:D,transactionHash:te||(null==D?void 0:D.transactionHash),selectedPaymentMethod:U,selectedNetwork:F,merchantName:(null==c?void 0:c.merchantName)||"Merchant",onClose:m})}),(B||ee)&&t.jsxs("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg mx-6 mb-4",children:[t.jsx("p",{className:"text-red-800 text-sm",children:B||ee}),t.jsx("button",{onClick:()=>{q(""),Y.setTransactionError("")},className:"mt-2 text-red-600 hover:text-red-800 text-xs underline",children:"Dismiss"})]})]}),S!==Dn&&t.jsxs("div",{className:"text-center text-xs text-gray-500 flex items-center justify-center gap-1 py-6 bg-white rounded-b-3xl",style:{fontFamily:Ln},children:[t.jsxs("p",{children:["Powered by ",t.jsx("span",{className:"text-[#7042D2] font-semibold",children:"Coinley"})," - Multi-Wallet Support"]}),t.jsxs("svg",{className:"inline w-4 h-4 text-green-500 ml-1",fill:"none",stroke:"currentColor",strokeWidth:"2",viewBox:"0 0 24 24",children:[t.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M9 12l2 2 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]})})]}):null;var se},$n=e=>t.jsx(s.WagmiProvider,{config:g,children:t.jsx(a.QueryClientProvider,{client:Mn,children:t.jsx(Rn,{...e})})}),Gn=n.createContext(null),On=n.forwardRef(({customerEmail:e="",merchantName:t="",onSuccess:s,onError:a,onClose:r,theme:i="light",autoOpen:o=!1,testMode:c=!1,debug:l=!1,merchantWalletAddresses:d={}},m)=>{const u=n.useContext(Gn);if(!u)throw new Error("CoinleyCheckout must be used within a CoinleyProvider");const{openPayment:h,closePayment:p}=u,y=t=>{try{if(!t.amount||t.amount<=0)throw new Error("Amount must be greater than 0");const n={...t,customerEmail:t.customerEmail||e,merchantWalletAddresses:{...d,...t.merchantWalletAddresses},metadata:{...t.metadata,testMode:c,checkoutVersion:"1.0.0"}};h(n,{onSuccess:s,onError:a,onClose:r})}catch(n){a&&a(n)}},g=()=>{p()};return n.useImperativeHandle(m,()=>({open:y,close:g})),null});On.displayName="CoinleyCheckout";const zn={ethereum:_t,bsc:Ot,polygon:en,arbitrum:Mt,optimism:Xt,avalanche:Rt},Wn=[{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],type:"function"}];const Hn=new class{constructor(){this.clients=new Map}getClient(e){if(!this.clients.has(e)){const t=zn[e];if(!t)throw new Error(`Unsupported network: ${e}`);const n=c.createPublicClient({chain:t,transport:c.http()});this.clients.set(e,n)}return this.clients.get(e)}async checkNativeBalance(e,t){try{const n=this.getClient(t),s=await n.getBalance({address:e}),a=c.formatUnits(s,18);return{balance:parseFloat(a),balanceWei:s.toString(),symbol:this.getNativeTokenSymbol(t),decimals:18}}catch(n){throw new Error(`Failed to check native balance: ${n.message}`)}}async checkTokenBalance(e,t,n){try{const s=this.getClient(n),a=c.getContract({address:t,abi:Wn,client:s}),[r,i,o]=await Promise.all([a.read.balanceOf([e]),a.read.decimals().catch(()=>18),a.read.symbol().catch(()=>"TOKEN")]);return{balance:parseFloat(c.formatUnits(r,i)),balanceWei:r.toString(),symbol:o,decimals:i,tokenAddress:t}}catch(s){throw new Error(`Failed to check token balance: ${s.message}`)}}async validateBalance(e,t,n,s,a=!0){try{let r,i=null;r=t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,s):await this.checkNativeBalance(e,s),t.contractAddress&&a&&(i=await this.checkNativeBalance(e,s));const o=r.balance>=n,c=o?0:n-r.balance;let l=0,d=!0,m=0;if(a)if(l=this.estimateGasFee(s,!!t.contractAddress),t.contractAddress)d=i.balance>=l,m=d?0:l-i.balance;else{const e=n+l;d=r.balance>=e,m=d?0:e-r.balance}const u={isValid:o&&d,tokenBalance:r,nativeBalance:i,requiredAmount:n,estimatedGasFee:l,hasEnoughTokens:o,hasEnoughForGas:d,tokenShortfall:c,gasShortfall:m,errors:[]};if(o||u.errors.push(`Insufficient ${t.symbol} balance. Need ${n} ${t.symbol}, have ${r.balance.toFixed(6)} ${t.symbol}`),!d){const e=(null==i?void 0:i.symbol)||this.getNativeTokenSymbol(s);t.contractAddress?u.errors.push(`Insufficient ${e} for gas fees. Need ~${l.toFixed(6)} ${e}, have ${i.balance.toFixed(6)} ${e}`):u.errors.push(`Insufficient ${e} for payment + gas. Need ${(n+l).toFixed(6)} ${e} total, have ${r.balance.toFixed(6)} ${e}`)}return u}catch(r){return{isValid:!1,errors:[`Failed to check balance: ${r.message}`],tokenBalance:null,nativeBalance:null}}}estimateGasFee(e,t=!1){return{ethereum:t?.001:5e-4,bsc:t?5e-4:3e-4,polygon:t?.01:.005,arbitrum:t?3e-4:2e-4,optimism:t?3e-4:2e-4,avalanche:t?.001:5e-4}[e]||.001}getNativeTokenSymbol(e){return{ethereum:"ETH",bsc:"BNB",polygon:"MATIC",arbitrum:"ETH",optimism:"ETH",avalanche:"AVAX"}[e]||"ETH"}async getBalance(e,t,n){return t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,n):await this.checkNativeBalance(e,n)}formatBalance(e,t,n=6){return null==e?"Unknown":0===e?`0 ${t}`:e<.001?`${e.toFixed(8)} ${t}`:e<1?`${e.toFixed(6)} ${t}`:`${e.toFixed(4)} ${t}`}async checkMultipleBalances(e,t,n){try{const s=t.map(t=>this.getBalance(e,t,n).catch(e=>({error:e.message,symbol:t.symbol,balance:0})));return await Promise.all(s)}catch(s){throw s}}};class qn{constructor(e,t,n){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,this.apiKey=t,this.apiSecret=n}async request(e,t={}){const n=`${this.baseURL}${e}`,s={"Content-Type":"application/json","X-API-Key":this.apiKey,"X-API-Secret":this.apiSecret,...t.headers},a=await fetch(n,{...t,headers:s});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.error||`HTTP ${a.status}`)}return a.json()}async getNetworks(){try{return await this.request("/api/networks")}catch(e){return{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"},{id:"137",name:"Polygon",shortName:"polygon",chainId:"0x89",type:"polygon"},{id:"42161",name:"Arbitrum",shortName:"arbitrum",chainId:"0xa4b1",type:"arbitrum"},{id:"10",name:"Optimism",shortName:"optimism",chainId:"0xa",type:"optimism"},{id:"43114",name:"Avalanche",shortName:"avalanche",chainId:"0xa86a",type:"avalanche"},{id:"42220",name:"Celo",shortName:"celo",chainId:"0xa4ec",type:"celo"},{id:"8453",name:"Base",shortName:"base",chainId:"0x2105",type:"base"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(e){return{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"2",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E641a3FA62e50A9da1CE0647a2bFBC5A",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"3",name:"Binance USD",symbol:"BUSD",contractAddress:"0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"4",name:"USD Coin",symbol:"USDC",contractAddress:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"5",name:"USD Coin",symbol:"USDC",contractAddress:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"6",name:"Tether USD",symbol:"USDT",contractAddress:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"7",name:"Tether USD",symbol:"USDT",contractAddress:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"8",name:"USD Coin",symbol:"USDC",contractAddress:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"9",name:"Tether USD",symbol:"USDT",contractAddress:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"10",name:"USD Coin",symbol:"USDC",contractAddress:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"11",name:"Tether USD",symbol:"USDT",contractAddress:"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"12",name:"USD Coin",symbol:"USDC",contractAddress:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"13",name:"Tether USD",symbol:"USDT",contractAddress:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"14",name:"USD Coin",symbol:"USDC",contractAddress:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"15",name:"Tether USD",symbol:"USDT",contractAddress:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}},{id:"16",name:"USD Coin",symbol:"USDC",contractAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}async updatePaymentStatus(e,t,n=null){return await this.request(`/api/payments/${e}/status`,{method:"PUT",body:JSON.stringify({status:t,transactionHash:n})})}}class Vn{constructor(e={}){if(!e.publicKey&&!e.apiKey)throw new Error("CoinleyVanilla: publicKey or apiKey is required");if(!e.publicKey&&!e.apiSecret)throw new Error("CoinleyVanilla: apiSecret is required when using apiKey");if(!e.apiUrl)throw new Error("CoinleyVanilla: apiUrl is required");this.config={publicKey:e.publicKey||null,apiKey:e.apiKey||null,apiSecret:e.apiSecret||null,apiUrl:e.apiUrl.replace(/\/$/,""),theme:e.theme||"light",debug:e.debug||!1,...e},this.isOpen=!1,this.root=null,this.container=null,this.callbacks={},this.currentPayment=null,this.config.debug}open(e,t={}){if(!this.isOpen)try{this._validatePaymentConfig(e),this.callbacks=t,this.currentPayment=e,this._createContainer(),this.root=u.createRoot(this.container),this.isOpen=!0,this.root.render(n.createElement($n,{publicKey:this.config.publicKey,apiKey:this.config.apiKey,apiSecret:this.config.apiSecret,apiUrl:this.config.apiUrl,isOpen:!0,theme:this.config.theme,config:{amount:e.amount,customerEmail:e.customerEmail,merchantName:e.merchantName||"Merchant",callbackUrl:e.callbackUrl||this._getDefaultCallbackUrl(),merchantWalletAddresses:e.merchantWalletAddresses||{},preferredNetwork:e.preferredNetwork,preferredCurrency:e.preferredCurrency,metadata:{...e.metadata,source:"vanilla-sdk",sdkVersion:"2.0.0",timestamp:(new Date).toISOString()}},onSuccess:this._handleSuccess.bind(this),onError:this._handleError.bind(this),onClose:this._handleClose.bind(this)})),this.config.debug}catch(s){t.onError&&t.onError(s.message||"Failed to open payment modal")}}close(){this.isOpen&&(this._cleanup(),this.config.debug)}isPaymentOpen(){return this.isOpen}updateConfig(e){this.config={...this.config,...e},this.config.debug}getConfig(){return{...this.config}}getCurrentPayment(){return this.currentPayment?{...this.currentPayment}:null}_validatePaymentConfig(e){if(!e)throw new Error("Payment configuration is required");if(!e.amount||"number"!=typeof e.amount||e.amount<=0)throw new Error("Valid amount (number > 0) is required");if(!e.customerEmail||"string"!=typeof e.customerEmail)throw new Error("Customer email is required");if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.customerEmail))throw new Error("Invalid email format");if(e.merchantWalletAddresses){if("object"!=typeof e.merchantWalletAddresses)throw new Error("merchantWalletAddresses must be an object");Object.keys(e.merchantWalletAddresses).length}}_createContainer(){this.container||(this.container=document.createElement("div"),this.container.id="coinley-payment-container",this.container.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 999999;\n ",document.body.appendChild(this.container))}_getDefaultCallbackUrl(){return"undefined"!=typeof window?`${window.location.origin}/api/webhooks/coinley`:""}_handleSuccess(e,t,n){this.config.debug,this.callbacks.onSuccess&&this.callbacks.onSuccess(e,t,n)}_handleError(e){this.config.debug,this.callbacks.onError&&this.callbacks.onError(e)}_handleClose(){this._cleanup(),this.callbacks.onClose&&this.callbacks.onClose()}_cleanup(){if(this.isOpen=!1,this.root){try{this.root.unmount()}catch(e){}this.root=null}this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null),this.currentPayment=null}}function Qn(){document.querySelectorAll('script[src*="coinley-vanilla"]').forEach(e=>{const t=e.getAttribute("data-public-key"),n=e.getAttribute("data-api-key"),s=e.getAttribute("data-api-secret"),a=e.getAttribute("data-api-url"),r=e.getAttribute("data-theme")||"light",i=e.hasAttribute("data-debug");if((t||n&&s)&&a)try{window.coinley=new Vn({publicKey:t,apiKey:n,apiSecret:s,apiUrl:a,theme:r,debug:i})}catch(o){}})}"undefined"!=typeof window&&(window.CoinleyVanilla=Vn,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Qn):Qn());class Kn{constructor(e="https://paymentscreen.vercel.app/"){this.basePaymentUrl=e.endsWith("/")?e:e+"/"}generatePaymentURL(e){const{merchant:t,amount:n,productAmount:s,platformFee:a,networkFee:r,token:i="USDC",network:o="Ethereum Mainnet",merchantAddress:c}=e;if(!t)throw new Error("Merchant name is required");if(!n)throw new Error("Amount is required");if(!c)throw new Error("Merchant address (smart contract) is required");const l=s||.95*n,d=a||.03*n,m=r||.02*n,u=new URLSearchParams({merchant:t,amount:n.toString(),productAmount:l.toString(),platformFee:d.toString(),networkFee:m.toString(),token:i,network:o,merchantAddress:c});return this.basePaymentUrl+"?"+u.toString()}async generateQRCode(e,t={}){const{width:n=300,margin:s=2,colorDark:a="#7c3aed",colorLight:r="#ffffff"}=t;try{const t=this.generatePaymentURL(e);return{qrCodeDataURL:await d.toDataURL(t,{width:n,margin:s,color:{dark:a,light:r}}),paymentURL:t,paymentData:{...e,qrCodeUrl:t}}}catch(i){throw new Error(`Failed to generate QR code: ${i.message}`)}}async generateQRCodeToCanvas(e,t,n={}){const{width:s=300,margin:a=2,colorDark:r="#7c3aed",colorLight:i="#ffffff"}=n;try{const n=this.generatePaymentURL(e);return await d.toCanvas(t,n,{width:s,margin:a,color:{dark:r,light:i}}),n}catch(o){throw new Error(`Failed to generate QR code to canvas: ${o.message}`)}}validatePaymentData(e){const t=[],n=[];e.merchant||t.push("Merchant name is required"),(!e.amount||e.amount<=0)&&t.push("Valid amount is required"),e.merchantAddress||t.push("Merchant address (smart contract) is required"),e.merchantAddress&&!/^0x[a-fA-F0-9]{40}$/.test(e.merchantAddress)&&t.push("Invalid Ethereum address format for merchantAddress"),e.amount>1e4&&n.push("Large payment amount detected");return(e.platformFee||0)+(e.networkFee||0)>.1*e.amount&&n.push("High fees detected (>10% of total amount)"),{isValid:0===t.length,errors:t,warnings:n}}async createPaymentQR(e){const{merchantName:t,amount:n,productAmount:s,platformFee:a,networkFee:r,token:i,network:o,merchantWalletAddresses:c,selectedNetwork:l="ethereum",...d}=e,m={merchant:t||"Coinley Merchant",amount:n,productAmount:s,platformFee:a,networkFee:r,token:i||"USDC",network:o||"Ethereum Mainnet",merchantAddress:(null==c?void 0:c[l])||(null==c?void 0:c.ethereum)||(null==c?void 0:c.splitPaymentContract),...d},u=this.validatePaymentData(m);if(!u.isValid)throw new Error(`Payment validation failed: ${u.errors.join(", ")}`);return{...await this.generateQRCode(m),validation:u,instructions:{userAction:"Scan this QR code with your mobile wallet to pay",expectedFlow:"QR Scan → Payment Screen → Wallet Connect → Split Payment → Confirmation",supportedWallets:["MetaMask","Trust Wallet","Coinbase Wallet","WalletConnect compatible wallets"]}}}}const Zn=new Kn,Yn={formatAmount:(e,t=2)=>e.toFixed(t),truncateAddress:(e,t=6,n=4)=>e?e.length<=t+n?e:`${e.slice(0,t)}...${e.slice(-n)}`:"",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 _n extends Error{constructor(e,t){super(e),this.name="CoinleyError",this.code=t}}const Jn={react:'\nimport { CoinleyProvider, CoinleyCheckout } from \'coinley-test\';\n\n// New recommended way - using publicKey only\n<CoinleyProvider\n publicKey="pk_your-public-key"\n apiUrl="https://api.coinley.io"\n>\n <CoinleyCheckout\n ref={checkoutRef}\n onSuccess={(paymentId, txHash, details) => console.log(\'Success!\')}\n onError={(error) => console.error(\'Error:\', error)}\n onClose={() => console.log(\'Closed\')}\n />\n</CoinleyProvider>\n\n// Legacy way (still supported) - using apiKey + apiSecret\n<CoinleyProvider\n apiKey="your-api-key"\n apiSecret="your-api-secret"\n apiUrl="https://api.coinley.io"\n>\n ...\n</CoinleyProvider>\n ',vanilla:'\n\x3c!-- Include via CDN --\x3e\n<script src="https://unpkg.com/coinley-test@latest/vanilla"><\/script>\n<link rel="stylesheet" href="https://unpkg.com/coinley-test@latest/vanilla/style.css">\n\n<script>\n// New recommended way - using publicKey only\nconst coinley = new CoinleyVanilla({\n publicKey: "pk_your-public-key",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Legacy way (still supported)\nconst coinleyLegacy = new CoinleyVanilla({\n apiKey: "your-api-key",\n apiSecret: "your-api-secret",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Use in checkout\ncoinley.open({\n amount: 100,\n customerEmail: "customer@example.com",\n merchantName: "Your Store",\n merchantWalletAddresses: {\n ethereum: "0x...",\n bsc: "0x..."\n }\n}, {\n onSuccess: (paymentId, txHash, details) => console.log(\'Success!\'),\n onError: (error) => console.error(\'Error:\', error),\n onClose: () => console.log(\'Closed\')\n});\n<\/script>\n '};e.CoinleyCheckout=On,e.CoinleyError=_n,e.CoinleyProvider=({publicKey:e,apiKey:s,apiSecret:a,apiUrl:r,theme:i="light",debug:o=!1,children:c})=>{const[l,d]=n.useState(!1),[m,u]=n.useState(null),[h,p]=n.useState({}),[y,g]=n.useState(""),f=()=>{d(!1),u(null),h.onClose&&h.onClose()},b={openPayment:(e,t)=>{u(e),t&&p(t),d(!0)},closePayment:f};return t.jsxs(Gn.Provider,{value:b,children:[c,l&&m&&t.jsx($n,{publicKey:e,apiKey:s,apiSecret:a,apiUrl:r,isOpen:l,config:m,theme:i,debug:o,merchantName:y,onSuccess:h.onSuccess,onError:h.onError,onClose:f})]})},e.CoinleyVanilla=Vn,e.DEFAULT_CONFIG={theme:"light",debug:!1,testMode:!1,autoOpen:!1},e.EnhancedSimpleCoinleyPayment=$n,e.PaymentAPI=class{constructor(e,t,n=null){t&&t.startsWith("pk_")?(this.publicKey=t,this.apiKey=null,this.apiSecret=null):(this.publicKey=null,this.apiKey=t,this.apiSecret=n),this.api=m.create({baseURL:e.endsWith("/")?e.slice(0,-1):e,timeout:3e4,headers:{"Content-Type":"application/json"}}),this.api.interceptors.request.use(e=>{if(this.publicKey)e.headers["x-public-key"]=this.publicKey;else{e.headers["x-api-key"]=this.apiKey,e.headers["x-api-secret"]=this.apiSecret;const t=this.generateMerchantToken();t&&(e.headers.Authorization=`Bearer ${t}`)}return e},e=>Promise.reject(e)),this.api.interceptors.response.use(e=>e,e=>{var t,n,s;if(401===(null==(t=e.response)?void 0:t.status))throw new Error("Authentication failed. Please check your API credentials.");if(404===(null==(n=e.response)?void 0:n.status))throw new Error("API endpoint not found. Please check your API URL.");if((null==(s=e.response)?void 0:s.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 null}}async request(e,t={}){var n,s;try{return(await this.api({url:e,method:t.method||"GET",data:t.data||t.body?JSON.parse(t.body||"{}"):void 0,...t})).data}catch(a){if(null==(s=null==(n=a.response)?void 0:n.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Request failed")}}async createPayment(e){var t,n;try{return(await this.api.post("/api/payments/create",e)).data}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to create payment")}}async getPayment(e){var t,n;try{return(await this.api.get(`/api/payments/${e}`)).data}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.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{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{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,n;try{return(await this.api.post("/api/payments/verify-qr",{paymentId:e})).data}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to verify payment")}}async processPayment(e,t,n,s){var a;try{return(await this.api.post("/api/payments/process",{paymentId:e,transactionHash:t,network:n,senderAddress:s})).data}catch(r){if(null==(a=r.response)?void 0:a.data){const e=r.response.data,t=e.error||e.message||"Payment processing failed",n=new Error(t);throw n.isAlreadyCompleted=e.isAlreadyCompleted||!1,n.verificationAttempts=e.verificationAttempts||0,n.statusCode=r.response.status,n.originalData=e,n}throw new Error(r.message||"Failed to process PaymentSplitter transaction")}}async getContractInfo(e){var t,n;try{return(await this.api.get(`/api/payments/contract/${e}`)).data.contractInfo}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to get contract information")}}async getPaymentSplitterStatus(e){var t,n;try{return(await this.api.get(`/api/payments/splitter-status/${e}`)).data.paymentSplitterStatus}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to get PaymentSplitter status")}}async checkPaymentSplitterHealth(){try{return(await this.api.get("/api/payments/health")).data.paymentSplitterHealth}catch(e){return{error:e.message}}}async healthCheck(){try{return 200===(await this.api.get("/api/health")).status}catch(e){return!1}}},e.PaymentQRGenerator=Kn,e.QRCodePayment=({apiKey:e,apiSecret:s,apiUrl:a,config:r,onSuccess:i,onError:o,onClose:c,isOpen:l,theme:m="light",mode:u="splitpayment",splitPaymentUrl:h="https://paymentscreen.vercel.app/"})=>{var p;const[y,g]=n.useState("network"),[f,b]=n.useState([]),[x,w]=n.useState([]),[v,k]=n.useState(null),[N,C]=n.useState(null),[P,j]=n.useState(null),[I,S]=n.useState(!1),[A,E]=n.useState(""),[F,U]=n.useState(""),[D,T]=n.useState(""),[B,L]=n.useState(""),[M,R]=n.useState(!1),[$,G]=n.useState(""),[O,z]=n.useState(!1),[W,H]=n.useState(null),q=n.useRef(new qn(a,e,s)),V=n.useRef(null);n.useEffect(()=>(l&&(K(),Q()),()=>{V.current&&clearInterval(V.current)}),[l]);const Q=()=>{g("network"),k(null),C(null),j(null),E(""),U(""),T(""),L(""),R(!1),G(""),z(!1),H(null),V.current&&clearInterval(V.current)},K=async()=>{try{S(!0),E("");const[e,t]=await Promise.all([q.current.getNetworks(),q.current.getTokens()]);b(e.networks||[]),w(t.stablecoins||[])}catch(e){E("Failed to load payment options.")}finally{S(!1)}},Z=async e=>{if(!N||!v||!P)return!1;try{const t=await Hn.validateBalance(e,N,P.totalAmount,v.shortName,!0);return H(t),!!t.isValid||(E(`Insufficient balance: ${t.errors.join(", ")}`),!1)}catch(t){return E(`Failed to check balance: ${t.message}`),!1}};if(!l)return null;const Y="dark"===m;return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:t.jsxs("div",{className:"rounded-lg shadow-xl max-w-md w-full mx-4 "+(Y?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[t.jsxs("div",{className:"p-4 border-b flex justify-between items-center "+(Y?"border-gray-700":"border-gray-200"),children:[t.jsxs("div",{className:"text-center flex-1",children:[t.jsx("h2",{className:"text-lg font-semibold",children:"splitpayment"===u?"Split Payment QR":"QR Code Payment"}),r.amount&&t.jsxs("p",{className:"text-2xl font-bold text-purple-600",children:["$",r.amount.toFixed(2)]}),t.jsx("p",{className:"text-xs text-blue-600",children:"splitpayment"===u?"📱 Scan to redirect to payment screen":"📱 Scan with mobile wallet"})]}),t.jsx("button",{onClick:c,className:"ml-4 text-gray-500 hover:text-gray-700 "+(Y?"hover:text-gray-300":""),children:"✕"})]}),t.jsxs("div",{className:"p-4 min-h-[400px]",children:[A&&t.jsxs("div",{className:"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200",children:[A,t.jsx("button",{onClick:()=>E(""),className:"ml-2 text-red-500 hover:text-red-700",children:"✕"})]}),"network"===y&&t.jsxs("div",{className:"space-y-4",children:[t.jsx("h3",{className:"font-medium text-center",children:"Select Network"}),t.jsx("div",{className:"space-y-2",children:f.map(e=>{var n;const s=null==(n=r.merchantWalletAddresses)?void 0:n[e.shortName];return t.jsxs("button",{onClick:()=>{k(e),g("token")},disabled:!s,className:"w-full p-3 border rounded-lg text-left transition-colors "+(s?"hover:border-purple-500 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"):"opacity-50 cursor-not-allowed "+(Y?"border-gray-700":"border-gray-100")),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsxs("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:[e.shortName.toUpperCase(),!s&&" (No merchant address configured)"]})]},e.id)})})]}),"token"===y&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("button",{onClick:()=>g("network"),className:""+(Y?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),t.jsxs("h3",{className:"font-medium",children:["Select Token on ",null==v?void 0:v.name]})]}),t.jsx("div",{className:"space-y-2",children:x.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==v?void 0:v.shortName)}).map(e=>t.jsxs("button",{onClick:()=>{C(e),(async e=>{var t,n;try{S(!0),E("");const s={amount:r.amount,currency:e.symbol,network:v.shortName,customerEmail:r.customerEmail,callbackUrl:r.callbackUrl,metadata:{...r.metadata,merchantWalletAddresses:r.merchantWalletAddresses,paymentMethod:"split_payment_qr",selectedNetwork:v.shortName,selectedToken:e.symbol}},a=await q.current.createPayment(s);j(a.payment);const i=(null==(t=r.merchantWalletAddresses)?void 0:t.splitPaymentContract)||(null==(n=r.merchantWalletAddresses)?void 0:n[v.shortName]);if(!i)throw new Error("Split payment contract address not found in config");const o=new URLSearchParams({merchant:r.merchantName||"Coinley Merchant",amount:a.payment.totalAmount.toString(),productAmount:(.95*a.payment.totalAmount).toFixed(2),platformFee:(.03*a.payment.totalAmount).toFixed(2),networkFee:(.02*a.payment.totalAmount).toFixed(2),token:e.symbol,network:v.name,merchantAddress:i,paymentId:a.payment.id}),c=h+"?"+o.toString();U(c);const l=await d.toDataURL(c,{width:256,margin:2,color:{dark:"#7c3aed",light:"#ffffff"}});T(l),g("scan")}catch(s){E(s.message||"Failed to generate split payment QR code")}finally{S(!1)}})(e)},disabled:I,className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors disabled:opacity-50 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsx("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:e.symbol})]},e.id))})]}),"scan"===y&&t.jsx("div",{className:"space-y-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("h3",{className:"font-medium mb-4",children:"splitpayment"===u?"Scan QR Code to Open Payment Screen":"Scan QR Code with Mobile Wallet"}),D?t.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[t.jsx("div",{className:"p-4 rounded-lg "+(Y?"bg-gray-800":"bg-gray-50"),children:t.jsx("img",{src:D,alt:"Payment QR Code",className:"mx-auto",style:{width:"200px",height:"200px"}})}),t.jsxs("div",{className:"text-sm space-y-1 "+(Y?"text-gray-300":"text-gray-600"),children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Amount:"}),t.jsxs("span",{className:"font-medium",children:[null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Network:"}),t.jsx("span",{className:"font-medium",children:null==v?void 0:v.name})]}),"splitpayment"===u&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Merchant:"}),t.jsx("span",{className:"font-medium",children:r.merchantName||"Coinley Merchant"})]})]}),t.jsx("div",{className:"p-3 rounded-lg text-xs "+(Y?"bg-blue-900 text-blue-200":"bg-blue-50 text-blue-600"),children:"splitpayment"===u?t.jsxs(t.Fragment,{children:["📱 Scan this QR code with your mobile wallet to open the payment screen.",t.jsx("br",{}),"The payment screen will auto-connect your wallet and execute the split payment."]}):"📱 Open your mobile wallet and scan this QR code to connect and pay"}),"splitpayment"===u?t.jsx("button",{onClick:()=>window.open(F,"_blank"),className:"w-full bg-purple-600 text-white py-2 px-4 rounded hover:bg-purple-700 text-sm",children:"🔗 Test Payment Screen (Opens in new tab)"}):t.jsx("button",{onClick:async()=>{try{S(!0),E("");const e="0x742d35Cc6634C0532925a3b8D9a5C7C47C77E4";G(e),R(!0),await Z(e),g("confirm")}catch(e){E("Failed to simulate wallet connection")}finally{S(!1)}},disabled:I,className:"w-full bg-gray-600 text-white py-2 px-4 rounded hover:bg-gray-700 disabled:opacity-50 text-sm",children:I?"Connecting...":"🧪 Simulate Wallet Scan (Test)"})]}):t.jsxs("div",{className:"flex items-center justify-center py-8",children:[t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"}),t.jsx("span",{className:"ml-2",children:"Generating QR Code..."})]})]})}),"confirm"===y&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4",children:t.jsx("span",{className:"text-2xl",children:"📱"})}),t.jsx("h3",{className:"font-medium",children:"Mobile Wallet Connected"}),t.jsx("p",{className:"text-sm mt-2 "+(Y?"text-gray-300":"text-gray-600"),children:"Ready to complete payment"})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-200",children:[t.jsx("p",{className:"text-green-600 text-sm font-medium",children:"✅ Wallet Connected"}),t.jsxs("p",{className:"font-mono text-xs text-green-700 mt-1",children:[null==$?void 0:$.slice(0,6),"...",null==$?void 0:$.slice(-4)]})]}),W&&t.jsx("div",{className:"p-3 rounded-lg border "+(W.isValid?"bg-green-50 border-green-200":"bg-red-50 border-red-200"),children:t.jsxs("div",{className:"space-y-2 text-sm",children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Required:"}),t.jsxs("span",{className:"font-medium",children:[null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Your Balance:"}),t.jsx("span",{className:"font-medium "+(W.hasEnoughTokens?"text-green-600":"text-red-600"),children:Hn.formatBalance(null==(p=W.tokenBalance)?void 0:p.balance,null==N?void 0:N.symbol)})]}),W.nativeBalance&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Gas Balance:"}),t.jsx("span",{className:"font-medium "+(W.hasEnoughForGas?"text-green-600":"text-red-600"),children:Hn.formatBalance(W.nativeBalance.balance,W.nativeBalance.symbol)})]})]})}),t.jsx("button",{onClick:async()=>{try{z(!0),E("");const e=`0x${Math.random().toString(16).substring(2,66)}`;await new Promise(e=>setTimeout(e,3e3)),g("success"),null==i||i(P.id,e,{network:v.name,token:N.symbol,amount:P.totalAmount,method:"qr_code",walletAddress:$})}catch(e){E("Transaction confirmation failed")}finally{z(!1)}},disabled:O||!(null==W?void 0:W.isValid),className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium",children:O?"Processing Payment...":(null==W?void 0:W.isValid)?`Confirm Payment of ${null==P?void 0:P.totalAmount} ${null==N?void 0:N.symbol}`:"Insufficient Balance"})]})]}),"success"===y&&t.jsxs("div",{className:"text-center space-y-4",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:t.jsx("span",{className:"text-2xl",children:"✅"})}),t.jsx("h3",{className:"font-medium text-green-600",children:"Payment Successful!"}),t.jsx("p",{className:"text-sm "+(Y?"text-gray-300":"text-gray-600"),children:"Transaction completed via QR code scan"}),t.jsx("button",{onClick:c,className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 font-medium",children:"Close"})]}),I&&"scan"!==y&&"confirm"!==y&&t.jsx("div",{className:"flex items-center justify-center py-8",children:t.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]=n.useState(e);return n.useEffect(()=>{document.documentElement.setAttribute("data-coinley-theme",a)},[a]),t.jsx("div",{className:`coinley-theme-${a}`,children:s})},e.USAGE_EXAMPLES=Jn,e.VERSION="0.0.26",e.generatePaymentQR=(e,t)=>Zn.generateQRCode(e,t),e.generatePaymentURL=e=>Zn.generatePaymentURL(e),e.paymentQR=Zn,e.useCoinley=()=>{const e=n.useContext(Gn);if(!e)throw new Error("useCoinley must be used within a CoinleyProvider");return e},e.utils=Yn,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
3
3
|
//# sourceMappingURL=index.umd.js.map
|