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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/assets/Logomark.png","../src/components/enhanced-payment/config/wagmiConfig.js","../src/components/enhanced-payment/api/paymentAPI.js","../src/components/enhanced-payment/hooks/usePaymentFlow.js","../src/components/enhanced-payment/config/chainConfig.js","../src/components/enhanced-payment/hooks/useWalletConnection.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/chain/defineChain.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/version.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/base.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/encoding.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/isHex.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/size.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/trim.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/data.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/pad.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/encoding/toHex.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/encoding/toBytes.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/encoding/fromHex.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/formatter.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/transaction.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/block.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/log.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/transactionReceipt.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/transactionRequest.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/constants/number.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/concat.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/cursor.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/cursor.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/encoding/toRlp.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/constants/unit.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/unit/formatUnits.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/unit/formatGwei.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/transaction.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/blobsToCommitments.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/blobsToProofs.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/hash/sha256.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/constants/blob.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/constants/kzg.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/blob.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/toBlobs.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/toBlobSidecars.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/address.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/chain.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/node.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/lru.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/hash/keccak256.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/address/getAddress.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/address/isAddress.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/slice.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/transaction/assertTransaction.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/transaction/getTransactionType.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/transaction/serializeAccessList.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/transaction/serializeTransaction.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/op-stack/contracts.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/op-stack/formatters.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/op-stack/serializers.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/op-stack/chainConfig.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/arbitrum.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/avalanche.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/base.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/bsc.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/celo/fees.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/celo/utils.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/celo/formatters.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/celo/serializers.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/celo/chainConfig.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/celo.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/mainnet.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/optimism.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/polygon.js","../src/components/enhanced-payment/utils/contractUtils.js","../src/components/enhanced-payment/utils/errorUtils.js","../src/components/enhanced-payment/hooks/useTransactionHandling.js","../src/components/enhanced-payment/components/ModernDropdown.jsx","../src/components/enhanced-payment/components/ScreenTransition.jsx","../src/components/enhanced-payment/utils/formatUtils.js","../src/components/enhanced-payment/components/PaymentStatus.jsx","../src/components/enhanced-payment/config/logoConfig.js","../src/components/enhanced-payment/utils/walletUtils.js","../src/components/enhanced-payment/utils/deepLinkUtils.js","../src/components/enhanced-payment/components/QRCodeDisplay.jsx","../src/components/enhanced-payment/components/WalletSelector.jsx","../src/utils/debugUtils.js","../src/components/enhanced-payment/components/MobileWalletDropdown.jsx","../src/components/enhanced-payment/components/ErrorDisplay.jsx","../src/components/enhanced-payment/constants/index.js","../src/components/EnhancedSimpleCoinleyPayment.jsx","../src/CoinleyProvider.jsx","../src/PaymentAPI.js","../src/utils/balanceChecker.js","../src/components/QRCodePayment.jsx","../src/vanilla/index.js","../src/utils/paymentQRGenerator.js","../src/index.js"],"sourcesContent":["export default \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABxCAYAAAAj+QZ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vqQk3E3SYkw7n2oUnJsAkRwmEFiXzn/gYkJQOXEGFP51Eue07zhREwJCkZupVldxYWLH/VB1cXat5fdaJhE8JriwUl3nTRrk4T3Bbdq1NCDUEYNCFm87Z8SAtzUukMOoK94bHo7Yw6orMjbTmxDOD05U/SBz2l2wab3ncgjS78H0eagrHjdQciAAAAAElFTkSuQmCC\"","import { createConfig, http, fallback } from '@wagmi/core';\nimport { mainnet, bsc, polygon, arbitrum, optimism, avalanche, celo, base } from '@wagmi/core/chains';\nimport { injected, metaMask, coinbaseWallet } from '@wagmi/connectors';\nimport logo from \"../../../assets/Logomark.png\";\n\n// Alchemy API configuration - Dual keys for failover\nconst ALCHEMY_API_KEY_PRIMARY = 'YWG990wOlIikc1tU7-WWTepfU8d1f4dp';\nconst ALCHEMY_API_KEY_SECONDARY = 'qtIcCe_-8t4rIWktnWJm0';\n\n// Version tracking for debugging\nconst WAGMI_CONFIG_VERSION = '2.7.0-dual-alchemy-keys';\nconsole.log('🔧 SDK wagmiConfig version:', WAGMI_CONFIG_VERSION);\nconsole.log('🌐 SDK RPC config:', 'Dual Alchemy keys (primary + secondary failover) + Public fallbacks (3-4 endpoints per chain)');\nconsole.log('⚡ Alchemy networks: ALL 8 CHAINS (Ethereum, BSC, Polygon, Arbitrum, Optimism, Avalanche, Celo, Base)');\nconsole.log('🔐 Alchemy failover: 2 API keys for maximum reliability (auto-failover on rate limit/error)');\nconsole.log('✅ Ethereum simulation bypass: Working (proven by Etherscan 100% success rate)');\nconsole.log('🔍 Enhanced error extraction: Hex error data, panic detection, custom errors');\nconsole.log('🎯 UX improvement: Blockchain explorer links added to success screen');\nconsole.log('🔄 Balance check fallback: Wallet RPC → App fallback RPC (fixes Coinbase Wallet issues)');\nconsole.log('🔧 ChainId normalization: Unified normalizeChainId() util handles hex/decimal/number');\nconsole.log('⏳ Backend sync delay: 8s wait before API call (prevents RPC indexing lag errors)');\n\n// Dynamic connectors based on device\nconst getConnectors = () => {\n const baseConnectors = [\n injected(),\n metaMask({\n dappMetadata: {\n name: 'Coinley Payment',\n icon: logo\n }\n }),\n coinbaseWallet({\n appName: 'Coinley Payment',\n appLogoUrl: logo\n })\n ];\n\n return baseConnectors;\n};\n\nexport const wagmiConfig = createConfig({\n chains: [mainnet, bsc, polygon, arbitrum, optimism, avalanche, celo, base],\n connectors: getConnectors(),\n transports: {\n // Dual Alchemy keys (primary + secondary) + Public fallbacks for maximum reliability\n [mainnet.id]: fallback([\n http(`https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://cloudflare-eth.com', { timeout: 10_000, retryCount: 1 }),\n http('https://eth.llamarpc.com', { timeout: 10_000, retryCount: 1 }),\n http('https://ethereum.publicnode.com', { timeout: 10_000, retryCount: 1 }),\n ]),\n [bsc.id]: fallback([\n http(`https://bnb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://bnb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://bsc-dataseed.bnbchain.org', { timeout: 10_000, retryCount: 1 }),\n http('https://bsc-dataseed-public.bnbchain.org', { timeout: 10_000, retryCount: 1 }),\n http('https://bsc.nodereal.io', { timeout: 10_000, retryCount: 1 }),\n ]),\n [polygon.id]: fallback([\n http(`https://polygon-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://polygon-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://polygon.llamarpc.com', { timeout: 10_000, retryCount: 1 }),\n http('https://polygon-rpc.com', { timeout: 10_000, retryCount: 1 }),\n http('https://polygon.drpc.org', { timeout: 10_000, retryCount: 1 }),\n ]),\n [arbitrum.id]: fallback([\n http(`https://arb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://arb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://arb1.arbitrum.io/rpc', { timeout: 10_000, retryCount: 1 }),\n http('https://arbitrum.llamarpc.com', { timeout: 10_000, retryCount: 1 }),\n ]),\n [optimism.id]: fallback([\n http(`https://opt-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://opt-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://mainnet.optimism.io', { timeout: 10_000, retryCount: 1 }),\n http('https://optimism.llamarpc.com', { timeout: 10_000, retryCount: 1 }),\n ]),\n [avalanche.id]: fallback([\n http(`https://avax-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://avax-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://api.avax.network/ext/bc/C/rpc', { timeout: 10_000, retryCount: 1 }),\n http('https://avalanche.public-rpc.com', { timeout: 10_000, retryCount: 1 }),\n ]),\n [celo.id]: fallback([\n http(`https://celo-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://celo-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://forno.celo.org', { timeout: 10_000, retryCount: 1 }),\n http('https://celo.drpc.org', { timeout: 10_000, retryCount: 1 }),\n ]),\n [base.id]: fallback([\n http(`https://base-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://base-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://mainnet.base.org', { timeout: 10_000, retryCount: 1 }),\n http('https://base.llamarpc.com', { timeout: 10_000, retryCount: 1 }),\n http('https://base.meowrpc.com', { timeout: 10_000, retryCount: 1 }),\n ]),\n },\n});\n\nexport { getConnectors };","// Payment API class for backend communication\n// Supports both new publicKey auth and legacy apiKey+apiSecret auth\n\nexport class SimplePaymentAPI {\n constructor(baseURL, publicKeyOrApiKey, apiSecret = null) {\n this.baseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;\n\n // Determine if using new publicKey auth (starts with 'pk_') or legacy auth\n if (publicKeyOrApiKey && publicKeyOrApiKey.startsWith('pk_')) {\n // New public key authentication\n this.publicKey = publicKeyOrApiKey;\n this.apiKey = null;\n this.apiSecret = null;\n } else {\n // Legacy authentication with apiKey + apiSecret\n this.publicKey = null;\n this.apiKey = publicKeyOrApiKey;\n this.apiSecret = apiSecret;\n }\n }\n\n async request(endpoint, options = {}) {\n const url = `${this.baseURL}${endpoint}`;\n\n // Build headers based on authentication method\n const headers = {\n 'Content-Type': 'application/json',\n ...options.headers\n };\n\n // Use public key if available (new method), otherwise use legacy auth\n if (this.publicKey) {\n headers['X-Public-Key'] = this.publicKey;\n } else {\n headers['X-API-Key'] = this.apiKey;\n headers['X-API-Secret'] = this.apiSecret;\n }\n\n // ✅ Add timeout to prevent infinite hanging (critical for blockchain calls)\n const timeout = options.timeout || 60000; // Default 60 seconds\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n ...options,\n headers,\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new Error(error.error || `HTTP ${response.status}`);\n }\n\n return response.json();\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error.name === 'AbortError') {\n throw new Error(`Request timeout after ${timeout / 1000}s: ${endpoint}`);\n }\n throw error;\n }\n }\n\n async getNetworks() {\n try {\n return await this.request('/api/networks');\n } catch (error) {\n console.error('Failed to fetch networks:', error);\n return {\n networks: [\n { id: '1', name: 'Ethereum', shortName: 'ethereum', chainId: '0x1', type: 'ethereum' },\n { id: '56', name: 'BSC', shortName: 'bsc', chainId: '0x38', type: 'bsc' },\n { id: '137', name: 'Polygon', shortName: 'polygon', chainId: '0x89', type: 'polygon' },\n { id: '42161', name: 'Arbitrum', shortName: 'arbitrum', chainId: '0xa4b1', type: 'arbitrum' },\n { id: '10', name: 'Optimism', shortName: 'optimism', chainId: '0xa', type: 'optimism' },\n { id: '43114', name: 'Avalanche', shortName: 'avalanche', chainId: '0xa86a', type: 'avalanche' }\n ]\n };\n }\n }\n\n async getTokens() {\n try {\n return await this.request('/api/networks/stablecoins');\n } catch (error) {\n console.error('Failed to fetch tokens:', error);\n return {\n stablecoins: [\n // Ethereum Network\n {\n id: '1', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n decimals: 6, networkId: '1',\n Network: { shortName: 'ethereum', name: 'Ethereum' }\n },\n {\n id: '2', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n decimals: 6, networkId: '1',\n Network: { shortName: 'ethereum', name: 'Ethereum' }\n },\n\n // BSC Network\n {\n id: '3', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x55d398326f99059fF775485246999027B3197955',\n decimals: 18, networkId: '56',\n Network: { shortName: 'bsc', name: 'BSC' }\n },\n {\n id: '4', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',\n decimals: 18, networkId: '56',\n Network: { shortName: 'bsc', name: 'BSC' }\n },\n\n // Polygon Network (Native USDC)\n {\n id: '5', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xc2132D05D31c914a87c6611C10748AEb04B58e8F',\n decimals: 6, networkId: '137',\n Network: { shortName: 'polygon', name: 'Polygon' }\n },\n {\n id: '6', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',\n decimals: 6, networkId: '137',\n Network: { shortName: 'polygon', name: 'Polygon' }\n },\n\n // Arbitrum Network (Native USDC)\n {\n id: '7', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',\n decimals: 6, networkId: '42161',\n Network: { shortName: 'arbitrum', name: 'Arbitrum' }\n },\n {\n id: '8', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n decimals: 6, networkId: '42161',\n Network: { shortName: 'arbitrum', name: 'Arbitrum' }\n },\n\n // Optimism Network\n {\n id: '9', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58',\n decimals: 6, networkId: '10',\n Network: { shortName: 'optimism', name: 'Optimism' }\n },\n {\n id: '10', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n decimals: 6, networkId: '10',\n Network: { shortName: 'optimism', name: 'Optimism' }\n },\n\n // Avalanche Network\n {\n id: '11', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7',\n decimals: 6, networkId: '43114',\n Network: { shortName: 'avalanche', name: 'Avalanche' }\n },\n {\n id: '12', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',\n decimals: 6, networkId: '43114',\n Network: { shortName: 'avalanche', name: 'Avalanche' }\n },\n\n // Celo Network (Native USDC)\n {\n id: '13', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e',\n decimals: 6, networkId: '42220',\n Network: { shortName: 'celo', name: 'Celo' }\n },\n {\n id: '14', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xcebA9300f2b948710d2653dD7B07f33A8B32118C',\n decimals: 6, networkId: '42220',\n Network: { shortName: 'celo', name: 'Celo' }\n },\n\n // Base Network\n {\n id: '15', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2',\n decimals: 6, networkId: '8453',\n Network: { shortName: 'base', name: 'Base' }\n },\n {\n id: '16', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n decimals: 6, networkId: '8453',\n Network: { shortName: 'base', name: 'Base' }\n }\n ]\n };\n }\n }\n\n async createPayment(data) {\n return await this.request('/api/payments/create', {\n method: 'POST',\n body: JSON.stringify(data)\n });\n }\n\n async verifyQRPayment(paymentId) {\n return await this.request('/api/payments/verify-qr', {\n method: 'POST',\n body: JSON.stringify({ paymentId })\n });\n }\n\n async checkPaymentStatus(paymentId) {\n return await this.request(`/api/payments/status/${paymentId}`);\n }\n\n async getContractInfo(chainId) {\n try {\n const response = await this.request(`/api/payments/contract/${chainId}`);\n if (!response.success) {\n throw new Error('Contract not supported on this network');\n }\n return response.contractInfo;\n } catch (error) {\n console.error('❌ Failed to get contract info:', error);\n throw new Error(error.message || 'Failed to get contract information');\n }\n }\n\n async processPayment(paymentId, transactionHash, network, senderAddress) {\n // ✅ Longer timeout for blockchain verification (90 seconds)\n console.log('📤 [API] processPayment called with:', {\n paymentId,\n transactionHash,\n network,\n senderAddress,\n baseURL: this.baseURL,\n hasPublicKey: !!this.publicKey,\n hasApiKey: !!this.apiKey,\n hasApiSecret: !!this.apiSecret\n });\n\n try {\n const result = await this.request('/api/payments/process', {\n method: 'POST',\n body: JSON.stringify({\n paymentId,\n transactionHash,\n network,\n senderAddress\n }),\n timeout: 90000 // 90 seconds - blockchain verification can be slow\n });\n console.log('✅ [API] processPayment succeeded:', result);\n return result;\n } catch (error) {\n console.error('❌ [API] processPayment failed:', {\n error: error.message,\n name: error.name,\n stack: error.stack\n });\n throw error;\n }\n }\n\n async failPayment(paymentId, reason = 'Payment cancelled by user') {\n return await this.request('/api/payments/fail', {\n method: 'POST',\n body: JSON.stringify({\n paymentId,\n reason,\n status: 'failed'\n })\n });\n }\n}","import { useState, useEffect, useRef } from 'react';\nimport { SimplePaymentAPI } from '../api/paymentAPI';\n\nexport const usePaymentFlow = (apiUrl, apiKey, apiSecret) => {\n const [currentStep, setCurrentStep] = useState('method');\n const [networks, setNetworks] = useState([]);\n const [tokens, setTokens] = useState([]);\n const [selectedNetwork, setSelectedNetwork] = useState(null);\n const [selectedToken, setSelectedToken] = useState(null);\n const [paymentMethod, setPaymentMethod] = useState(null);\n const [paymentData, setPaymentData] = useState(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState('');\n const [processing, setProcessing] = useState(false);\n const [processingMessage, setProcessingMessage] = useState('Processing transaction...');\n const [paymentType, setPaymentType] = useState('wallet');\n const [actualTransactionHash, setActualTransactionHash] = useState(null);\n\n const api = useRef(new SimplePaymentAPI(apiUrl, apiKey, apiSecret));\n\n const loadData = async () => {\n try {\n setLoading(true);\n setError('');\n\n console.log('🔄 Loading networks and tokens...');\n const [networksRes, tokensRes] = await Promise.all([\n api.current.getNetworks(),\n api.current.getTokens()\n ]);\n\n // Remove duplicate networks and filter out unsupported networks\n const uniqueNetworks = networksRes.networks?.reduce((acc, network) => {\n // Filter out Solana, Tron, and Algorand networks\n if (network.shortName === 'solana' || network.shortName === 'tron' || network.shortName === 'algorand') {\n return acc;\n }\n\n // Only include networks with valid chainId (EVM networks)\n if (!network.chainId || network.chainId === null) {\n return acc;\n }\n\n // Use chainId for deduplication (more reliable than UUID id)\n const key = `${network.chainId}-${network.shortName}`;\n if (!acc.some(n => `${n.chainId}-${n.shortName}` === key)) {\n acc.push(network);\n }\n return acc;\n }, []) || [];\n\n // Remove duplicate tokens and filter for only USDC and USDT\n const uniqueTokens = tokensRes.stablecoins?.reduce((acc, token) => {\n // Only allow USDC and USDT tokens\n if (token.symbol !== 'USDC' && token.symbol !== 'USDT') {\n return acc;\n }\n\n // Filter out tokens from unsupported networks\n if (token.Network?.shortName === 'solana' || token.Network?.shortName === 'tron' || token.Network?.shortName === 'algorand') {\n return acc;\n }\n\n // Use symbol + networkId for deduplication (not UUID id)\n const key = `${token.symbol}-${token.networkId}`;\n if (!acc.some(t => `${t.symbol}-${t.networkId}` === key)) {\n acc.push(token);\n }\n return acc;\n }, []) || [];\n\n setNetworks(uniqueNetworks);\n setTokens(uniqueTokens);\n\n console.log('✅ Loaded unique networks:', uniqueNetworks.length);\n console.log('📋 Networks:', uniqueNetworks.map(n => `${n.name} (${n.shortName}, chainId: ${n.chainId})`));\n console.log('✅ Loaded unique tokens:', uniqueTokens.length);\n console.log('📋 Tokens:', uniqueTokens.map(t => `${t.symbol} on ${t.Network?.name || 'Unknown'}`));\n\n } catch (err) {\n console.error('Failed to load data:', err);\n setError('Failed to load payment options. Using fallback data.');\n } finally {\n setLoading(false);\n }\n };\n\n const createPayment = async (config) => {\n try {\n setLoading(true);\n setError('');\n\n const paymentPayload = {\n amount: config.amount,\n currency: selectedToken.symbol,\n network: selectedNetwork.shortName,\n customerEmail: config.customerEmail,\n callbackUrl: config.callbackUrl,\n metadata: {\n ...config.metadata,\n merchantWalletAddresses: config.merchantWalletAddresses,\n paymentMethod,\n selectedNetwork: selectedNetwork.shortName,\n selectedToken: selectedToken.symbol,\n wagmiEnabled: true\n }\n };\n\n console.log('🔄 Creating payment:', paymentPayload);\n const payment = await api.current.createPayment(paymentPayload);\n setPaymentData(payment.payment);\n\n console.log('✅ Payment created:', payment.payment.id);\n setCurrentStep('confirm');\n\n } catch (err) {\n console.error('Payment creation failed:', err);\n setError(err.message);\n } finally {\n setLoading(false);\n }\n };\n\n const failPayment = async (reason = 'Payment cancelled by user') => {\n if (paymentData?.id) {\n try {\n console.log('🚫 Payment cancelled by user, notifying backend...', paymentData.id);\n await api.current.failPayment(paymentData.id, reason);\n console.log('✅ Backend notified of payment cancellation');\n } catch (error) {\n console.error('❌ Failed to notify backend of payment cancellation:', error);\n }\n }\n };\n\n const resetState = () => {\n setCurrentStep('method');\n setSelectedNetwork(null);\n setSelectedToken(null);\n setPaymentMethod(null);\n setPaymentData(null);\n setError('');\n setProcessing(false);\n setActualTransactionHash(null);\n setPaymentType('wallet');\n };\n\n const resetTransactionState = () => {\n setError('');\n setProcessing(false);\n setActualTransactionHash(null);\n setCurrentStep('confirm');\n };\n\n return {\n // State\n currentStep,\n networks,\n tokens,\n selectedNetwork,\n selectedToken,\n paymentMethod,\n paymentData,\n loading,\n error,\n processing,\n processingMessage,\n paymentType,\n actualTransactionHash,\n\n // Actions\n setCurrentStep,\n setSelectedNetwork,\n setSelectedToken,\n setPaymentMethod,\n setError,\n setProcessing,\n setProcessingMessage,\n setPaymentType,\n setActualTransactionHash,\n loadData,\n createPayment,\n failPayment,\n resetState,\n resetTransactionState,\n\n // API reference\n api: api.current\n };\n};","// Chain ID mappings for different networks\nexport const CHAIN_IDS = {\n ethereum: 1,\n bsc: 56,\n polygon: 137,\n arbitrum: 42161,\n optimism: 10,\n avalanche: 43114,\n celo: 42220,\n base: 8453\n};\n\n// Trust Wallet chain ID mapping (they use different IDs for some chains)\nexport const TRUST_CHAIN_IDS = {\n 1: 60, // Ethereum\n 56: 56, // BSC\n 137: 966, // Polygon\n 42161: 42161, // Arbitrum\n 10: 10, // Optimism\n 43114: 43114, // Avalanche\n 42220: 42220, // Celo\n 8453: 8453 // Base\n};\n\n// Network display names\nexport const NETWORK_NAMES = {\n ethereum: 'Ethereum',\n bsc: 'BSC',\n polygon: 'Polygon',\n arbitrum: 'Arbitrum',\n optimism: 'Optimism',\n avalanche: 'Avalanche',\n celo: 'Celo',\n base: 'Base'\n};\n\n/**\n * Normalize chainId to decimal number\n * Handles hex strings (\"0x1\", \"0xa86a\"), decimal strings (\"1\", \"43114\"), and numbers (1, 43114)\n * @param {string|number} chainId - Chain ID in any format\n * @returns {number} - Chain ID as decimal number\n */\nexport const normalizeChainId = (chainId) => {\n if (typeof chainId === 'number') {\n return chainId;\n }\n\n if (typeof chainId === 'string') {\n // Handle hex strings like \"0x1\" or \"0xa86a\"\n if (chainId.startsWith('0x')) {\n return parseInt(chainId, 16);\n }\n // Handle decimal strings like \"1\" or \"43114\"\n return parseInt(chainId, 10);\n }\n\n return 1; // Default to Ethereum mainnet\n};\n\n// Get numeric chain ID from network short name\nexport const getChainId = (networkShortName) => {\n return CHAIN_IDS[networkShortName] || 1;\n};\n\n// Get Trust Wallet chain ID mapping\nexport const getTrustChainId = (chainId) => {\n return TRUST_CHAIN_IDS[chainId] || 60;\n};\n\n// Get network display name\nexport const getNetworkDisplayName = (network) => {\n return NETWORK_NAMES[network] || network;\n};\n\n// Token contract addresses and decimals for different networks\nexport const TOKEN_CONTRACTS = {\n 'ethereum': {\n 'USDT': { contract: '0xdAC17F958D2ee523a2206206994597C13D831ec7', decimals: 6 },\n 'USDC': { contract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', decimals: 6 }\n },\n 'bsc': {\n 'USDT': { contract: '0x55d398326f99059fF775485246999027B3197955', decimals: 18 },\n 'USDC': { contract: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d', decimals: 18 }\n },\n 'polygon': {\n 'USDT': { contract: '0xc2132D05D31c914a87c6611C10748AEb04B58e8F', decimals: 6 },\n 'USDC': { contract: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', decimals: 6 }\n },\n 'arbitrum': {\n 'USDT': { contract: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9', decimals: 6 },\n 'USDC': { contract: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831', decimals: 6 }\n },\n 'optimism': {\n 'USDT': { contract: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58', decimals: 6 },\n 'USDC': { contract: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85', decimals: 6 }\n },\n 'avalanche': {\n 'USDT': { contract: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7', decimals: 6 },\n 'USDC': { contract: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E', decimals: 6 }\n },\n 'celo': {\n 'USDT': { contract: '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e', decimals: 6 },\n 'USDC': { contract: '0xcebA9300f2b948710d2653dD7B07f33A8B32118C', decimals: 6 }\n },\n 'base': {\n 'USDT': { contract: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2', decimals: 6 },\n 'USDC': { contract: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', decimals: 6 }\n }\n};\n\n// Get token info for a specific network and token symbol\nexport const getTokenInfo = (networkName, tokenSymbol) => {\n return TOKEN_CONTRACTS[networkName?.toLowerCase()]?.[tokenSymbol];\n};","import { useState, useEffect } from 'react';\nimport { useConnect, useAccount, useSwitchChain } from 'wagmi';\nimport { getAccount } from '@wagmi/core';\nimport { wagmiConfig } from '../config/wagmiConfig';\nimport { getChainId } from '../config/chainConfig';\n\nexport const useWalletConnection = () => {\n const [selectedWalletType, setSelectedWalletType] = useState(null);\n const [connectedWallet, setConnectedWallet] = useState(null);\n const [connectionError, setConnectionError] = useState('');\n\n const { connect, connectors } = useConnect();\n const { isConnected, address, chain } = useAccount();\n const { switchChain } = useSwitchChain();\n\n // Update connected wallet state when account changes\n useEffect(() => {\n if (isConnected && address) {\n setConnectedWallet({\n account: address,\n chainId: chain?.id,\n walletType: selectedWalletType\n });\n } else {\n setConnectedWallet(null);\n }\n }, [isConnected, address, chain, selectedWalletType]);\n\n const handleWalletSelection = (walletType) => {\n setSelectedWalletType(walletType);\n setConnectionError('');\n console.log(`📱 Selected wallet type: ${walletType}`);\n };\n\n const connectWallet = async (connector, selectedNetwork = null) => {\n if (!connector) {\n setConnectionError('Please select a wallet first');\n return false;\n }\n\n try {\n setConnectionError('');\n console.log(`🔗 Connecting to ${connector.name} wallet...`);\n\n // Use Wagmi's connect function directly\n await connect({ connector });\n console.log(`✅ ${connector.name} wallet connected successfully`);\n\n if (selectedNetwork) {\n // Check if we need to switch networks after connection\n const requiredChainId = getChainId(selectedNetwork.shortName);\n\n // Wait for wallet to initialize before switching networks\n // Some wallets (Zerion, Trust, Rabby) need more time on cold start\n const walletName = connector.name?.toLowerCase() || '';\n const needsLongerDelay = walletName.includes('zerion') ||\n walletName.includes('trust') ||\n walletName.includes('rabby');\n\n const delayMs = needsLongerDelay ? 5000 : 500; // 5s for slow wallets, 500ms for others\n console.log(`⏳ Waiting ${delayMs}ms for ${connector.name} to initialize...`);\n await new Promise(resolve => setTimeout(resolve, delayMs));\n\n // Get current chain info\n const currentAccount = getAccount(wagmiConfig);\n const currentChainId = currentAccount.chainId;\n\n console.log(`🔍 Network check: Current chain ${currentChainId}, Required chain ${requiredChainId} (${selectedNetwork.name})`);\n\n if (requiredChainId && currentChainId !== requiredChainId) {\n console.log(`🔄 Switching from chain ${currentChainId} to ${requiredChainId} (${selectedNetwork.name})`);\n try {\n await switchChain({ chainId: requiredChainId });\n console.log(`✅ Successfully switched to ${selectedNetwork.name}`);\n\n // Wait a moment for the wallet to update its state after network switch\n await new Promise(resolve => setTimeout(resolve, 1000));\n\n } catch (switchError) {\n console.error('❌ Network switch failed:', switchError);\n\n // Provide user-friendly error messages\n if (switchError.code === 4001 || switchError.message?.includes('User rejected')) {\n setConnectionError('Network switch was cancelled by user');\n } else if (switchError.message?.includes('Unrecognized chain ID')) {\n setConnectionError(`${selectedNetwork.name} network is not added to your wallet. Please add it manually.`);\n } else {\n setConnectionError(`Failed to switch to ${selectedNetwork.name}. Please switch manually in your wallet.`);\n }\n return false;\n }\n }\n }\n\n return true;\n\n } catch (err) {\n console.error(`${connector.name} wallet connection failed:`, err);\n\n // Provide user-friendly error messages\n if (err.code === 4001 || err.message.includes('User rejected') || err.message.includes('rejected')) {\n setConnectionError('User cancelled the connection request');\n } else {\n setConnectionError(`Failed to connect to ${connector.name}. Please try again.`);\n }\n return false;\n }\n };\n\n const disconnectWallet = () => {\n setConnectedWallet(null);\n setSelectedWalletType(null);\n setConnectionError('');\n };\n\n const clearError = () => {\n setConnectionError('');\n };\n\n const ensureCorrectNetwork = async (requiredNetwork) => {\n if (!requiredNetwork) {\n console.warn('⚠️ No network specified for verification');\n return true;\n }\n\n try {\n const requiredChainId = getChainId(requiredNetwork.shortName);\n const currentAccount = getAccount(wagmiConfig);\n const currentChainId = currentAccount.chainId;\n\n console.log(`🔍 Network verification: Current=${currentChainId}, Required=${requiredChainId} (${requiredNetwork.name})`);\n\n if (requiredChainId && currentChainId !== requiredChainId) {\n console.log(`🔄 Wrong network detected! Switching from chain ${currentChainId} to ${requiredChainId}...`);\n\n try {\n await switchChain({ chainId: requiredChainId });\n console.log(`✅ Successfully switched to ${requiredNetwork.name}`);\n\n // Wait a moment for the switch to complete\n await new Promise(resolve => setTimeout(resolve, 1000));\n return true;\n\n } catch (switchError) {\n console.error('❌ Network switch failed:', switchError);\n\n if (switchError.code === 4001 || switchError.message?.includes('User rejected')) {\n setConnectionError('Network switch was cancelled. Please switch to the correct network in your wallet.');\n } else if (switchError.message?.includes('Unrecognized chain ID')) {\n setConnectionError(`${requiredNetwork.name} network is not added to your wallet. Please add it manually.`);\n } else {\n setConnectionError(`Failed to switch to ${requiredNetwork.name}. Please switch manually in your wallet.`);\n }\n return false;\n }\n }\n\n console.log(`✅ Already on correct network: ${requiredNetwork.name}`);\n return true;\n\n } catch (error) {\n console.error('❌ Network verification failed:', error);\n setConnectionError('Failed to verify network. Please check your wallet connection.');\n return false;\n }\n };\n\n return {\n // State\n selectedWalletType,\n connectedWallet,\n connectionError,\n isConnected,\n address,\n chain,\n connectors,\n\n // Actions\n handleWalletSelection,\n connectWallet,\n disconnectWallet,\n switchChain,\n ensureCorrectNetwork,\n clearError,\n setSelectedWalletType,\n\n // Wagmi hooks\n connect\n };\n};","export function defineChain(chain) {\n return {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n };\n}\n//# sourceMappingURL=defineChain.js.map","export const version = '2.39.0';\n//# sourceMappingURL=version.js.map","import { version } from './version.js';\nlet errorConfig = {\n getDocsUrl: ({ docsBaseUrl, docsPath = '', docsSlug, }) => docsPath\n ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${docsSlug ? `#${docsSlug}` : ''}`\n : undefined,\n version: `viem@${version}`,\n};\nexport function setErrorConfig(config) {\n errorConfig = config;\n}\nexport class BaseError extends Error {\n constructor(shortMessage, args = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.details;\n if (args.cause?.message)\n return args.cause.message;\n return args.details;\n })();\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath;\n return args.docsPath;\n })();\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });\n const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),\n ].join('\\n');\n super(message, args.cause ? { cause: args.cause } : undefined);\n Object.defineProperty(this, \"details\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"docsPath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"metaMessages\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"shortMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'BaseError'\n });\n this.details = details;\n this.docsPath = docsPath;\n this.metaMessages = args.metaMessages;\n this.name = args.name ?? this.name;\n this.shortMessage = shortMessage;\n this.version = version;\n }\n walk(fn) {\n return walk(this, fn);\n }\n}\nfunction walk(err, fn) {\n if (fn?.(err))\n return err;\n if (err &&\n typeof err === 'object' &&\n 'cause' in err &&\n err.cause !== undefined)\n return walk(err.cause, fn);\n return fn ? null : err;\n}\n//# sourceMappingURL=base.js.map","import { BaseError } from './base.js';\nexport class IntegerOutOfRangeError extends BaseError {\n constructor({ max, min, signed, size, value, }) {\n super(`Number \"${value}\" is not in safe ${size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: 'IntegerOutOfRangeError' });\n }\n}\nexport class InvalidBytesBooleanError extends BaseError {\n constructor(bytes) {\n super(`Bytes value \"${bytes}\" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, {\n name: 'InvalidBytesBooleanError',\n });\n }\n}\nexport class InvalidHexBooleanError extends BaseError {\n constructor(hex) {\n super(`Hex value \"${hex}\" is not a valid boolean. The hex value must be \"0x0\" (false) or \"0x1\" (true).`, { name: 'InvalidHexBooleanError' });\n }\n}\nexport class InvalidHexValueError extends BaseError {\n constructor(value) {\n super(`Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`, { name: 'InvalidHexValueError' });\n }\n}\nexport class SizeOverflowError extends BaseError {\n constructor({ givenSize, maxSize }) {\n super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: 'SizeOverflowError' });\n }\n}\n//# sourceMappingURL=encoding.js.map","export function isHex(value, { strict = true } = {}) {\n if (!value)\n return false;\n if (typeof value !== 'string')\n return false;\n return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x');\n}\n//# sourceMappingURL=isHex.js.map","import { isHex } from './isHex.js';\n/**\n * @description Retrieves the size of the value (in bytes).\n *\n * @param value The value (hex or byte array) to retrieve the size of.\n * @returns The size of the value (in bytes).\n */\nexport function size(value) {\n if (isHex(value, { strict: false }))\n return Math.ceil((value.length - 2) / 2);\n return value.length;\n}\n//# sourceMappingURL=size.js.map","export function trim(hexOrBytes, { dir = 'left' } = {}) {\n let data = typeof hexOrBytes === 'string' ? hexOrBytes.replace('0x', '') : hexOrBytes;\n let sliceLength = 0;\n for (let i = 0; i < data.length - 1; i++) {\n if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')\n sliceLength++;\n else\n break;\n }\n data =\n dir === 'left'\n ? data.slice(sliceLength)\n : data.slice(0, data.length - sliceLength);\n if (typeof hexOrBytes === 'string') {\n if (data.length === 1 && dir === 'right')\n data = `${data}0`;\n return `0x${data.length % 2 === 1 ? `0${data}` : data}`;\n }\n return data;\n}\n//# sourceMappingURL=trim.js.map","import { BaseError } from './base.js';\nexport class SliceOffsetOutOfBoundsError extends BaseError {\n constructor({ offset, position, size, }) {\n super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset \"${offset}\" is out-of-bounds (size: ${size}).`, { name: 'SliceOffsetOutOfBoundsError' });\n }\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`, { name: 'SizeExceedsPaddingSizeError' });\n }\n}\nexport class InvalidBytesLengthError extends BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size} ${type} long.`, { name: 'InvalidBytesLengthError' });\n }\n}\n//# sourceMappingURL=data.js.map","import { SizeExceedsPaddingSizeError, } from '../../errors/data.js';\nexport function pad(hexOrBytes, { dir, size = 32 } = {}) {\n if (typeof hexOrBytes === 'string')\n return padHex(hexOrBytes, { dir, size });\n return padBytes(hexOrBytes, { dir, size });\n}\nexport function padHex(hex_, { dir, size = 32 } = {}) {\n if (size === null)\n return hex_;\n const hex = hex_.replace('0x', '');\n if (hex.length > size * 2)\n throw new SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'hex',\n });\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`;\n}\nexport function padBytes(bytes, { dir, size = 32 } = {}) {\n if (size === null)\n return bytes;\n if (bytes.length > size)\n throw new SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'bytes',\n });\n const paddedBytes = new Uint8Array(size);\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right';\n paddedBytes[padEnd ? i : size - i - 1] =\n bytes[padEnd ? i : bytes.length - i - 1];\n }\n return paddedBytes;\n}\n//# sourceMappingURL=pad.js.map","import { IntegerOutOfRangeError, } from '../../errors/encoding.js';\nimport { pad } from '../data/pad.js';\nimport { assertSize } from './fromHex.js';\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));\n/**\n * Encodes a string, number, bigint, or ByteArray into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex\n * - Example: https://viem.sh/docs/utilities/toHex#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world')\n * // '0x48656c6c6f20776f726c6421'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex(420)\n * // '0x1a4'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world', { size: 32 })\n * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'\n */\nexport function toHex(value, opts = {}) {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToHex(value, opts);\n if (typeof value === 'string') {\n return stringToHex(value, opts);\n }\n if (typeof value === 'boolean')\n return boolToHex(value, opts);\n return bytesToHex(value, opts);\n}\n/**\n * Encodes a boolean into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#booltohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true)\n * // '0x1'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(false)\n * // '0x0'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true, { size: 32 })\n * // '0x0000000000000000000000000000000000000000000000000000000000000001'\n */\nexport function boolToHex(value, opts = {}) {\n const hex = `0x${Number(value)}`;\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size });\n return pad(hex, { size: opts.size });\n }\n return hex;\n}\n/**\n * Encodes a bytes array into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#bytestohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function bytesToHex(value, opts = {}) {\n let string = '';\n for (let i = 0; i < value.length; i++) {\n string += hexes[value[i]];\n }\n const hex = `0x${string}`;\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size });\n return pad(hex, { dir: 'right', size: opts.size });\n }\n return hex;\n}\n/**\n * Encodes a number or bigint into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#numbertohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420)\n * // '0x1a4'\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420, { size: 32 })\n * // '0x00000000000000000000000000000000000000000000000000000000000001a4'\n */\nexport function numberToHex(value_, opts = {}) {\n const { signed, size } = opts;\n const value = BigInt(value_);\n let maxValue;\n if (size) {\n if (signed)\n maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n;\n else\n maxValue = 2n ** (BigInt(size) * 8n) - 1n;\n }\n else if (typeof value_ === 'number') {\n maxValue = BigInt(Number.MAX_SAFE_INTEGER);\n }\n const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0;\n if ((maxValue && value > maxValue) || value < minValue) {\n const suffix = typeof value_ === 'bigint' ? 'n' : '';\n throw new IntegerOutOfRangeError({\n max: maxValue ? `${maxValue}${suffix}` : undefined,\n min: `${minValue}${suffix}`,\n signed,\n size,\n value: `${value_}${suffix}`,\n });\n }\n const hex = `0x${(signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : value).toString(16)}`;\n if (size)\n return pad(hex, { size });\n return hex;\n}\nconst encoder = /*#__PURE__*/ new TextEncoder();\n/**\n * Encodes a UTF-8 string into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#stringtohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function stringToHex(value_, opts = {}) {\n const value = encoder.encode(value_);\n return bytesToHex(value, opts);\n}\n//# sourceMappingURL=toHex.js.map","import { BaseError } from '../../errors/base.js';\nimport { isHex } from '../data/isHex.js';\nimport { pad } from '../data/pad.js';\nimport { assertSize } from './fromHex.js';\nimport { numberToHex, } from './toHex.js';\nconst encoder = /*#__PURE__*/ new TextEncoder();\n/**\n * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes\n * - Example: https://viem.sh/docs/utilities/toBytes#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes('Hello world')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function toBytes(value, opts = {}) {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToBytes(value, opts);\n if (typeof value === 'boolean')\n return boolToBytes(value, opts);\n if (isHex(value))\n return hexToBytes(value, opts);\n return stringToBytes(value, opts);\n}\n/**\n * Encodes a boolean into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes\n *\n * @param value Boolean value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true)\n * // Uint8Array([1])\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true, { size: 32 })\n * // Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n */\nexport function boolToBytes(value, opts = {}) {\n const bytes = new Uint8Array(1);\n bytes[0] = Number(value);\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size });\n return pad(bytes, { size: opts.size });\n }\n return bytes;\n}\n// We use very optimized technique to convert hex string to byte array\nconst charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n};\nfunction charCodeToBase16(char) {\n if (char >= charCodeMap.zero && char <= charCodeMap.nine)\n return char - charCodeMap.zero;\n if (char >= charCodeMap.A && char <= charCodeMap.F)\n return char - (charCodeMap.A - 10);\n if (char >= charCodeMap.a && char <= charCodeMap.f)\n return char - (charCodeMap.a - 10);\n return undefined;\n}\n/**\n * Encodes a hex string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes\n *\n * @param hex Hex string to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function hexToBytes(hex_, opts = {}) {\n let hex = hex_;\n if (opts.size) {\n assertSize(hex, { size: opts.size });\n hex = pad(hex, { dir: 'right', size: opts.size });\n }\n let hexString = hex.slice(2);\n if (hexString.length % 2)\n hexString = `0${hexString}`;\n const length = hexString.length / 2;\n const bytes = new Uint8Array(length);\n for (let index = 0, j = 0; index < length; index++) {\n const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));\n const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new BaseError(`Invalid byte sequence (\"${hexString[j - 2]}${hexString[j - 1]}\" in \"${hexString}\").`);\n }\n bytes[index] = nibbleLeft * 16 + nibbleRight;\n }\n return bytes;\n}\n/**\n * Encodes a number into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes\n *\n * @param value Number to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function numberToBytes(value, opts) {\n const hex = numberToHex(value, opts);\n return hexToBytes(hex);\n}\n/**\n * Encodes a UTF-8 string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes\n *\n * @param value String to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function stringToBytes(value, opts = {}) {\n const bytes = encoder.encode(value);\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size });\n return pad(bytes, { dir: 'right', size: opts.size });\n }\n return bytes;\n}\n//# sourceMappingURL=toBytes.js.map","import { InvalidHexBooleanError, SizeOverflowError, } from '../../errors/encoding.js';\nimport { size as size_ } from '../data/size.js';\nimport { trim } from '../data/trim.js';\nimport { hexToBytes } from './toBytes.js';\nexport function assertSize(hexOrBytes, { size }) {\n if (size_(hexOrBytes) > size)\n throw new SizeOverflowError({\n givenSize: size_(hexOrBytes),\n maxSize: size,\n });\n}\n/**\n * Decodes a hex string into a string, number, bigint, boolean, or byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex\n * - Example: https://viem.sh/docs/utilities/fromHex#usage\n *\n * @param hex Hex string to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x1a4', 'number')\n * // 420\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c6421', 'string')\n * // 'Hello world'\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * to: 'string'\n * })\n * // 'Hello world'\n */\nexport function fromHex(hex, toOrOpts) {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts;\n const to = opts.to;\n if (to === 'number')\n return hexToNumber(hex, opts);\n if (to === 'bigint')\n return hexToBigInt(hex, opts);\n if (to === 'string')\n return hexToString(hex, opts);\n if (to === 'boolean')\n return hexToBool(hex, opts);\n return hexToBytes(hex, opts);\n}\n/**\n * Decodes a hex value into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobigint\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x1a4', { signed: true })\n * // 420n\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420n\n */\nexport function hexToBigInt(hex, opts = {}) {\n const { signed } = opts;\n if (opts.size)\n assertSize(hex, { size: opts.size });\n const value = BigInt(hex);\n if (!signed)\n return value;\n const size = (hex.length - 2) / 2;\n const max = (1n << (BigInt(size) * 8n - 1n)) - 1n;\n if (value <= max)\n return value;\n return value - BigInt(`0x${'f'.padStart(size * 2, 'f')}`) - 1n;\n}\n/**\n * Decodes a hex value into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobool\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x01')\n * // true\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // true\n */\nexport function hexToBool(hex_, opts = {}) {\n let hex = hex_;\n if (opts.size) {\n assertSize(hex, { size: opts.size });\n hex = trim(hex);\n }\n if (trim(hex) === '0x00')\n return false;\n if (trim(hex) === '0x01')\n return true;\n throw new InvalidHexBooleanError(hex);\n}\n/**\n * Decodes a hex string into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextonumber\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToNumber('0x1a4')\n * // 420\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420\n */\nexport function hexToNumber(hex, opts = {}) {\n return Number(hexToBigInt(hex, opts));\n}\n/**\n * Decodes a hex value into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextostring\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c6421')\n * // 'Hello world!'\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // 'Hello world'\n */\nexport function hexToString(hex, opts = {}) {\n let bytes = hexToBytes(hex);\n if (opts.size) {\n assertSize(bytes, { size: opts.size });\n bytes = trim(bytes, { dir: 'right' });\n }\n return new TextDecoder().decode(bytes);\n}\n//# sourceMappingURL=fromHex.js.map","export function defineFormatter(type, format) {\n return ({ exclude, format: overrides, }) => {\n return {\n exclude,\n format: (args, action) => {\n const formatted = format(args, action);\n if (exclude) {\n for (const key of exclude) {\n delete formatted[key];\n }\n }\n return {\n ...formatted,\n ...overrides(args, action),\n };\n },\n type,\n };\n };\n}\n//# sourceMappingURL=formatter.js.map","import { hexToNumber } from '../encoding/fromHex.js';\nimport { defineFormatter } from './formatter.js';\nexport const transactionType = {\n '0x0': 'legacy',\n '0x1': 'eip2930',\n '0x2': 'eip1559',\n '0x3': 'eip4844',\n '0x4': 'eip7702',\n};\nexport function formatTransaction(transaction, _) {\n const transaction_ = {\n ...transaction,\n blockHash: transaction.blockHash ? transaction.blockHash : null,\n blockNumber: transaction.blockNumber\n ? BigInt(transaction.blockNumber)\n : null,\n chainId: transaction.chainId ? hexToNumber(transaction.chainId) : undefined,\n gas: transaction.gas ? BigInt(transaction.gas) : undefined,\n gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : undefined,\n maxFeePerBlobGas: transaction.maxFeePerBlobGas\n ? BigInt(transaction.maxFeePerBlobGas)\n : undefined,\n maxFeePerGas: transaction.maxFeePerGas\n ? BigInt(transaction.maxFeePerGas)\n : undefined,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas\n ? BigInt(transaction.maxPriorityFeePerGas)\n : undefined,\n nonce: transaction.nonce ? hexToNumber(transaction.nonce) : undefined,\n to: transaction.to ? transaction.to : null,\n transactionIndex: transaction.transactionIndex\n ? Number(transaction.transactionIndex)\n : null,\n type: transaction.type\n ? transactionType[transaction.type]\n : undefined,\n typeHex: transaction.type ? transaction.type : undefined,\n value: transaction.value ? BigInt(transaction.value) : undefined,\n v: transaction.v ? BigInt(transaction.v) : undefined,\n };\n if (transaction.authorizationList)\n transaction_.authorizationList = formatAuthorizationList(transaction.authorizationList);\n transaction_.yParity = (() => {\n // If `yParity` is provided, we will use it.\n if (transaction.yParity)\n return Number(transaction.yParity);\n // If no `yParity` provided, try derive from `v`.\n if (typeof transaction_.v === 'bigint') {\n if (transaction_.v === 0n || transaction_.v === 27n)\n return 0;\n if (transaction_.v === 1n || transaction_.v === 28n)\n return 1;\n if (transaction_.v >= 35n)\n return transaction_.v % 2n === 0n ? 1 : 0;\n }\n return undefined;\n })();\n if (transaction_.type === 'legacy') {\n delete transaction_.accessList;\n delete transaction_.maxFeePerBlobGas;\n delete transaction_.maxFeePerGas;\n delete transaction_.maxPriorityFeePerGas;\n delete transaction_.yParity;\n }\n if (transaction_.type === 'eip2930') {\n delete transaction_.maxFeePerBlobGas;\n delete transaction_.maxFeePerGas;\n delete transaction_.maxPriorityFeePerGas;\n }\n if (transaction_.type === 'eip1559') {\n delete transaction_.maxFeePerBlobGas;\n }\n return transaction_;\n}\nexport const defineTransaction = /*#__PURE__*/ defineFormatter('transaction', formatTransaction);\n//////////////////////////////////////////////////////////////////////////////\nfunction formatAuthorizationList(authorizationList) {\n return authorizationList.map((authorization) => ({\n address: authorization.address,\n chainId: Number(authorization.chainId),\n nonce: Number(authorization.nonce),\n r: authorization.r,\n s: authorization.s,\n yParity: Number(authorization.yParity),\n }));\n}\n//# sourceMappingURL=transaction.js.map","import { defineFormatter } from './formatter.js';\nimport { formatTransaction } from './transaction.js';\nexport function formatBlock(block, _) {\n const transactions = (block.transactions ?? []).map((transaction) => {\n if (typeof transaction === 'string')\n return transaction;\n return formatTransaction(transaction);\n });\n return {\n ...block,\n baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,\n blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined,\n difficulty: block.difficulty ? BigInt(block.difficulty) : undefined,\n excessBlobGas: block.excessBlobGas\n ? BigInt(block.excessBlobGas)\n : undefined,\n gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined,\n gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined,\n hash: block.hash ? block.hash : null,\n logsBloom: block.logsBloom ? block.logsBloom : null,\n nonce: block.nonce ? block.nonce : null,\n number: block.number ? BigInt(block.number) : null,\n size: block.size ? BigInt(block.size) : undefined,\n timestamp: block.timestamp ? BigInt(block.timestamp) : undefined,\n transactions,\n totalDifficulty: block.totalDifficulty\n ? BigInt(block.totalDifficulty)\n : null,\n };\n}\nexport const defineBlock = /*#__PURE__*/ defineFormatter('block', formatBlock);\n//# sourceMappingURL=block.js.map","export function formatLog(log, { args, eventName, } = {}) {\n return {\n ...log,\n blockHash: log.blockHash ? log.blockHash : null,\n blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,\n logIndex: log.logIndex ? Number(log.logIndex) : null,\n transactionHash: log.transactionHash ? log.transactionHash : null,\n transactionIndex: log.transactionIndex\n ? Number(log.transactionIndex)\n : null,\n ...(eventName ? { args, eventName } : {}),\n };\n}\n//# sourceMappingURL=log.js.map","import { hexToNumber } from '../encoding/fromHex.js';\nimport { defineFormatter } from './formatter.js';\nimport { formatLog } from './log.js';\nimport { transactionType } from './transaction.js';\nexport const receiptStatuses = {\n '0x0': 'reverted',\n '0x1': 'success',\n};\nexport function formatTransactionReceipt(transactionReceipt, _) {\n const receipt = {\n ...transactionReceipt,\n blockNumber: transactionReceipt.blockNumber\n ? BigInt(transactionReceipt.blockNumber)\n : null,\n contractAddress: transactionReceipt.contractAddress\n ? transactionReceipt.contractAddress\n : null,\n cumulativeGasUsed: transactionReceipt.cumulativeGasUsed\n ? BigInt(transactionReceipt.cumulativeGasUsed)\n : null,\n effectiveGasPrice: transactionReceipt.effectiveGasPrice\n ? BigInt(transactionReceipt.effectiveGasPrice)\n : null,\n gasUsed: transactionReceipt.gasUsed\n ? BigInt(transactionReceipt.gasUsed)\n : null,\n logs: transactionReceipt.logs\n ? transactionReceipt.logs.map((log) => formatLog(log))\n : null,\n to: transactionReceipt.to ? transactionReceipt.to : null,\n transactionIndex: transactionReceipt.transactionIndex\n ? hexToNumber(transactionReceipt.transactionIndex)\n : null,\n status: transactionReceipt.status\n ? receiptStatuses[transactionReceipt.status]\n : null,\n type: transactionReceipt.type\n ? transactionType[transactionReceipt.type] || transactionReceipt.type\n : null,\n };\n if (transactionReceipt.blobGasPrice)\n receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice);\n if (transactionReceipt.blobGasUsed)\n receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed);\n return receipt;\n}\nexport const defineTransactionReceipt = /*#__PURE__*/ defineFormatter('transactionReceipt', formatTransactionReceipt);\n//# sourceMappingURL=transactionReceipt.js.map","import { bytesToHex, numberToHex } from '../encoding/toHex.js';\nimport { defineFormatter } from './formatter.js';\nexport const rpcTransactionType = {\n legacy: '0x0',\n eip2930: '0x1',\n eip1559: '0x2',\n eip4844: '0x3',\n eip7702: '0x4',\n};\nexport function formatTransactionRequest(request, _) {\n const rpcRequest = {};\n if (typeof request.authorizationList !== 'undefined')\n rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList);\n if (typeof request.accessList !== 'undefined')\n rpcRequest.accessList = request.accessList;\n if (typeof request.blobVersionedHashes !== 'undefined')\n rpcRequest.blobVersionedHashes = request.blobVersionedHashes;\n if (typeof request.blobs !== 'undefined') {\n if (typeof request.blobs[0] !== 'string')\n rpcRequest.blobs = request.blobs.map((x) => bytesToHex(x));\n else\n rpcRequest.blobs = request.blobs;\n }\n if (typeof request.data !== 'undefined')\n rpcRequest.data = request.data;\n if (request.account)\n rpcRequest.from = request.account.address;\n if (typeof request.from !== 'undefined')\n rpcRequest.from = request.from;\n if (typeof request.gas !== 'undefined')\n rpcRequest.gas = numberToHex(request.gas);\n if (typeof request.gasPrice !== 'undefined')\n rpcRequest.gasPrice = numberToHex(request.gasPrice);\n if (typeof request.maxFeePerBlobGas !== 'undefined')\n rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas);\n if (typeof request.maxFeePerGas !== 'undefined')\n rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas);\n if (typeof request.maxPriorityFeePerGas !== 'undefined')\n rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas);\n if (typeof request.nonce !== 'undefined')\n rpcRequest.nonce = numberToHex(request.nonce);\n if (typeof request.to !== 'undefined')\n rpcRequest.to = request.to;\n if (typeof request.type !== 'undefined')\n rpcRequest.type = rpcTransactionType[request.type];\n if (typeof request.value !== 'undefined')\n rpcRequest.value = numberToHex(request.value);\n return rpcRequest;\n}\nexport const defineTransactionRequest = /*#__PURE__*/ defineFormatter('transactionRequest', formatTransactionRequest);\n//////////////////////////////////////////////////////////////////////////////\nfunction formatAuthorizationList(authorizationList) {\n return authorizationList.map((authorization) => ({\n address: authorization.address,\n r: authorization.r\n ? numberToHex(BigInt(authorization.r))\n : authorization.r,\n s: authorization.s\n ? numberToHex(BigInt(authorization.s))\n : authorization.s,\n chainId: numberToHex(authorization.chainId),\n nonce: numberToHex(authorization.nonce),\n ...(typeof authorization.yParity !== 'undefined'\n ? { yParity: numberToHex(authorization.yParity) }\n : {}),\n ...(typeof authorization.v !== 'undefined' &&\n typeof authorization.yParity === 'undefined'\n ? { v: numberToHex(authorization.v) }\n : {}),\n }));\n}\n//# sourceMappingURL=transactionRequest.js.map","export const maxInt8 = 2n ** (8n - 1n) - 1n;\nexport const maxInt16 = 2n ** (16n - 1n) - 1n;\nexport const maxInt24 = 2n ** (24n - 1n) - 1n;\nexport const maxInt32 = 2n ** (32n - 1n) - 1n;\nexport const maxInt40 = 2n ** (40n - 1n) - 1n;\nexport const maxInt48 = 2n ** (48n - 1n) - 1n;\nexport const maxInt56 = 2n ** (56n - 1n) - 1n;\nexport const maxInt64 = 2n ** (64n - 1n) - 1n;\nexport const maxInt72 = 2n ** (72n - 1n) - 1n;\nexport const maxInt80 = 2n ** (80n - 1n) - 1n;\nexport const maxInt88 = 2n ** (88n - 1n) - 1n;\nexport const maxInt96 = 2n ** (96n - 1n) - 1n;\nexport const maxInt104 = 2n ** (104n - 1n) - 1n;\nexport const maxInt112 = 2n ** (112n - 1n) - 1n;\nexport const maxInt120 = 2n ** (120n - 1n) - 1n;\nexport const maxInt128 = 2n ** (128n - 1n) - 1n;\nexport const maxInt136 = 2n ** (136n - 1n) - 1n;\nexport const maxInt144 = 2n ** (144n - 1n) - 1n;\nexport const maxInt152 = 2n ** (152n - 1n) - 1n;\nexport const maxInt160 = 2n ** (160n - 1n) - 1n;\nexport const maxInt168 = 2n ** (168n - 1n) - 1n;\nexport const maxInt176 = 2n ** (176n - 1n) - 1n;\nexport const maxInt184 = 2n ** (184n - 1n) - 1n;\nexport const maxInt192 = 2n ** (192n - 1n) - 1n;\nexport const maxInt200 = 2n ** (200n - 1n) - 1n;\nexport const maxInt208 = 2n ** (208n - 1n) - 1n;\nexport const maxInt216 = 2n ** (216n - 1n) - 1n;\nexport const maxInt224 = 2n ** (224n - 1n) - 1n;\nexport const maxInt232 = 2n ** (232n - 1n) - 1n;\nexport const maxInt240 = 2n ** (240n - 1n) - 1n;\nexport const maxInt248 = 2n ** (248n - 1n) - 1n;\nexport const maxInt256 = 2n ** (256n - 1n) - 1n;\nexport const minInt8 = -(2n ** (8n - 1n));\nexport const minInt16 = -(2n ** (16n - 1n));\nexport const minInt24 = -(2n ** (24n - 1n));\nexport const minInt32 = -(2n ** (32n - 1n));\nexport const minInt40 = -(2n ** (40n - 1n));\nexport const minInt48 = -(2n ** (48n - 1n));\nexport const minInt56 = -(2n ** (56n - 1n));\nexport const minInt64 = -(2n ** (64n - 1n));\nexport const minInt72 = -(2n ** (72n - 1n));\nexport const minInt80 = -(2n ** (80n - 1n));\nexport const minInt88 = -(2n ** (88n - 1n));\nexport const minInt96 = -(2n ** (96n - 1n));\nexport const minInt104 = -(2n ** (104n - 1n));\nexport const minInt112 = -(2n ** (112n - 1n));\nexport const minInt120 = -(2n ** (120n - 1n));\nexport const minInt128 = -(2n ** (128n - 1n));\nexport const minInt136 = -(2n ** (136n - 1n));\nexport const minInt144 = -(2n ** (144n - 1n));\nexport const minInt152 = -(2n ** (152n - 1n));\nexport const minInt160 = -(2n ** (160n - 1n));\nexport const minInt168 = -(2n ** (168n - 1n));\nexport const minInt176 = -(2n ** (176n - 1n));\nexport const minInt184 = -(2n ** (184n - 1n));\nexport const minInt192 = -(2n ** (192n - 1n));\nexport const minInt200 = -(2n ** (200n - 1n));\nexport const minInt208 = -(2n ** (208n - 1n));\nexport const minInt216 = -(2n ** (216n - 1n));\nexport const minInt224 = -(2n ** (224n - 1n));\nexport const minInt232 = -(2n ** (232n - 1n));\nexport const minInt240 = -(2n ** (240n - 1n));\nexport const minInt248 = -(2n ** (248n - 1n));\nexport const minInt256 = -(2n ** (256n - 1n));\nexport const maxUint8 = 2n ** 8n - 1n;\nexport const maxUint16 = 2n ** 16n - 1n;\nexport const maxUint24 = 2n ** 24n - 1n;\nexport const maxUint32 = 2n ** 32n - 1n;\nexport const maxUint40 = 2n ** 40n - 1n;\nexport const maxUint48 = 2n ** 48n - 1n;\nexport const maxUint56 = 2n ** 56n - 1n;\nexport const maxUint64 = 2n ** 64n - 1n;\nexport const maxUint72 = 2n ** 72n - 1n;\nexport const maxUint80 = 2n ** 80n - 1n;\nexport const maxUint88 = 2n ** 88n - 1n;\nexport const maxUint96 = 2n ** 96n - 1n;\nexport const maxUint104 = 2n ** 104n - 1n;\nexport const maxUint112 = 2n ** 112n - 1n;\nexport const maxUint120 = 2n ** 120n - 1n;\nexport const maxUint128 = 2n ** 128n - 1n;\nexport const maxUint136 = 2n ** 136n - 1n;\nexport const maxUint144 = 2n ** 144n - 1n;\nexport const maxUint152 = 2n ** 152n - 1n;\nexport const maxUint160 = 2n ** 160n - 1n;\nexport const maxUint168 = 2n ** 168n - 1n;\nexport const maxUint176 = 2n ** 176n - 1n;\nexport const maxUint184 = 2n ** 184n - 1n;\nexport const maxUint192 = 2n ** 192n - 1n;\nexport const maxUint200 = 2n ** 200n - 1n;\nexport const maxUint208 = 2n ** 208n - 1n;\nexport const maxUint216 = 2n ** 216n - 1n;\nexport const maxUint224 = 2n ** 224n - 1n;\nexport const maxUint232 = 2n ** 232n - 1n;\nexport const maxUint240 = 2n ** 240n - 1n;\nexport const maxUint248 = 2n ** 248n - 1n;\nexport const maxUint256 = 2n ** 256n - 1n;\n//# sourceMappingURL=number.js.map","export function concat(values) {\n if (typeof values[0] === 'string')\n return concatHex(values);\n return concatBytes(values);\n}\nexport function concatBytes(values) {\n let length = 0;\n for (const arr of values) {\n length += arr.length;\n }\n const result = new Uint8Array(length);\n let offset = 0;\n for (const arr of values) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\nexport function concatHex(values) {\n return `0x${values.reduce((acc, x) => acc + x.replace('0x', ''), '')}`;\n}\n//# sourceMappingURL=concat.js.map","import { BaseError } from './base.js';\nexport class NegativeOffsetError extends BaseError {\n constructor({ offset }) {\n super(`Offset \\`${offset}\\` cannot be negative.`, {\n name: 'NegativeOffsetError',\n });\n }\n}\nexport class PositionOutOfBoundsError extends BaseError {\n constructor({ length, position }) {\n super(`Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`, { name: 'PositionOutOfBoundsError' });\n }\n}\nexport class RecursiveReadLimitExceededError extends BaseError {\n constructor({ count, limit }) {\n super(`Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`, { name: 'RecursiveReadLimitExceededError' });\n }\n}\n//# sourceMappingURL=cursor.js.map","import { NegativeOffsetError, PositionOutOfBoundsError, RecursiveReadLimitExceededError, } from '../errors/cursor.js';\nconst staticCursor = {\n bytes: new Uint8Array(),\n dataView: new DataView(new ArrayBuffer(0)),\n position: 0,\n positionReadCount: new Map(),\n recursiveReadCount: 0,\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n assertReadLimit() {\n if (this.recursiveReadCount >= this.recursiveReadLimit)\n throw new RecursiveReadLimitExceededError({\n count: this.recursiveReadCount + 1,\n limit: this.recursiveReadLimit,\n });\n },\n assertPosition(position) {\n if (position < 0 || position > this.bytes.length - 1)\n throw new PositionOutOfBoundsError({\n length: this.bytes.length,\n position,\n });\n },\n decrementPosition(offset) {\n if (offset < 0)\n throw new NegativeOffsetError({ offset });\n const position = this.position - offset;\n this.assertPosition(position);\n this.position = position;\n },\n getReadCount(position) {\n return this.positionReadCount.get(position || this.position) || 0;\n },\n incrementPosition(offset) {\n if (offset < 0)\n throw new NegativeOffsetError({ offset });\n const position = this.position + offset;\n this.assertPosition(position);\n this.position = position;\n },\n inspectByte(position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position);\n return this.bytes[position];\n },\n inspectBytes(length, position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position + length - 1);\n return this.bytes.subarray(position, position + length);\n },\n inspectUint8(position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position);\n return this.bytes[position];\n },\n inspectUint16(position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position + 1);\n return this.dataView.getUint16(position);\n },\n inspectUint24(position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position + 2);\n return ((this.dataView.getUint16(position) << 8) +\n this.dataView.getUint8(position + 2));\n },\n inspectUint32(position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position + 3);\n return this.dataView.getUint32(position);\n },\n pushByte(byte) {\n this.assertPosition(this.position);\n this.bytes[this.position] = byte;\n this.position++;\n },\n pushBytes(bytes) {\n this.assertPosition(this.position + bytes.length - 1);\n this.bytes.set(bytes, this.position);\n this.position += bytes.length;\n },\n pushUint8(value) {\n this.assertPosition(this.position);\n this.bytes[this.position] = value;\n this.position++;\n },\n pushUint16(value) {\n this.assertPosition(this.position + 1);\n this.dataView.setUint16(this.position, value);\n this.position += 2;\n },\n pushUint24(value) {\n this.assertPosition(this.position + 2);\n this.dataView.setUint16(this.position, value >> 8);\n this.dataView.setUint8(this.position + 2, value & ~4294967040);\n this.position += 3;\n },\n pushUint32(value) {\n this.assertPosition(this.position + 3);\n this.dataView.setUint32(this.position, value);\n this.position += 4;\n },\n readByte() {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectByte();\n this.position++;\n return value;\n },\n readBytes(length, size) {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectBytes(length);\n this.position += size ?? length;\n return value;\n },\n readUint8() {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectUint8();\n this.position += 1;\n return value;\n },\n readUint16() {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectUint16();\n this.position += 2;\n return value;\n },\n readUint24() {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectUint24();\n this.position += 3;\n return value;\n },\n readUint32() {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectUint32();\n this.position += 4;\n return value;\n },\n get remaining() {\n return this.bytes.length - this.position;\n },\n setPosition(position) {\n const oldPosition = this.position;\n this.assertPosition(position);\n this.position = position;\n return () => (this.position = oldPosition);\n },\n _touch() {\n if (this.recursiveReadLimit === Number.POSITIVE_INFINITY)\n return;\n const count = this.getReadCount();\n this.positionReadCount.set(this.position, count + 1);\n if (count > 0)\n this.recursiveReadCount++;\n },\n};\nexport function createCursor(bytes, { recursiveReadLimit = 8_192 } = {}) {\n const cursor = Object.create(staticCursor);\n cursor.bytes = bytes;\n cursor.dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n cursor.positionReadCount = new Map();\n cursor.recursiveReadLimit = recursiveReadLimit;\n return cursor;\n}\n//# sourceMappingURL=cursor.js.map","import { BaseError } from '../../errors/base.js';\nimport { createCursor, } from '../cursor.js';\nimport { hexToBytes } from './toBytes.js';\nimport { bytesToHex } from './toHex.js';\nexport function toRlp(bytes, to = 'hex') {\n const encodable = getEncodable(bytes);\n const cursor = createCursor(new Uint8Array(encodable.length));\n encodable.encode(cursor);\n if (to === 'hex')\n return bytesToHex(cursor.bytes);\n return cursor.bytes;\n}\nexport function bytesToRlp(bytes, to = 'bytes') {\n return toRlp(bytes, to);\n}\nexport function hexToRlp(hex, to = 'hex') {\n return toRlp(hex, to);\n}\nfunction getEncodable(bytes) {\n if (Array.isArray(bytes))\n return getEncodableList(bytes.map((x) => getEncodable(x)));\n return getEncodableBytes(bytes);\n}\nfunction getEncodableList(list) {\n const bodyLength = list.reduce((acc, x) => acc + x.length, 0);\n const sizeOfBodyLength = getSizeOfLength(bodyLength);\n const length = (() => {\n if (bodyLength <= 55)\n return 1 + bodyLength;\n return 1 + sizeOfBodyLength + bodyLength;\n })();\n return {\n length,\n encode(cursor) {\n if (bodyLength <= 55) {\n cursor.pushByte(0xc0 + bodyLength);\n }\n else {\n cursor.pushByte(0xc0 + 55 + sizeOfBodyLength);\n if (sizeOfBodyLength === 1)\n cursor.pushUint8(bodyLength);\n else if (sizeOfBodyLength === 2)\n cursor.pushUint16(bodyLength);\n else if (sizeOfBodyLength === 3)\n cursor.pushUint24(bodyLength);\n else\n cursor.pushUint32(bodyLength);\n }\n for (const { encode } of list) {\n encode(cursor);\n }\n },\n };\n}\nfunction getEncodableBytes(bytesOrHex) {\n const bytes = typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex;\n const sizeOfBytesLength = getSizeOfLength(bytes.length);\n const length = (() => {\n if (bytes.length === 1 && bytes[0] < 0x80)\n return 1;\n if (bytes.length <= 55)\n return 1 + bytes.length;\n return 1 + sizeOfBytesLength + bytes.length;\n })();\n return {\n length,\n encode(cursor) {\n if (bytes.length === 1 && bytes[0] < 0x80) {\n cursor.pushBytes(bytes);\n }\n else if (bytes.length <= 55) {\n cursor.pushByte(0x80 + bytes.length);\n cursor.pushBytes(bytes);\n }\n else {\n cursor.pushByte(0x80 + 55 + sizeOfBytesLength);\n if (sizeOfBytesLength === 1)\n cursor.pushUint8(bytes.length);\n else if (sizeOfBytesLength === 2)\n cursor.pushUint16(bytes.length);\n else if (sizeOfBytesLength === 3)\n cursor.pushUint24(bytes.length);\n else\n cursor.pushUint32(bytes.length);\n cursor.pushBytes(bytes);\n }\n },\n };\n}\nfunction getSizeOfLength(length) {\n if (length < 2 ** 8)\n return 1;\n if (length < 2 ** 16)\n return 2;\n if (length < 2 ** 24)\n return 3;\n if (length < 2 ** 32)\n return 4;\n throw new BaseError('Length is too large.');\n}\n//# sourceMappingURL=toRlp.js.map","export const etherUnits = {\n gwei: 9,\n wei: 18,\n};\nexport const gweiUnits = {\n ether: -9,\n wei: 9,\n};\nexport const weiUnits = {\n ether: -18,\n gwei: -9,\n};\n//# sourceMappingURL=unit.js.map","/**\n * Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number..\n *\n * - Docs: https://viem.sh/docs/utilities/formatUnits\n *\n * @example\n * import { formatUnits } from 'viem'\n *\n * formatUnits(420000000000n, 9)\n * // '420'\n */\nexport function formatUnits(value, decimals) {\n let display = value.toString();\n const negative = display.startsWith('-');\n if (negative)\n display = display.slice(1);\n display = display.padStart(decimals, '0');\n let [integer, fraction] = [\n display.slice(0, display.length - decimals),\n display.slice(display.length - decimals),\n ];\n fraction = fraction.replace(/(0+)$/, '');\n return `${negative ? '-' : ''}${integer || '0'}${fraction ? `.${fraction}` : ''}`;\n}\n//# sourceMappingURL=formatUnits.js.map","import { gweiUnits } from '../../constants/unit.js';\nimport { formatUnits } from './formatUnits.js';\n/**\n * Converts numerical wei to a string representation of gwei.\n *\n * - Docs: https://viem.sh/docs/utilities/formatGwei\n *\n * @example\n * import { formatGwei } from 'viem'\n *\n * formatGwei(1000000000n)\n * // '1'\n */\nexport function formatGwei(wei, unit = 'wei') {\n return formatUnits(wei, gweiUnits[unit]);\n}\n//# sourceMappingURL=formatGwei.js.map","import { formatEther } from '../utils/unit/formatEther.js';\nimport { formatGwei } from '../utils/unit/formatGwei.js';\nimport { BaseError } from './base.js';\nexport function prettyPrint(args) {\n const entries = Object.entries(args)\n .map(([key, value]) => {\n if (value === undefined || value === false)\n return null;\n return [key, value];\n })\n .filter(Boolean);\n const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0);\n return entries\n .map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`)\n .join('\\n');\n}\nexport class FeeConflictError extends BaseError {\n constructor() {\n super([\n 'Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.',\n 'Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others.',\n ].join('\\n'), { name: 'FeeConflictError' });\n }\n}\nexport class InvalidLegacyVError extends BaseError {\n constructor({ v }) {\n super(`Invalid \\`v\\` value \"${v}\". Expected 27 or 28.`, {\n name: 'InvalidLegacyVError',\n });\n }\n}\nexport class InvalidSerializableTransactionError extends BaseError {\n constructor({ transaction }) {\n super('Cannot infer a transaction type from provided transaction.', {\n metaMessages: [\n 'Provided Transaction:',\n '{',\n prettyPrint(transaction),\n '}',\n '',\n 'To infer the type, either provide:',\n '- a `type` to the Transaction, or',\n '- an EIP-1559 Transaction with `maxFeePerGas`, or',\n '- an EIP-2930 Transaction with `gasPrice` & `accessList`, or',\n '- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or',\n '- an EIP-7702 Transaction with `authorizationList`, or',\n '- a Legacy Transaction with `gasPrice`',\n ],\n name: 'InvalidSerializableTransactionError',\n });\n }\n}\nexport class InvalidSerializedTransactionTypeError extends BaseError {\n constructor({ serializedType }) {\n super(`Serialized transaction type \"${serializedType}\" is invalid.`, {\n name: 'InvalidSerializedTransactionType',\n });\n Object.defineProperty(this, \"serializedType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.serializedType = serializedType;\n }\n}\nexport class InvalidSerializedTransactionError extends BaseError {\n constructor({ attributes, serializedTransaction, type, }) {\n const missing = Object.entries(attributes)\n .map(([key, value]) => (typeof value === 'undefined' ? key : undefined))\n .filter(Boolean);\n super(`Invalid serialized transaction of type \"${type}\" was provided.`, {\n metaMessages: [\n `Serialized Transaction: \"${serializedTransaction}\"`,\n missing.length > 0 ? `Missing Attributes: ${missing.join(', ')}` : '',\n ].filter(Boolean),\n name: 'InvalidSerializedTransactionError',\n });\n Object.defineProperty(this, \"serializedTransaction\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"type\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.serializedTransaction = serializedTransaction;\n this.type = type;\n }\n}\nexport class InvalidStorageKeySizeError extends BaseError {\n constructor({ storageKey }) {\n super(`Size for storage key \"${storageKey}\" is invalid. Expected 32 bytes. Got ${Math.floor((storageKey.length - 2) / 2)} bytes.`, { name: 'InvalidStorageKeySizeError' });\n }\n}\nexport class TransactionExecutionError extends BaseError {\n constructor(cause, { account, docsPath, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, }) {\n const prettyArgs = prettyPrint({\n chain: chain && `${chain?.name} (id: ${chain?.id})`,\n from: account?.address,\n to,\n value: typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice: typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas: typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n });\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Request Arguments:',\n prettyArgs,\n ].filter(Boolean),\n name: 'TransactionExecutionError',\n });\n Object.defineProperty(this, \"cause\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.cause = cause;\n }\n}\nexport class TransactionNotFoundError extends BaseError {\n constructor({ blockHash, blockNumber, blockTag, hash, index, }) {\n let identifier = 'Transaction';\n if (blockTag && index !== undefined)\n identifier = `Transaction at block time \"${blockTag}\" at index \"${index}\"`;\n if (blockHash && index !== undefined)\n identifier = `Transaction at block hash \"${blockHash}\" at index \"${index}\"`;\n if (blockNumber && index !== undefined)\n identifier = `Transaction at block number \"${blockNumber}\" at index \"${index}\"`;\n if (hash)\n identifier = `Transaction with hash \"${hash}\"`;\n super(`${identifier} could not be found.`, {\n name: 'TransactionNotFoundError',\n });\n }\n}\nexport class TransactionReceiptNotFoundError extends BaseError {\n constructor({ hash }) {\n super(`Transaction receipt with hash \"${hash}\" could not be found. The Transaction may not be processed on a block yet.`, {\n name: 'TransactionReceiptNotFoundError',\n });\n }\n}\nexport class TransactionReceiptRevertedError extends BaseError {\n constructor({ receipt }) {\n super(`Transaction with hash \"${receipt.transactionHash}\" reverted.`, {\n metaMessages: [\n 'The receipt marked the transaction as \"reverted\". This could mean that the function on the contract you are trying to call threw an error.',\n ' ',\n 'You can attempt to extract the revert reason by:',\n '- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract',\n '- using the `call` Action with raw `data`',\n ],\n name: 'TransactionReceiptRevertedError',\n });\n Object.defineProperty(this, \"receipt\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.receipt = receipt;\n }\n}\nexport class WaitForTransactionReceiptTimeoutError extends BaseError {\n constructor({ hash }) {\n super(`Timed out while waiting for transaction with hash \"${hash}\" to be confirmed.`, { name: 'WaitForTransactionReceiptTimeoutError' });\n }\n}\n//# sourceMappingURL=transaction.js.map","import { toHex } from '../encoding/toHex.js';\nimport { toYParitySignatureArray } from '../transaction/serializeTransaction.js';\n/*\n * Serializes an EIP-7702 authorization list.\n */\nexport function serializeAuthorizationList(authorizationList) {\n if (!authorizationList || authorizationList.length === 0)\n return [];\n const serializedAuthorizationList = [];\n for (const authorization of authorizationList) {\n const { chainId, nonce, ...signature } = authorization;\n const contractAddress = authorization.address;\n serializedAuthorizationList.push([\n chainId ? toHex(chainId) : '0x',\n contractAddress,\n nonce ? toHex(nonce) : '0x',\n ...toYParitySignatureArray({}, signature),\n ]);\n }\n return serializedAuthorizationList;\n}\n//# sourceMappingURL=serializeAuthorizationList.js.map","import { hexToBytes } from '../encoding/toBytes.js';\nimport { bytesToHex } from '../encoding/toHex.js';\n/**\n * Compute commitments from a list of blobs.\n *\n * @example\n * ```ts\n * import { blobsToCommitments, toBlobs } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * ```\n */\nexport function blobsToCommitments(parameters) {\n const { kzg } = parameters;\n const to = parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes');\n const blobs = (typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x))\n : parameters.blobs);\n const commitments = [];\n for (const blob of blobs)\n commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)));\n return (to === 'bytes'\n ? commitments\n : commitments.map((x) => bytesToHex(x)));\n}\n//# sourceMappingURL=blobsToCommitments.js.map","import { hexToBytes } from '../encoding/toBytes.js';\nimport { bytesToHex } from '../encoding/toHex.js';\n/**\n * Compute the proofs for a list of blobs and their commitments.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n * ```\n */\nexport function blobsToProofs(parameters) {\n const { kzg } = parameters;\n const to = parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes');\n const blobs = (typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x))\n : parameters.blobs);\n const commitments = (typeof parameters.commitments[0] === 'string'\n ? parameters.commitments.map((x) => hexToBytes(x))\n : parameters.commitments);\n const proofs = [];\n for (let i = 0; i < blobs.length; i++) {\n const blob = blobs[i];\n const commitment = commitments[i];\n proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)));\n }\n return (to === 'bytes'\n ? proofs\n : proofs.map((x) => bytesToHex(x)));\n}\n//# sourceMappingURL=blobsToProofs.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport { SHA224 as SHA224n, sha224 as sha224n, SHA256 as SHA256n, sha256 as sha256n, } from \"./sha2.js\";\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256 = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256 = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224 = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224 = sha224n;\n//# sourceMappingURL=sha256.js.map","import { sha256 as noble_sha256 } from '@noble/hashes/sha256';\nimport { isHex } from '../data/isHex.js';\nimport { toBytes } from '../encoding/toBytes.js';\nimport { toHex } from '../encoding/toHex.js';\nexport function sha256(value, to_) {\n const to = to_ || 'hex';\n const bytes = noble_sha256(isHex(value, { strict: false }) ? toBytes(value) : value);\n if (to === 'bytes')\n return bytes;\n return toHex(bytes);\n}\n//# sourceMappingURL=sha256.js.map","import { bytesToHex } from '../encoding/toHex.js';\nimport { sha256 } from '../hash/sha256.js';\n/**\n * Transform a commitment to it's versioned hash.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentToVersionedHash,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const [commitment] = blobsToCommitments({ blobs, kzg })\n * const versionedHash = commitmentToVersionedHash({ commitment })\n * ```\n */\nexport function commitmentToVersionedHash(parameters) {\n const { commitment, version = 1 } = parameters;\n const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes');\n const versionedHash = sha256(commitment, 'bytes');\n versionedHash.set([version], 0);\n return (to === 'bytes' ? versionedHash : bytesToHex(versionedHash));\n}\n//# sourceMappingURL=commitmentToVersionedHash.js.map","import { commitmentToVersionedHash, } from './commitmentToVersionedHash.js';\n/**\n * Transform a list of commitments to their versioned hashes.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentsToVersionedHashes,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const versionedHashes = commitmentsToVersionedHashes({ commitments })\n * ```\n */\nexport function commitmentsToVersionedHashes(parameters) {\n const { commitments, version } = parameters;\n const to = parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes');\n const hashes = [];\n for (const commitment of commitments) {\n hashes.push(commitmentToVersionedHash({\n commitment,\n to,\n version,\n }));\n }\n return hashes;\n}\n//# sourceMappingURL=commitmentsToVersionedHashes.js.map","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n/** Blob limit per transaction. */\nconst blobsPerTransaction = 6;\n/** The number of bytes in a BLS scalar field element. */\nexport const bytesPerFieldElement = 32;\n/** The number of field elements in a blob. */\nexport const fieldElementsPerBlob = 4096;\n/** The number of bytes in a blob. */\nexport const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob;\n/** Blob bytes limit per transaction. */\nexport const maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction -\n // terminator byte (0x80).\n 1 -\n // zero byte (0x00) appended to each field element.\n 1 * fieldElementsPerBlob * blobsPerTransaction;\n//# sourceMappingURL=blob.js.map","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\nexport const versionedHashVersionKzg = 1;\n//# sourceMappingURL=kzg.js.map","import { versionedHashVersionKzg } from '../constants/kzg.js';\nimport { BaseError } from './base.js';\nexport class BlobSizeTooLargeError extends BaseError {\n constructor({ maxSize, size }) {\n super('Blob size is too large.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],\n name: 'BlobSizeTooLargeError',\n });\n }\n}\nexport class EmptyBlobError extends BaseError {\n constructor() {\n super('Blob data must not be empty.', { name: 'EmptyBlobError' });\n }\n}\nexport class InvalidVersionedHashSizeError extends BaseError {\n constructor({ hash, size, }) {\n super(`Versioned hash \"${hash}\" size is invalid.`, {\n metaMessages: ['Expected: 32', `Received: ${size}`],\n name: 'InvalidVersionedHashSizeError',\n });\n }\n}\nexport class InvalidVersionedHashVersionError extends BaseError {\n constructor({ hash, version, }) {\n super(`Versioned hash \"${hash}\" version is invalid.`, {\n metaMessages: [\n `Expected: ${versionedHashVersionKzg}`,\n `Received: ${version}`,\n ],\n name: 'InvalidVersionedHashVersionError',\n });\n }\n}\n//# sourceMappingURL=blob.js.map","import { bytesPerBlob, bytesPerFieldElement, fieldElementsPerBlob, maxBytesPerTransaction, } from '../../constants/blob.js';\nimport { BlobSizeTooLargeError, EmptyBlobError, } from '../../errors/blob.js';\nimport { createCursor } from '../cursor.js';\nimport { size } from '../data/size.js';\nimport { hexToBytes } from '../encoding/toBytes.js';\nimport { bytesToHex } from '../encoding/toHex.js';\n/**\n * Transforms arbitrary data to blobs.\n *\n * @example\n * ```ts\n * import { toBlobs, stringToHex } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * ```\n */\nexport function toBlobs(parameters) {\n const to = parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes');\n const data = (typeof parameters.data === 'string'\n ? hexToBytes(parameters.data)\n : parameters.data);\n const size_ = size(data);\n if (!size_)\n throw new EmptyBlobError();\n if (size_ > maxBytesPerTransaction)\n throw new BlobSizeTooLargeError({\n maxSize: maxBytesPerTransaction,\n size: size_,\n });\n const blobs = [];\n let active = true;\n let position = 0;\n while (active) {\n const blob = createCursor(new Uint8Array(bytesPerBlob));\n let size = 0;\n while (size < fieldElementsPerBlob) {\n const bytes = data.slice(position, position + (bytesPerFieldElement - 1));\n // Push a zero byte so the field element doesn't overflow the BLS modulus.\n blob.pushByte(0x00);\n // Push the current segment of data bytes.\n blob.pushBytes(bytes);\n // If we detect that the current segment of data bytes is less than 31 bytes,\n // we can stop processing and push a terminator byte to indicate the end of the blob.\n if (bytes.length < 31) {\n blob.pushByte(0x80);\n active = false;\n break;\n }\n size++;\n position += 31;\n }\n blobs.push(blob);\n }\n return (to === 'bytes'\n ? blobs.map((x) => x.bytes)\n : blobs.map((x) => bytesToHex(x.bytes)));\n}\n//# sourceMappingURL=toBlobs.js.map","import { blobsToCommitments, } from './blobsToCommitments.js';\nimport { blobsToProofs } from './blobsToProofs.js';\nimport { toBlobs } from './toBlobs.js';\n/**\n * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.\n *\n * @example\n * ```ts\n * import { toBlobSidecars, stringToHex } from 'viem'\n *\n * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })\n * ```\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs,\n * blobsToProofs,\n * toBlobSidecars,\n * stringToHex\n * } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n *\n * const sidecars = toBlobSidecars({ blobs, commitments, proofs })\n * ```\n */\nexport function toBlobSidecars(parameters) {\n const { data, kzg, to } = parameters;\n const blobs = parameters.blobs ?? toBlobs({ data: data, to });\n const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg, to });\n const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg, to });\n const sidecars = [];\n for (let i = 0; i < blobs.length; i++)\n sidecars.push({\n blob: blobs[i],\n commitment: commitments[i],\n proof: proofs[i],\n });\n return sidecars;\n}\n//# sourceMappingURL=toBlobSidecars.js.map","import { BaseError } from './base.js';\nexport class InvalidAddressError extends BaseError {\n constructor({ address }) {\n super(`Address \"${address}\" is invalid.`, {\n metaMessages: [\n '- Address must be a hex value of 20 bytes (40 hex characters).',\n '- Address must match its checksum counterpart.',\n ],\n name: 'InvalidAddressError',\n });\n }\n}\n//# sourceMappingURL=address.js.map","import { BaseError } from './base.js';\nexport class ChainDoesNotSupportContract extends BaseError {\n constructor({ blockNumber, chain, contract, }) {\n super(`Chain \"${chain.name}\" does not support contract \"${contract.name}\".`, {\n metaMessages: [\n 'This could be due to any of the following:',\n ...(blockNumber &&\n contract.blockCreated &&\n contract.blockCreated > blockNumber\n ? [\n `- The contract \"${contract.name}\" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).`,\n ]\n : [\n `- The chain does not have the contract \"${contract.name}\" configured.`,\n ]),\n ],\n name: 'ChainDoesNotSupportContract',\n });\n }\n}\nexport class ChainMismatchError extends BaseError {\n constructor({ chain, currentChainId, }) {\n super(`The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} – ${chain.name}).`, {\n metaMessages: [\n `Current Chain ID: ${currentChainId}`,\n `Expected Chain ID: ${chain.id} – ${chain.name}`,\n ],\n name: 'ChainMismatchError',\n });\n }\n}\nexport class ChainNotFoundError extends BaseError {\n constructor() {\n super([\n 'No chain was provided to the request.',\n 'Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient.',\n ].join('\\n'), {\n name: 'ChainNotFoundError',\n });\n }\n}\nexport class ClientChainNotConfiguredError extends BaseError {\n constructor() {\n super('No chain was provided to the Client.', {\n name: 'ClientChainNotConfiguredError',\n });\n }\n}\nexport class InvalidChainIdError extends BaseError {\n constructor({ chainId }) {\n super(typeof chainId === 'number'\n ? `Chain ID \"${chainId}\" is invalid.`\n : 'Chain ID is invalid.', { name: 'InvalidChainIdError' });\n }\n}\n//# sourceMappingURL=chain.js.map","import { formatGwei } from '../utils/unit/formatGwei.js';\nimport { BaseError } from './base.js';\nexport class ExecutionRevertedError extends BaseError {\n constructor({ cause, message, } = {}) {\n const reason = message\n ?.replace('execution reverted: ', '')\n ?.replace('execution reverted', '');\n super(`Execution reverted ${reason ? `with reason: ${reason}` : 'for an unknown reason'}.`, {\n cause,\n name: 'ExecutionRevertedError',\n });\n }\n}\nObject.defineProperty(ExecutionRevertedError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 3\n});\nObject.defineProperty(ExecutionRevertedError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /execution reverted/\n});\nexport class FeeCapTooHighError extends BaseError {\n constructor({ cause, maxFeePerGas, } = {}) {\n super(`The fee cap (\\`maxFeePerGas\\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''}) cannot be higher than the maximum allowed value (2^256-1).`, {\n cause,\n name: 'FeeCapTooHighError',\n });\n }\n}\nObject.defineProperty(FeeCapTooHighError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /max fee per gas higher than 2\\^256-1|fee cap higher than 2\\^256-1/\n});\nexport class FeeCapTooLowError extends BaseError {\n constructor({ cause, maxFeePerGas, } = {}) {\n super(`The fee cap (\\`maxFeePerGas\\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ''} gwei) cannot be lower than the block base fee.`, {\n cause,\n name: 'FeeCapTooLowError',\n });\n }\n}\nObject.defineProperty(FeeCapTooLowError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/\n});\nexport class NonceTooHighError extends BaseError {\n constructor({ cause, nonce, } = {}) {\n super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ''}is higher than the next one expected.`, { cause, name: 'NonceTooHighError' });\n }\n}\nObject.defineProperty(NonceTooHighError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /nonce too high/\n});\nexport class NonceTooLowError extends BaseError {\n constructor({ cause, nonce, } = {}) {\n super([\n `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ''}is lower than the current nonce of the account.`,\n 'Try increasing the nonce or find the latest nonce with `getTransactionCount`.',\n ].join('\\n'), { cause, name: 'NonceTooLowError' });\n }\n}\nObject.defineProperty(NonceTooLowError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /nonce too low|transaction already imported|already known/\n});\nexport class NonceMaxValueError extends BaseError {\n constructor({ cause, nonce, } = {}) {\n super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ''}exceeds the maximum allowed nonce.`, { cause, name: 'NonceMaxValueError' });\n }\n}\nObject.defineProperty(NonceMaxValueError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /nonce has max value/\n});\nexport class InsufficientFundsError extends BaseError {\n constructor({ cause } = {}) {\n super([\n 'The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account.',\n ].join('\\n'), {\n cause,\n metaMessages: [\n 'This error could arise when the account does not have enough funds to:',\n ' - pay for the total gas fee,',\n ' - pay for the value to send.',\n ' ',\n 'The cost of the transaction is calculated as `gas * gas fee + value`, where:',\n ' - `gas` is the amount of gas needed for transaction to execute,',\n ' - `gas fee` is the gas fee,',\n ' - `value` is the amount of ether to send to the recipient.',\n ],\n name: 'InsufficientFundsError',\n });\n }\n}\nObject.defineProperty(InsufficientFundsError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /insufficient funds|exceeds transaction sender account balance/\n});\nexport class IntrinsicGasTooHighError extends BaseError {\n constructor({ cause, gas, } = {}) {\n super(`The amount of gas ${gas ? `(${gas}) ` : ''}provided for the transaction exceeds the limit allowed for the block.`, {\n cause,\n name: 'IntrinsicGasTooHighError',\n });\n }\n}\nObject.defineProperty(IntrinsicGasTooHighError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /intrinsic gas too high|gas limit reached/\n});\nexport class IntrinsicGasTooLowError extends BaseError {\n constructor({ cause, gas, } = {}) {\n super(`The amount of gas ${gas ? `(${gas}) ` : ''}provided for the transaction is too low.`, {\n cause,\n name: 'IntrinsicGasTooLowError',\n });\n }\n}\nObject.defineProperty(IntrinsicGasTooLowError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /intrinsic gas too low/\n});\nexport class TransactionTypeNotSupportedError extends BaseError {\n constructor({ cause }) {\n super('The transaction type is not supported for this chain.', {\n cause,\n name: 'TransactionTypeNotSupportedError',\n });\n }\n}\nObject.defineProperty(TransactionTypeNotSupportedError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /transaction type not valid/\n});\nexport class TipAboveFeeCapError extends BaseError {\n constructor({ cause, maxPriorityFeePerGas, maxFeePerGas, } = {}) {\n super([\n `The provided tip (\\`maxPriorityFeePerGas\\`${maxPriorityFeePerGas\n ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei`\n : ''}) cannot be higher than the fee cap (\\`maxFeePerGas\\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''}).`,\n ].join('\\n'), {\n cause,\n name: 'TipAboveFeeCapError',\n });\n }\n}\nObject.defineProperty(TipAboveFeeCapError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/\n});\nexport class UnknownNodeError extends BaseError {\n constructor({ cause }) {\n super(`An error occurred while executing: ${cause?.shortMessage}`, {\n cause,\n name: 'UnknownNodeError',\n });\n }\n}\n//# sourceMappingURL=node.js.map","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap extends Map {\n constructor(size) {\n super();\n Object.defineProperty(this, \"maxSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.maxSize = size;\n }\n get(key) {\n const value = super.get(key);\n if (super.has(key) && value !== undefined) {\n this.delete(key);\n super.set(key, value);\n }\n return value;\n }\n set(key, value) {\n super.set(key, value);\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value;\n if (firstKey)\n this.delete(firstKey);\n }\n return this;\n }\n}\n//# sourceMappingURL=lru.js.map","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./_u64.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, clean, createHasher, createXOFer, Hash, swap32IfBE, toBytes, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/** Keccak sponge function. */\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n this.enableXOF = false;\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));\n/** SHA3-224 hash function. */\nexport const sha3_224 = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\nconst genShake = (suffix, blockLen, outputLen) => createXOFer((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();\n//# sourceMappingURL=sha3.js.map","import { keccak_256 } from '@noble/hashes/sha3';\nimport { isHex } from '../data/isHex.js';\nimport { toBytes } from '../encoding/toBytes.js';\nimport { toHex } from '../encoding/toHex.js';\nexport function keccak256(value, to_) {\n const to = to_ || 'hex';\n const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value);\n if (to === 'bytes')\n return bytes;\n return toHex(bytes);\n}\n//# sourceMappingURL=keccak256.js.map","import { InvalidAddressError } from '../../errors/address.js';\nimport { stringToBytes, } from '../encoding/toBytes.js';\nimport { keccak256 } from '../hash/keccak256.js';\nimport { LruMap } from '../lru.js';\nimport { isAddress } from './isAddress.js';\nconst checksumAddressCache = /*#__PURE__*/ new LruMap(8192);\nexport function checksumAddress(address_, \n/**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\nchainId) {\n if (checksumAddressCache.has(`${address_}.${chainId}`))\n return checksumAddressCache.get(`${address_}.${chainId}`);\n const hexAddress = chainId\n ? `${chainId}${address_.toLowerCase()}`\n : address_.substring(2).toLowerCase();\n const hash = keccak256(stringToBytes(hexAddress), 'bytes');\n const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split('');\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1] >> 4 >= 8 && address[i]) {\n address[i] = address[i].toUpperCase();\n }\n if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {\n address[i + 1] = address[i + 1].toUpperCase();\n }\n }\n const result = `0x${address.join('')}`;\n checksumAddressCache.set(`${address_}.${chainId}`, result);\n return result;\n}\nexport function getAddress(address, \n/**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\nchainId) {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address });\n return checksumAddress(address, chainId);\n}\n//# sourceMappingURL=getAddress.js.map","import { LruMap } from '../lru.js';\nimport { checksumAddress } from './getAddress.js';\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/;\n/** @internal */\nexport const isAddressCache = /*#__PURE__*/ new LruMap(8192);\nexport function isAddress(address, options) {\n const { strict = true } = options ?? {};\n const cacheKey = `${address}.${strict}`;\n if (isAddressCache.has(cacheKey))\n return isAddressCache.get(cacheKey);\n const result = (() => {\n if (!addressRegex.test(address))\n return false;\n if (address.toLowerCase() === address)\n return true;\n if (strict)\n return checksumAddress(address) === address;\n return true;\n })();\n isAddressCache.set(cacheKey, result);\n return result;\n}\n//# sourceMappingURL=isAddress.js.map","import { SliceOffsetOutOfBoundsError, } from '../../errors/data.js';\nimport { isHex } from './isHex.js';\nimport { size } from './size.js';\n/**\n * @description Returns a section of the hex or byte array given a start/end bytes offset.\n *\n * @param value The hex or byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function slice(value, start, end, { strict } = {}) {\n if (isHex(value, { strict: false }))\n return sliceHex(value, start, end, {\n strict,\n });\n return sliceBytes(value, start, end, {\n strict,\n });\n}\nfunction assertStartOffset(value, start) {\n if (typeof start === 'number' && start > 0 && start > size(value) - 1)\n throw new SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: size(value),\n });\n}\nfunction assertEndOffset(value, start, end) {\n if (typeof start === 'number' &&\n typeof end === 'number' &&\n size(value) !== end - start) {\n throw new SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: size(value),\n });\n }\n}\n/**\n * @description Returns a section of the byte array given a start/end bytes offset.\n *\n * @param value The byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceBytes(value_, start, end, { strict } = {}) {\n assertStartOffset(value_, start);\n const value = value_.slice(start, end);\n if (strict)\n assertEndOffset(value, start, end);\n return value;\n}\n/**\n * @description Returns a section of the hex value given a start/end bytes offset.\n *\n * @param value The hex value to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceHex(value_, start, end, { strict } = {}) {\n assertStartOffset(value_, start);\n const value = `0x${value_\n .replace('0x', '')\n .slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`;\n if (strict)\n assertEndOffset(value, start, end);\n return value;\n}\n//# sourceMappingURL=slice.js.map","import { versionedHashVersionKzg } from '../../constants/kzg.js';\nimport { maxUint256 } from '../../constants/number.js';\nimport { InvalidAddressError, } from '../../errors/address.js';\nimport { BaseError } from '../../errors/base.js';\nimport { EmptyBlobError, InvalidVersionedHashSizeError, InvalidVersionedHashVersionError, } from '../../errors/blob.js';\nimport { InvalidChainIdError, } from '../../errors/chain.js';\nimport { FeeCapTooHighError, TipAboveFeeCapError, } from '../../errors/node.js';\nimport { isAddress } from '../address/isAddress.js';\nimport { size } from '../data/size.js';\nimport { slice } from '../data/slice.js';\nimport { hexToNumber } from '../encoding/fromHex.js';\nexport function assertTransactionEIP7702(transaction) {\n const { authorizationList } = transaction;\n if (authorizationList) {\n for (const authorization of authorizationList) {\n const { chainId } = authorization;\n const address = authorization.address;\n if (!isAddress(address))\n throw new InvalidAddressError({ address });\n if (chainId < 0)\n throw new InvalidChainIdError({ chainId });\n }\n }\n assertTransactionEIP1559(transaction);\n}\nexport function assertTransactionEIP4844(transaction) {\n const { blobVersionedHashes } = transaction;\n if (blobVersionedHashes) {\n if (blobVersionedHashes.length === 0)\n throw new EmptyBlobError();\n for (const hash of blobVersionedHashes) {\n const size_ = size(hash);\n const version = hexToNumber(slice(hash, 0, 1));\n if (size_ !== 32)\n throw new InvalidVersionedHashSizeError({ hash, size: size_ });\n if (version !== versionedHashVersionKzg)\n throw new InvalidVersionedHashVersionError({\n hash,\n version,\n });\n }\n }\n assertTransactionEIP1559(transaction);\n}\nexport function assertTransactionEIP1559(transaction) {\n const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction;\n if (chainId <= 0)\n throw new InvalidChainIdError({ chainId });\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n if (maxFeePerGas && maxFeePerGas > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas });\n if (maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas)\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });\n}\nexport function assertTransactionEIP2930(transaction) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;\n if (chainId <= 0)\n throw new InvalidChainIdError({ chainId });\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError('`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.');\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });\n}\nexport function assertTransactionLegacy(transaction) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n if (typeof chainId !== 'undefined' && chainId <= 0)\n throw new InvalidChainIdError({ chainId });\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError('`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.');\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });\n}\n//# sourceMappingURL=assertTransaction.js.map","import { InvalidSerializableTransactionError, } from '../../errors/transaction.js';\nexport function getTransactionType(transaction) {\n if (transaction.type)\n return transaction.type;\n if (typeof transaction.authorizationList !== 'undefined')\n return 'eip7702';\n if (typeof transaction.blobs !== 'undefined' ||\n typeof transaction.blobVersionedHashes !== 'undefined' ||\n typeof transaction.maxFeePerBlobGas !== 'undefined' ||\n typeof transaction.sidecars !== 'undefined')\n return 'eip4844';\n if (typeof transaction.maxFeePerGas !== 'undefined' ||\n typeof transaction.maxPriorityFeePerGas !== 'undefined') {\n return 'eip1559';\n }\n if (typeof transaction.gasPrice !== 'undefined') {\n if (typeof transaction.accessList !== 'undefined')\n return 'eip2930';\n return 'legacy';\n }\n throw new InvalidSerializableTransactionError({ transaction });\n}\n//# sourceMappingURL=getTransactionType.js.map","import { InvalidAddressError, } from '../../errors/address.js';\nimport { InvalidStorageKeySizeError, } from '../../errors/transaction.js';\nimport { isAddress } from '../address/isAddress.js';\n/*\n * Serialize an EIP-2930 access list\n * @remarks\n * Use to create a transaction serializer with support for EIP-2930 access lists\n *\n * @param accessList - Array of objects of address and arrays of Storage Keys\n * @throws InvalidAddressError, InvalidStorageKeySizeError\n * @returns Array of hex strings\n */\nexport function serializeAccessList(accessList) {\n if (!accessList || accessList.length === 0)\n return [];\n const serializedAccessList = [];\n for (let i = 0; i < accessList.length; i++) {\n const { address, storageKeys } = accessList[i];\n for (let j = 0; j < storageKeys.length; j++) {\n if (storageKeys[j].length - 2 !== 64) {\n throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] });\n }\n }\n if (!isAddress(address, { strict: false })) {\n throw new InvalidAddressError({ address });\n }\n serializedAccessList.push([address, storageKeys]);\n }\n return serializedAccessList;\n}\n//# sourceMappingURL=serializeAccessList.js.map","import { InvalidLegacyVError, } from '../../errors/transaction.js';\nimport { serializeAuthorizationList, } from '../authorization/serializeAuthorizationList.js';\nimport { blobsToCommitments, } from '../blob/blobsToCommitments.js';\nimport { blobsToProofs, } from '../blob/blobsToProofs.js';\nimport { commitmentsToVersionedHashes, } from '../blob/commitmentsToVersionedHashes.js';\nimport { toBlobSidecars, } from '../blob/toBlobSidecars.js';\nimport { concatHex } from '../data/concat.js';\nimport { trim } from '../data/trim.js';\nimport { bytesToHex, numberToHex, } from '../encoding/toHex.js';\nimport { toRlp } from '../encoding/toRlp.js';\nimport { assertTransactionEIP1559, assertTransactionEIP2930, assertTransactionEIP4844, assertTransactionEIP7702, assertTransactionLegacy, } from './assertTransaction.js';\nimport { getTransactionType, } from './getTransactionType.js';\nimport { serializeAccessList, } from './serializeAccessList.js';\nexport function serializeTransaction(transaction, signature) {\n const type = getTransactionType(transaction);\n if (type === 'eip1559')\n return serializeTransactionEIP1559(transaction, signature);\n if (type === 'eip2930')\n return serializeTransactionEIP2930(transaction, signature);\n if (type === 'eip4844')\n return serializeTransactionEIP4844(transaction, signature);\n if (type === 'eip7702')\n return serializeTransactionEIP7702(transaction, signature);\n return serializeTransactionLegacy(transaction, signature);\n}\nfunction serializeTransactionEIP7702(transaction, signature) {\n const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data, } = transaction;\n assertTransactionEIP7702(transaction);\n const serializedAccessList = serializeAccessList(accessList);\n const serializedAuthorizationList = serializeAuthorizationList(authorizationList);\n return concatHex([\n '0x04',\n toRlp([\n numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n serializedAuthorizationList,\n ...toYParitySignatureArray(transaction, signature),\n ]),\n ]);\n}\nfunction serializeTransactionEIP4844(transaction, signature) {\n const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data, } = transaction;\n assertTransactionEIP4844(transaction);\n let blobVersionedHashes = transaction.blobVersionedHashes;\n let sidecars = transaction.sidecars;\n // If `blobs` are passed, we will need to compute the KZG commitments & proofs.\n if (transaction.blobs &&\n (typeof blobVersionedHashes === 'undefined' ||\n typeof sidecars === 'undefined')) {\n const blobs = (typeof transaction.blobs[0] === 'string'\n ? transaction.blobs\n : transaction.blobs.map((x) => bytesToHex(x)));\n const kzg = transaction.kzg;\n const commitments = blobsToCommitments({\n blobs,\n kzg,\n });\n if (typeof blobVersionedHashes === 'undefined')\n blobVersionedHashes = commitmentsToVersionedHashes({\n commitments,\n });\n if (typeof sidecars === 'undefined') {\n const proofs = blobsToProofs({ blobs, commitments, kzg });\n sidecars = toBlobSidecars({ blobs, commitments, proofs });\n }\n }\n const serializedAccessList = serializeAccessList(accessList);\n const serializedTransaction = [\n numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? numberToHex(maxFeePerBlobGas) : '0x',\n blobVersionedHashes ?? [],\n ...toYParitySignatureArray(transaction, signature),\n ];\n const blobs = [];\n const commitments = [];\n const proofs = [];\n if (sidecars)\n for (let i = 0; i < sidecars.length; i++) {\n const { blob, commitment, proof } = sidecars[i];\n blobs.push(blob);\n commitments.push(commitment);\n proofs.push(proof);\n }\n return concatHex([\n '0x03',\n sidecars\n ? // If sidecars are enabled, envelope turns into a \"wrapper\":\n toRlp([serializedTransaction, blobs, commitments, proofs])\n : // If sidecars are disabled, standard envelope is used:\n toRlp(serializedTransaction),\n ]);\n}\nfunction serializeTransactionEIP1559(transaction, signature) {\n const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data, } = transaction;\n assertTransactionEIP1559(transaction);\n const serializedAccessList = serializeAccessList(accessList);\n const serializedTransaction = [\n numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ];\n return concatHex([\n '0x02',\n toRlp(serializedTransaction),\n ]);\n}\nfunction serializeTransactionEIP2930(transaction, signature) {\n const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction;\n assertTransactionEIP2930(transaction);\n const serializedAccessList = serializeAccessList(accessList);\n const serializedTransaction = [\n numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ];\n return concatHex([\n '0x01',\n toRlp(serializedTransaction),\n ]);\n}\nfunction serializeTransactionLegacy(transaction, signature) {\n const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction;\n assertTransactionLegacy(transaction);\n let serializedTransaction = [\n nonce ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n ];\n if (signature) {\n const v = (() => {\n // EIP-155 (inferred chainId)\n if (signature.v >= 35n) {\n const inferredChainId = (signature.v - 35n) / 2n;\n if (inferredChainId > 0)\n return signature.v;\n return 27n + (signature.v === 35n ? 0n : 1n);\n }\n // EIP-155 (explicit chainId)\n if (chainId > 0)\n return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n);\n // Pre-EIP-155 (no chainId)\n const v = 27n + (signature.v === 27n ? 0n : 1n);\n if (signature.v !== v)\n throw new InvalidLegacyVError({ v: signature.v });\n return v;\n })();\n const r = trim(signature.r);\n const s = trim(signature.s);\n serializedTransaction = [\n ...serializedTransaction,\n numberToHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ];\n }\n else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n numberToHex(chainId),\n '0x',\n '0x',\n ];\n }\n return toRlp(serializedTransaction);\n}\nexport function toYParitySignatureArray(transaction, signature_) {\n const signature = signature_ ?? transaction;\n const { v, yParity } = signature;\n if (typeof signature.r === 'undefined')\n return [];\n if (typeof signature.s === 'undefined')\n return [];\n if (typeof v === 'undefined' && typeof yParity === 'undefined')\n return [];\n const r = trim(signature.r);\n const s = trim(signature.s);\n const yParity_ = (() => {\n if (typeof yParity === 'number')\n return yParity ? numberToHex(1) : '0x';\n if (v === 0n)\n return '0x';\n if (v === 1n)\n return numberToHex(1);\n return v === 27n ? '0x' : numberToHex(1);\n })();\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s];\n}\n//# sourceMappingURL=serializeTransaction.js.map","/**\n * Predeploy contracts for OP Stack.\n * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md\n */\nexport const contracts = {\n gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },\n l1Block: { address: '0x4200000000000000000000000000000000000015' },\n l2CrossDomainMessenger: {\n address: '0x4200000000000000000000000000000000000007',\n },\n l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },\n l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },\n l2ToL1MessagePasser: {\n address: '0x4200000000000000000000000000000000000016',\n },\n};\n//# sourceMappingURL=contracts.js.map","import { hexToBigInt } from '../utils/encoding/fromHex.js';\nimport { defineBlock } from '../utils/formatters/block.js';\nimport { defineTransaction, formatTransaction, } from '../utils/formatters/transaction.js';\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js';\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args) {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string')\n return transaction;\n const formatted = formatTransaction(transaction);\n if (formatted.typeHex === '0x7e') {\n formatted.isSystemTx = transaction.isSystemTx;\n formatted.mint = transaction.mint\n ? hexToBigInt(transaction.mint)\n : undefined;\n formatted.sourceHash = transaction.sourceHash;\n formatted.type = 'deposit';\n }\n return formatted;\n });\n return {\n transactions,\n stateRoot: args.stateRoot,\n };\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args) {\n const transaction = {};\n if (args.type === '0x7e') {\n transaction.isSystemTx = args.isSystemTx;\n transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined;\n transaction.sourceHash = args.sourceHash;\n transaction.type = 'deposit';\n }\n return transaction;\n },\n }),\n transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({\n format(args) {\n return {\n l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,\n l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,\n l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,\n l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,\n };\n },\n }),\n};\n//# sourceMappingURL=formatters.js.map","import { InvalidAddressError } from '../errors/address.js';\nimport { isAddress } from '../utils/address/isAddress.js';\nimport { concatHex } from '../utils/data/concat.js';\nimport { toHex } from '../utils/encoding/toHex.js';\nimport { toRlp } from '../utils/encoding/toRlp.js';\nimport { serializeTransaction as serializeTransaction_, } from '../utils/transaction/serializeTransaction.js';\nexport function serializeTransaction(transaction, signature) {\n if (isDeposit(transaction))\n return serializeTransactionDeposit(transaction);\n return serializeTransaction_(transaction, signature);\n}\nexport const serializers = {\n transaction: serializeTransaction,\n};\nfunction serializeTransactionDeposit(transaction) {\n assertTransactionDeposit(transaction);\n const { sourceHash, data, from, gas, isSystemTx, mint, to, value } = transaction;\n const serializedTransaction = [\n sourceHash,\n from,\n to ?? '0x',\n mint ? toHex(mint) : '0x',\n value ? toHex(value) : '0x',\n gas ? toHex(gas) : '0x',\n isSystemTx ? '0x1' : '0x',\n data ?? '0x',\n ];\n return concatHex([\n '0x7e',\n toRlp(serializedTransaction),\n ]);\n}\nfunction isDeposit(transaction) {\n if (transaction.type === 'deposit')\n return true;\n if (typeof transaction.sourceHash !== 'undefined')\n return true;\n return false;\n}\nexport function assertTransactionDeposit(transaction) {\n const { from, to } = transaction;\n if (from && !isAddress(from))\n throw new InvalidAddressError({ address: from });\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n}\n//# sourceMappingURL=serializers.js.map","import { contracts } from './contracts.js';\nimport { formatters } from './formatters.js';\nimport { serializers } from './serializers.js';\nexport const chainConfig = {\n blockTime: 2_000,\n contracts,\n formatters,\n serializers,\n};\n//# sourceMappingURL=chainConfig.js.map","import { defineChain } from '../../utils/chain/defineChain.js';\nexport const arbitrum = /*#__PURE__*/ defineChain({\n id: 42_161,\n name: 'Arbitrum One',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n blockTime: 250,\n rpcUrls: {\n default: {\n http: ['https://arb1.arbitrum.io/rpc'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Arbiscan',\n url: 'https://arbiscan.io',\n apiUrl: 'https://api.arbiscan.io/api',\n },\n },\n contracts: {\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 7654707,\n },\n },\n});\n//# sourceMappingURL=arbitrum.js.map","import { defineChain } from '../../utils/chain/defineChain.js';\nexport const avalanche = /*#__PURE__*/ defineChain({\n id: 43_114,\n name: 'Avalanche',\n blockTime: 1_700,\n nativeCurrency: {\n decimals: 18,\n name: 'Avalanche',\n symbol: 'AVAX',\n },\n rpcUrls: {\n default: { http: ['https://api.avax.network/ext/bc/C/rpc'] },\n },\n blockExplorers: {\n default: {\n name: 'SnowTrace',\n url: 'https://snowtrace.io',\n apiUrl: 'https://api.snowtrace.io',\n },\n },\n contracts: {\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 11907934,\n },\n },\n});\n//# sourceMappingURL=avalanche.js.map","import { chainConfig } from '../../op-stack/chainConfig.js';\nimport { defineChain } from '../../utils/chain/defineChain.js';\nconst sourceId = 1; // mainnet\nexport const base = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 8453,\n name: 'Base',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://basescan.org',\n apiUrl: 'https://api.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x56315b90c40730925ec5485cf004d835058518A0',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 5022,\n },\n portal: {\n [sourceId]: {\n address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',\n blockCreated: 17482143,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',\n blockCreated: 17482143,\n },\n },\n },\n sourceId,\n});\nexport const basePreconf = /*#__PURE__*/ defineChain({\n ...base,\n experimental_preconfirmationTime: 200,\n rpcUrls: {\n default: {\n http: ['https://mainnet-preconf.base.org'],\n },\n },\n});\n//# sourceMappingURL=base.js.map","import { defineChain } from '../../utils/chain/defineChain.js';\nexport const bsc = /*#__PURE__*/ defineChain({\n id: 56,\n name: 'BNB Smart Chain',\n blockTime: 750,\n nativeCurrency: {\n decimals: 18,\n name: 'BNB',\n symbol: 'BNB',\n },\n rpcUrls: {\n default: { http: ['https://56.rpc.thirdweb.com'] },\n },\n blockExplorers: {\n default: {\n name: 'BscScan',\n url: 'https://bscscan.com',\n apiUrl: 'https://api.bscscan.com/api',\n },\n },\n contracts: {\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 15921452,\n },\n },\n});\n//# sourceMappingURL=bsc.js.map","export const fees = {\n /*\n * Estimates the fees per gas for a transaction.\n \n * If the transaction is to be paid in a token (feeCurrency is present) then the fees\n * are estimated in the value of the token. Otherwise falls back to the default\n * estimation by returning null.\n *\n * @param params fee estimation function parameters\n */\n estimateFeesPerGas: async (params) => {\n if (!params.request?.feeCurrency)\n return null;\n const [gasPrice, maxPriorityFeePerGas] = await Promise.all([\n estimateFeePerGasInFeeCurrency(params.client, params.request.feeCurrency),\n estimateMaxPriorityFeePerGasInFeeCurrency(params.client, params.request.feeCurrency),\n ]);\n // eth_gasPrice for cel2 returns baseFeePerGas + maxPriorityFeePerGas\n const maxFeePerGas = params.multiply(gasPrice - maxPriorityFeePerGas) + maxPriorityFeePerGas;\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n };\n },\n};\n/*\n * Estimate the fee per gas in the value of the fee token\n\n *\n * @param client - Client to use\n * @param feeCurrency - Address of a whitelisted fee token\n * @returns The fee per gas in wei in the value of the fee token\n *\n */\nasync function estimateFeePerGasInFeeCurrency(client, feeCurrency) {\n const fee = await client.request({\n method: 'eth_gasPrice',\n params: [feeCurrency],\n });\n return BigInt(fee);\n}\n/*\n * Estimate the max priority fee per gas in the value of the fee token\n\n *\n * @param client - Client to use\n * @param feeCurrency - Address of a whitelisted fee token\n * @returns The fee per gas in wei in the value of the fee token\n *\n */\nasync function estimateMaxPriorityFeePerGasInFeeCurrency(client, feeCurrency) {\n const feesPerGas = await client.request({\n method: 'eth_maxPriorityFeePerGas',\n params: [feeCurrency],\n });\n return BigInt(feesPerGas);\n}\n//# sourceMappingURL=fees.js.map","import { trim } from '../utils/data/trim.js';\nexport function isEmpty(value) {\n return (value === 0 ||\n value === 0n ||\n value === undefined ||\n value === null ||\n value === '0' ||\n value === '' ||\n (typeof value === 'string' &&\n (trim(value).toLowerCase() === '0x' ||\n trim(value).toLowerCase() === '0x00')));\n}\nexport function isPresent(value) {\n return !isEmpty(value);\n}\n/** @internal */\nexport function isEIP1559(transaction) {\n return (typeof transaction.maxFeePerGas !== 'undefined' &&\n typeof transaction.maxPriorityFeePerGas !== 'undefined');\n}\nexport function isCIP64(transaction) {\n /*\n * Enable end user to force the tx to be considered as a CIP-64.\n *\n * The preliminary type will be determined as \"eip1559\" by src/utils/transaction/getTransactionType.ts\n * and so we need the logic below to check for the specific value instead of checking if just any\n * transaction type is provided. If that's anything else than \"cip64\" then we need to reevaluate the\n * type based on the transaction fields.\n *\n * Modify with caution and according to https://github.com/celo-org/celo-proposals/blob/master/CIPs/cip-0064.md\n */\n if (transaction.type === 'cip64') {\n return true;\n }\n return isEIP1559(transaction) && isPresent(transaction.feeCurrency);\n}\n//# sourceMappingURL=utils.js.map","import { hexToBigInt } from '../utils/encoding/fromHex.js';\nimport { defineBlock } from '../utils/formatters/block.js';\nimport { defineTransaction, formatTransaction, } from '../utils/formatters/transaction.js';\nimport { defineTransactionRequest } from '../utils/formatters/transactionRequest.js';\nimport { isCIP64 } from './utils.js';\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args) {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string')\n return transaction;\n const formatted = formatTransaction(transaction);\n return {\n ...formatted,\n ...(transaction.gatewayFee\n ? {\n gatewayFee: hexToBigInt(transaction.gatewayFee),\n gatewayFeeRecipient: transaction.gatewayFeeRecipient,\n }\n : {}),\n feeCurrency: transaction.feeCurrency,\n };\n });\n return {\n transactions,\n };\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args) {\n if (args.type === '0x7e')\n return {\n isSystemTx: args.isSystemTx,\n mint: args.mint ? hexToBigInt(args.mint) : undefined,\n sourceHash: args.sourceHash,\n type: 'deposit',\n };\n const transaction = { feeCurrency: args.feeCurrency };\n if (args.type === '0x7b')\n transaction.type = 'cip64';\n else {\n if (args.type === '0x7c')\n transaction.type = 'cip42';\n transaction.gatewayFee = args.gatewayFee\n ? hexToBigInt(args.gatewayFee)\n : null;\n transaction.gatewayFeeRecipient = args.gatewayFeeRecipient;\n }\n return transaction;\n },\n }),\n transactionRequest: /*#__PURE__*/ defineTransactionRequest({\n format(args) {\n const request = {};\n if (args.feeCurrency)\n request.feeCurrency = args.feeCurrency;\n if (isCIP64(args))\n request.type = '0x7b';\n return request;\n },\n }),\n};\n//# sourceMappingURL=formatters.js.map","import { maxUint256 } from '../constants/number.js';\nimport { InvalidAddressError } from '../errors/address.js';\nimport { BaseError } from '../errors/base.js';\nimport { InvalidChainIdError } from '../errors/chain.js';\nimport { FeeCapTooHighError, TipAboveFeeCapError } from '../errors/node.js';\nimport { serializeTransaction as serializeTransaction_op } from '../op-stack/serializers.js';\nimport { isAddress } from '../utils/address/isAddress.js';\nimport { concatHex } from '../utils/data/concat.js';\nimport { toHex } from '../utils/encoding/toHex.js';\nimport { toRlp } from '../utils/encoding/toRlp.js';\nimport { serializeAccessList } from '../utils/transaction/serializeAccessList.js';\nimport { toYParitySignatureArray } from '../utils/transaction/serializeTransaction.js';\nimport { isCIP64, isEmpty, isPresent } from './utils.js';\nexport function serializeTransaction(transaction, signature) {\n if (isCIP64(transaction))\n return serializeTransactionCIP64(transaction, signature);\n return serializeTransaction_op(transaction, signature);\n}\nexport const serializers = {\n transaction: serializeTransaction,\n};\nfunction serializeTransactionCIP64(transaction, signature) {\n assertTransactionCIP64(transaction);\n const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, feeCurrency, data, } = transaction;\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializeAccessList(accessList),\n feeCurrency,\n ...toYParitySignatureArray(transaction, signature),\n ];\n return concatHex([\n '0x7b',\n toRlp(serializedTransaction),\n ]);\n}\n// maxFeePerGas must be less than maxUint256\nconst MAX_MAX_FEE_PER_GAS = maxUint256;\nexport function assertTransactionCIP42(transaction) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to, feeCurrency, gatewayFee, gatewayFeeRecipient, } = transaction;\n if (chainId <= 0)\n throw new InvalidChainIdError({ chainId });\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n if (gasPrice)\n throw new BaseError('`gasPrice` is not a valid CIP-42 Transaction attribute.');\n if (isPresent(maxFeePerGas) && maxFeePerGas > MAX_MAX_FEE_PER_GAS)\n throw new FeeCapTooHighError({ maxFeePerGas });\n if (isPresent(maxPriorityFeePerGas) &&\n isPresent(maxFeePerGas) &&\n maxPriorityFeePerGas > maxFeePerGas)\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });\n if ((isPresent(gatewayFee) && isEmpty(gatewayFeeRecipient)) ||\n (isPresent(gatewayFeeRecipient) && isEmpty(gatewayFee))) {\n throw new BaseError('`gatewayFee` and `gatewayFeeRecipient` must be provided together.');\n }\n if (isPresent(feeCurrency) && !isAddress(feeCurrency)) {\n throw new BaseError('`feeCurrency` MUST be a token address for CIP-42 transactions.');\n }\n if (isPresent(gatewayFeeRecipient) && !isAddress(gatewayFeeRecipient)) {\n throw new InvalidAddressError(gatewayFeeRecipient);\n }\n if (isEmpty(feeCurrency) && isEmpty(gatewayFeeRecipient)) {\n throw new BaseError('Either `feeCurrency` or `gatewayFeeRecipient` must be provided for CIP-42 transactions.');\n }\n}\nexport function assertTransactionCIP64(transaction) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to, feeCurrency, } = transaction;\n if (chainId <= 0)\n throw new InvalidChainIdError({ chainId });\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n if (gasPrice)\n throw new BaseError('`gasPrice` is not a valid CIP-64 Transaction attribute.');\n if (isPresent(maxFeePerGas) && maxFeePerGas > MAX_MAX_FEE_PER_GAS)\n throw new FeeCapTooHighError({ maxFeePerGas });\n if (isPresent(maxPriorityFeePerGas) &&\n isPresent(maxFeePerGas) &&\n maxPriorityFeePerGas > maxFeePerGas)\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });\n if (isPresent(feeCurrency) && !isAddress(feeCurrency)) {\n throw new BaseError('`feeCurrency` MUST be a token address for CIP-64 transactions.');\n }\n if (isEmpty(feeCurrency)) {\n throw new BaseError('`feeCurrency` must be provided for CIP-64 transactions.');\n }\n}\n//# sourceMappingURL=serializers.js.map","import { contracts } from '../op-stack/contracts.js';\nimport { fees } from './fees.js';\nimport { formatters } from './formatters.js';\nimport { serializers } from './serializers.js';\nexport const chainConfig = {\n blockTime: 1_000,\n contracts,\n formatters,\n serializers,\n fees,\n};\n//# sourceMappingURL=chainConfig.js.map","import { chainConfig } from '../../celo/chainConfig.js';\nimport { defineChain } from '../../utils/chain/defineChain.js';\nexport const celo = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 42_220,\n name: 'Celo',\n nativeCurrency: {\n decimals: 18,\n name: 'CELO',\n symbol: 'CELO',\n },\n rpcUrls: {\n default: { http: ['https://forno.celo.org'] },\n },\n blockExplorers: {\n default: {\n name: 'Celo Explorer',\n url: 'https://celoscan.io',\n apiUrl: 'https://api.celoscan.io/api',\n },\n },\n contracts: {\n multicall3: {\n address: '0xcA11bde05977b3631167028862bE2a173976CA11',\n blockCreated: 13112599,\n },\n },\n testnet: false,\n});\n//# sourceMappingURL=celo.js.map","import { defineChain } from '../../utils/chain/defineChain.js';\nexport const mainnet = /*#__PURE__*/ defineChain({\n id: 1,\n name: 'Ethereum',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n blockTime: 12_000,\n rpcUrls: {\n default: {\n http: ['https://eth.merkle.io'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Etherscan',\n url: 'https://etherscan.io',\n apiUrl: 'https://api.etherscan.io/api',\n },\n },\n contracts: {\n ensUniversalResolver: {\n address: '0xeeeeeeee14d718c2b47d9923deab1335e144eeee',\n blockCreated: 23_085_558,\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 14_353_601,\n },\n },\n});\n//# sourceMappingURL=mainnet.js.map","import { chainConfig } from '../../op-stack/chainConfig.js';\nimport { defineChain } from '../../utils/chain/defineChain.js';\nconst sourceId = 1; // mainnet\nexport const optimism = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 10,\n name: 'OP Mainnet',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.optimism.io'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Optimism Explorer',\n url: 'https://optimistic.etherscan.io',\n apiUrl: 'https://api-optimistic.etherscan.io/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0xe5965Ab5962eDc7477C8520243A95517CD252fA9',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0xdfe97868233d1aa22e815a266982f2cf17685a27',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 4286263,\n },\n portal: {\n [sourceId]: {\n address: '0xbEb5Fc579115071764c7423A4f12eDde41f106Ed',\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x99C9fc46f92E8a1c0deC1b1747d010903E884bE1',\n },\n },\n },\n sourceId,\n});\n//# sourceMappingURL=optimism.js.map","import { defineChain } from '../../utils/chain/defineChain.js';\nexport const polygon = /*#__PURE__*/ defineChain({\n id: 137,\n name: 'Polygon',\n blockTime: 2000,\n nativeCurrency: { name: 'POL', symbol: 'POL', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://polygon-rpc.com'],\n },\n },\n blockExplorers: {\n default: {\n name: 'PolygonScan',\n url: 'https://polygonscan.com',\n apiUrl: 'https://api.polygonscan.com/api',\n },\n },\n contracts: {\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 25770160,\n },\n },\n});\n//# sourceMappingURL=polygon.js.map","// Contract utility functions for payment processing\n\n// Validate contract ABI structure\nexport const validateABI = (abi, functionName) => {\n if (!Array.isArray(abi)) {\n throw new Error('ABI must be an array');\n }\n\n const func = abi.find(item =>\n item.type === 'function' &&\n item.name === functionName\n );\n\n if (!func) {\n throw new Error(`Function ${functionName} not found in ABI`);\n }\n\n return func;\n};\n\n// Create structured parameters for tuple-based contract calls\nexport const createTupleParams = (paramDefinition, values) => {\n const tupleInputs = paramDefinition.inputs[0];\n\n if (tupleInputs.type !== 'tuple') {\n throw new Error('Expected tuple parameter definition');\n }\n\n const structuredParams = {};\n tupleInputs.components.forEach((component, index) => {\n if (values[component.name] !== undefined) {\n structuredParams[component.name] = values[component.name];\n }\n });\n\n return structuredParams;\n};\n\n// Validate BigInt conversion\nexport const validateBigInt = (value, name) => {\n try {\n const bigIntValue = BigInt(value || 0);\n if (bigIntValue < 0n) {\n throw new Error(`${name} cannot be negative`);\n }\n return bigIntValue;\n } catch (error) {\n throw new Error(`Invalid ${name}: ${error.message}`);\n }\n};\n\n// Check if contract function expects tuple parameters\nexport const usesTupleParameters = (abi, functionName) => {\n const func = validateABI(abi, functionName);\n return func.inputs.length === 1 && func.inputs[0].type === 'tuple';\n};\n\n// Validate Ethereum address format\nexport const validateAddress = (addr, name, allowZero = false) => {\n if (!addr || typeof addr !== 'string') {\n throw new Error(`Missing ${name} address`);\n }\n if (!addr.startsWith('0x')) {\n throw new Error(`Invalid ${name} address format: must start with 0x`);\n }\n if (addr.length !== 42) {\n throw new Error(`Invalid ${name} address length: expected 42 characters, got ${addr.length}`);\n }\n if (addr === '0x0000000000000000000000000000000000000000' && !allowZero) {\n throw new Error(`Invalid ${name} address: cannot be zero address`);\n }\n};\n\n// Validate contract call parameters for PaymentSplitter\nexport const validateSplitPaymentParams = (params) => {\n // Validate addresses\n validateAddress(params.token, 'token');\n validateAddress(params.recipient1, 'recipient1');\n validateAddress(params.recipient2, 'recipient2');\n\n // Allow recipient3 to be zero address if percentage is 0 (optional recipient)\n const recipient3Percentage = BigInt(params.recipient3Percentage || 0);\n const allowZeroRecipient3 = recipient3Percentage === 0n;\n validateAddress(params.recipient3, 'recipient3', allowZeroRecipient3);\n\n // Validate payment ID\n if (!params.paymentId || typeof params.paymentId !== 'string' || params.paymentId.length === 0) {\n throw new Error('Invalid payment ID: must be a non-empty string');\n }\n\n // Ensure all numeric values are valid BigInts\n let amount, percentage1, percentage2, percentage3;\n\n try {\n amount = BigInt(params.amount || 0);\n percentage1 = BigInt(params.recipient1Percentage || 0);\n percentage2 = BigInt(params.recipient2Percentage || 0);\n percentage3 = BigInt(params.recipient3Percentage || 0);\n } catch (bigIntError) {\n throw new Error('Invalid numeric values: cannot convert to BigInt');\n }\n\n if (amount <= 0n) {\n throw new Error(`Invalid amount: ${params.amount} (must be greater than 0)`);\n }\n\n const totalPercentage = percentage1 + percentage2 + percentage3;\n if (totalPercentage !== 10000n) {\n throw new Error(`Invalid percentages: total is ${totalPercentage} but must equal 10000 basis points (100%). Individual: ${percentage1}, ${percentage2}, ${percentage3}`);\n }\n\n return {\n amount,\n percentage1,\n percentage2,\n percentage3\n };\n};\n\n// Create structured parameters for PaymentSplitter contract\nexport const createSplitPaymentParams = (params) => {\n const validated = validateSplitPaymentParams(params);\n\n return {\n token: params.token,\n amount: validated.amount,\n paymentId: params.paymentId,\n recipient1: params.recipient1,\n recipient2: params.recipient2,\n recipient3: params.recipient3,\n recipient1Percentage: validated.percentage1,\n recipient2Percentage: validated.percentage2,\n recipient3Percentage: validated.percentage3\n };\n};\n\n// Helper function to categorize contract simulation errors\nexport const categorizeSimulationError = (error) => {\n if (!error.message) {\n return {\n revertReason: 'Transaction will revert',\n userFriendlyMessage: 'Transaction simulation failed'\n };\n }\n\n const errorMsg = error.message.toLowerCase();\n\n if (errorMsg.includes('abi encoding params/values length mismatch')) {\n return {\n revertReason: 'Smart contract parameter mismatch. This is likely a technical issue.',\n userFriendlyMessage: 'Technical error: Contract parameters mismatch. Please try again or contact support.'\n };\n }\n\n if (errorMsg.includes('payment id already used')) {\n return {\n revertReason: 'This payment ID has already been used.',\n userFriendlyMessage: 'This payment has already been processed. Please check your transaction history.'\n };\n }\n\n if (errorMsg.includes('percentages must equal 100')) {\n return {\n revertReason: 'Payment split percentages are incorrect.',\n userFriendlyMessage: 'Internal error: Payment split configuration is invalid. Please contact support.'\n };\n }\n\n if (errorMsg.includes('token transfer failed') || errorMsg.includes('transfer amount exceeds')) {\n return {\n revertReason: 'Insufficient token balance or approval.',\n userFriendlyMessage: 'Insufficient balance or token approval. Please check your wallet balance.'\n };\n }\n\n if (errorMsg.includes('amount must be greater than 0')) {\n return {\n revertReason: 'Payment amount is invalid.',\n userFriendlyMessage: 'Invalid payment amount. Please try again.'\n };\n }\n\n if (errorMsg.includes('invalid recipient') || errorMsg.includes('zero address')) {\n return {\n revertReason: 'One of the payment recipients has an invalid address.',\n userFriendlyMessage: 'Payment configuration error: Invalid recipient address. Please contact support.'\n };\n }\n\n if (errorMsg.includes('insufficient gas') || errorMsg.includes('out of gas')) {\n return {\n revertReason: 'Insufficient gas for transaction.',\n userFriendlyMessage: 'Not enough gas to process transaction. Please increase gas limit or check ETH balance.'\n };\n }\n\n if (errorMsg.includes('nonce')) {\n return {\n revertReason: 'Transaction nonce conflict.',\n userFriendlyMessage: 'Transaction ordering conflict. Please try again in a moment.'\n };\n }\n\n return {\n revertReason: error.message,\n userFriendlyMessage: `Transaction simulation failed: ${error.message.substring(0, 100)}${error.message.length > 100 ? '...' : ''}`\n };\n};\n\n// Standard ERC20 ABI for approve function\nexport const ERC20_APPROVE_ABI = [\n {\n constant: false,\n inputs: [\n { name: \"_spender\", type: \"address\" },\n { name: \"_value\", type: \"uint256\" }\n ],\n name: \"approve\",\n outputs: [],\n payable: false,\n stateMutability: \"nonpayable\",\n type: \"function\"\n }\n];\n\n// USDT has a different approve function signature\nexport const USDT_APPROVE_ABI = [\n {\n constant: false,\n inputs: [\n { name: \"_spender\", type: \"address\" },\n { name: \"_value\", type: \"uint256\" }\n ],\n name: \"approve\",\n outputs: [],\n payable: false,\n stateMutability: \"nonpayable\",\n type: \"function\"\n }\n];\n\n// ERC20 balance check ABI\nexport const ERC20_BALANCE_ABI = [\n {\n constant: true,\n inputs: [\n {\n name: \"_owner\",\n type: \"address\"\n }\n ],\n name: \"balanceOf\",\n outputs: [\n {\n name: \"balance\",\n type: \"uint256\"\n }\n ],\n payable: false,\n stateMutability: \"view\",\n type: \"function\"\n }\n];","// User-friendly error message utilities\n\n/**\n * Parse wallet/transaction errors into user-friendly messages\n */\nexport const parseUserFriendlyError = (error) => {\n const errorMessage = error?.message?.toLowerCase() || error?.toString()?.toLowerCase() || '';\n const errorCode = error?.code || error?.reason || '';\n\n console.log('🔍 Original error:', error);\n console.log('🔍 Error message:', errorMessage);\n console.log('🔍 Error code:', errorCode);\n\n // User rejected transaction\n if (errorMessage.includes('user rejected') ||\n errorMessage.includes('user denied') ||\n errorMessage.includes('user cancelled') ||\n errorMessage.includes('rejected by user') ||\n errorCode === 4001 ||\n errorCode === 'ACTION_REJECTED') {\n return {\n type: 'user_rejected',\n title: 'Transaction Cancelled',\n message: 'You cancelled the transaction. No charges were made.',\n suggestion: 'Click \"Pay Now\" to try again when you\\'re ready.'\n };\n }\n\n // Insufficient funds\n if (errorMessage.includes('insufficient funds') ||\n errorMessage.includes('insufficient balance') ||\n errorMessage.includes('insufficient eth') ||\n errorMessage.includes('insufficient matic') ||\n errorMessage.includes('insufficient bnb') ||\n errorCode === -32000) {\n return {\n type: 'insufficient_funds',\n title: 'Insufficient Funds',\n message: 'You don\\'t have enough tokens or gas fees in your wallet.',\n suggestion: 'Add more funds to your wallet and try again.'\n };\n }\n\n // Network/RPC errors\n if (errorMessage.includes('network error') ||\n errorMessage.includes('rpc error') ||\n errorMessage.includes('connection failed') ||\n errorMessage.includes('timeout') ||\n errorMessage.includes('request failed')) {\n return {\n type: 'network_error',\n title: 'Network Error',\n message: 'Unable to connect to the blockchain network.',\n suggestion: 'Check your internet connection and try again.'\n };\n }\n\n // Wrong network\n if (errorMessage.includes('wrong network') ||\n errorMessage.includes('unsupported network') ||\n errorMessage.includes('chain mismatch') ||\n errorCode === 4902) {\n return {\n type: 'wrong_network',\n title: 'Wrong Network',\n message: 'Please switch to the correct network in your wallet.',\n suggestion: 'Your wallet should prompt you to switch networks.'\n };\n }\n\n // Wallet not connected\n if (errorMessage.includes('wallet not connected') ||\n errorMessage.includes('no provider') ||\n errorMessage.includes('wallet disconnected') ||\n errorCode === 4900) {\n return {\n type: 'wallet_disconnected',\n title: 'Wallet Disconnected',\n message: 'Your wallet is not connected.',\n suggestion: 'Please reconnect your wallet and try again.'\n };\n }\n\n // Gas estimation failed\n if (errorMessage.includes('gas estimation failed') ||\n errorMessage.includes('execution reverted') ||\n errorMessage.includes('out of gas')) {\n return {\n type: 'gas_error',\n title: 'Transaction Failed',\n message: 'The transaction couldn\\'t be processed.',\n suggestion: 'This might be a temporary issue. Please try again.'\n };\n }\n\n // Token approval specific errors\n if (errorMessage.includes('approve') && errorMessage.includes('failed')) {\n return {\n type: 'approval_failed',\n title: 'Token Approval Failed',\n message: 'Failed to approve token spending.',\n suggestion: 'Please try the approval step again.'\n };\n }\n\n // Generic contract/transaction errors\n if (errorMessage.includes('transaction failed') ||\n errorMessage.includes('revert') ||\n errorMessage.includes('contract call failed')) {\n return {\n type: 'transaction_failed',\n title: 'Transaction Failed',\n message: 'The blockchain transaction was unsuccessful.',\n suggestion: 'Please check your wallet and try again.'\n };\n }\n\n // Wallet popup blocked\n if (errorMessage.includes('popup') ||\n errorMessage.includes('blocked')) {\n return {\n type: 'popup_blocked',\n title: 'Wallet Popup Blocked',\n message: 'Your browser blocked the wallet popup.',\n suggestion: 'Please allow popups for this site and try again.'\n };\n }\n\n // Rate limiting\n if (errorMessage.includes('rate limit') ||\n errorMessage.includes('too many requests')) {\n return {\n type: 'rate_limited',\n title: 'Too Many Requests',\n message: 'Please wait a moment before trying again.',\n suggestion: 'Wait 30 seconds and retry your transaction.'\n };\n }\n\n // Payment verification pending (not yet confirmed on blockchain)\n if (errorMessage.includes('payment not yet confirmed') ||\n errorMessage.includes('not yet confirmed on-chain') ||\n errorMessage.includes('payment not found on-chain') ||\n errorMessage.includes('please complete the payment')) {\n return {\n type: 'payment_pending',\n title: 'Payment Pending',\n message: 'Your payment is still being confirmed on the blockchain.',\n suggestion: 'Please wait a moment and try again, or check if your transaction completed successfully.'\n };\n }\n\n // Mobile wallet specific errors\n if (errorMessage.includes('deep link') ||\n errorMessage.includes('app not installed') ||\n errorMessage.includes('wallet app')) {\n return {\n type: 'mobile_wallet_error',\n title: 'Wallet App Issue',\n message: 'Unable to open or connect to your wallet app.',\n suggestion: 'Make sure your wallet app is installed and try again.'\n };\n }\n\n // Default fallback for unknown errors\n return {\n type: 'unknown_error',\n title: 'Something Went Wrong',\n message: 'An unexpected error occurred.',\n suggestion: 'Please try again or contact support if the problem persists.'\n };\n};\n\n/**\n * Get error severity level for UI styling\n */\nexport const getErrorSeverity = (errorType) => {\n switch (errorType) {\n case 'user_rejected':\n return 'info'; // Not really an error, just user choice\n\n case 'insufficient_funds':\n case 'wrong_network':\n case 'wallet_disconnected':\n case 'payment_pending':\n return 'warning'; // User can fix these\n\n case 'network_error':\n case 'gas_error':\n case 'rate_limited':\n return 'error'; // Temporary issues\n\n case 'transaction_failed':\n case 'approval_failed':\n case 'unknown_error':\n default:\n return 'critical'; // Serious issues\n }\n};\n\n/**\n * Get appropriate action button text based on error type\n */\nexport const getErrorActionText = (errorType) => {\n switch (errorType) {\n case 'user_rejected':\n return 'Try Again';\n\n case 'insufficient_funds':\n return 'Add Funds & Retry';\n\n case 'wrong_network':\n return 'Switch Network & Retry';\n\n case 'wallet_disconnected':\n return 'Reconnect Wallet';\n\n case 'payment_pending':\n return 'Check Again';\n\n case 'network_error':\n case 'rate_limited':\n return 'Retry';\n\n case 'popup_blocked':\n return 'Allow Popups & Retry';\n\n case 'mobile_wallet_error':\n return 'Open Wallet App';\n\n default:\n return 'Try Again';\n }\n};\n\n/**\n * Format error for console logging (keeps technical details for debugging)\n */\nexport const formatErrorForLogging = (error, context = '') => {\n const timestamp = new Date().toISOString();\n const userFriendly = parseUserFriendlyError(error);\n\n return {\n timestamp,\n context,\n userFriendly,\n technical: {\n message: error?.message || 'Unknown error',\n code: error?.code,\n reason: error?.reason,\n stack: error?.stack,\n name: error?.name\n }\n };\n};\n\nexport default {\n parseUserFriendlyError,\n getErrorSeverity,\n getErrorActionText,\n formatErrorForLogging\n};","import { useState, useEffect } from 'react';\nimport { useSendTransaction, useWaitForTransactionReceipt, useWriteContract, useSimulateContract } from 'wagmi';\nimport { readContract, writeContract, simulateContract, waitForTransactionReceipt, estimateFeesPerGas } from '@wagmi/core';\nimport { erc20Abi, createPublicClient, http, fallback } from 'viem';\nimport { mainnet, bsc, polygon, arbitrum, optimism, avalanche, celo, base } from 'viem/chains';\nimport { wagmiConfig } from '../config/wagmiConfig';\nimport { normalizeChainId } from '../config/chainConfig';\nimport {\n validateSplitPaymentParams,\n createSplitPaymentParams,\n categorizeSimulationError,\n ERC20_BALANCE_ABI,\n USDT_APPROVE_ABI\n} from '../utils/contractUtils';\nimport { parseUserFriendlyError, formatErrorForLogging } from '../utils/errorUtils';\n\n// 🔖 SDK VERSION TRACKING\nconst TRANSACTION_HANDLER_VERSION = '2.6.0-base-network';\nconst FIX_DATE = '2025-10-24';\nconst FIXES_APPLIED = [\n '✅ 3s RPC propagation delay after approval (Coinbase Wallet fix)',\n '✅ Allowance verification loop (3 attempts, 2s intervals)',\n '✅ Avalanche simulation bypass (JSON-RPC error workaround)',\n '✅ Ethereum simulation bypass (stale RPC state workaround)',\n '✅ 120s transaction timeout (was 60s)',\n '✅ 20% gas price buffer (FIXED: proper estimateFeesPerGas import)',\n '✅ Balance check fallback RPC (Alchemy primary, 3+ public fallbacks)',\n '✅ USDT reset handling',\n '⚡ Alchemy RPCs: ALL 8 CHAINS (ETH, BSC, MATIC, ARB, OP, AVAX, CELO, BASE) - 99.9% uptime',\n '✅ 8s backend sync delay (prevents \"payment not found\" RPC indexing lag)',\n '🆕 Base network support (Chain ID 8453, Contract: 0x6D827e60d0dC279cAa09f026d1641ECDb5704753)'\n];\nconsole.log(`%c🔖 Transaction Handler Version: ${TRANSACTION_HANDLER_VERSION}`, 'color: #00ff00; font-weight: bold; font-size: 14px;');\nconsole.log(`%c📅 Build Date: ${FIX_DATE}`, 'color: #00aaff; font-weight: bold;');\nconsole.log(`%c🛠️ Fixes Applied:`, 'color: #ffaa00; font-weight: bold;');\nFIXES_APPLIED.forEach(fix => console.log(`%c ${fix}`, 'color: #aaaaaa;'));\n\n// ⛽ Helper function to calculate gas fees with buffer for volatile networks\n// Adds 20% buffer to prevent \"max fee per gas less than block base fee\" errors\nconst getGasFeesWithBuffer = async (wagmiConfig, chainId) => {\n try {\n // Use Wagmi's estimateFeesPerGas action\n const gasPrice = await estimateFeesPerGas(wagmiConfig, { chainId });\n\n // Add 20% buffer to both maxFeePerGas and maxPriorityFeePerGas\n const GAS_BUFFER_MULTIPLIER = 120n; // 120% = 1.20x\n const MULTIPLIER_BASE = 100n;\n\n const bufferedFees = {\n maxFeePerGas: gasPrice.maxFeePerGas ? (gasPrice.maxFeePerGas * GAS_BUFFER_MULTIPLIER) / MULTIPLIER_BASE : undefined,\n maxPriorityFeePerGas: gasPrice.maxPriorityFeePerGas ? (gasPrice.maxPriorityFeePerGas * GAS_BUFFER_MULTIPLIER) / MULTIPLIER_BASE : undefined\n };\n\n console.log('⛽ Gas price with 20% buffer:', {\n original: {\n maxFeePerGas: gasPrice.maxFeePerGas?.toString(),\n maxPriorityFeePerGas: gasPrice.maxPriorityFeePerGas?.toString()\n },\n buffered: {\n maxFeePerGas: bufferedFees.maxFeePerGas?.toString(),\n maxPriorityFeePerGas: bufferedFees.maxPriorityFeePerGas?.toString()\n }\n });\n\n return bufferedFees;\n } catch (error) {\n console.warn('⚠️ Could not estimate gas with buffer, using default:', error.message);\n return {}; // Return empty object to let wagmi use defaults\n }\n};\n\n// Alchemy API configuration (same as wagmiConfig)\nconst ALCHEMY_API_KEY = 'YWG990wOlIikc1tU7-WWTepfU8d1f4dp';\n\n// Helper function to get fallback RPC client for a given chain\n// Uses app's own RPC configuration instead of wallet's RPC\n// Priority: Alchemy (primary) → Public RPCs (fallback)\nconst getFallbackRpcClient = (chainId) => {\n const chainMap = {\n 1: mainnet,\n 56: bsc,\n 137: polygon,\n 42161: arbitrum,\n 10: optimism,\n 43114: avalanche,\n 42220: celo,\n 8453: base\n };\n\n const rpcEndpoints = {\n 1: [\n `https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://cloudflare-eth.com',\n 'https://eth.llamarpc.com',\n 'https://ethereum.publicnode.com'\n ],\n 56: [\n `https://bnb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://bsc-dataseed.bnbchain.org',\n 'https://bsc-dataseed-public.bnbchain.org',\n 'https://bsc.nodereal.io'\n ],\n 137: [\n `https://polygon-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://polygon.llamarpc.com',\n 'https://polygon-rpc.com',\n 'https://polygon.drpc.org'\n ],\n 42161: [\n `https://arb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://arb1.arbitrum.io/rpc',\n 'https://arbitrum.llamarpc.com'\n ],\n 10: [\n `https://opt-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://mainnet.optimism.io',\n 'https://optimism.llamarpc.com'\n ],\n 43114: [\n `https://avax-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://api.avax.network/ext/bc/C/rpc',\n 'https://avalanche.public-rpc.com'\n ],\n 42220: [\n `https://celo-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://forno.celo.org',\n 'https://celo.drpc.org'\n ],\n 8453: [\n `https://base-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://mainnet.base.org',\n 'https://base.llamarpc.com',\n 'https://base.meowrpc.com'\n ]\n };\n\n const chain = chainMap[chainId];\n const endpoints = rpcEndpoints[chainId];\n\n if (!chain || !endpoints) {\n return null;\n }\n\n // Create fallback transport with multiple RPC endpoints (Alchemy first, then public)\n const transports = endpoints.map(url => http(url, { timeout: 10_000, retryCount: 1 }));\n\n return createPublicClient({\n chain,\n transport: fallback(transports)\n });\n};\n\nexport const useTransactionHandling = (paymentData, selectedToken, selectedNetwork, address, api, walletConnection) => {\n const [transactionStep, setTransactionStep] = useState('idle'); // idle, approve, splitPayment, processing, success, error\n const [transactionError, setTransactionError] = useState('');\n const [currentTransactionHash, setCurrentTransactionHash] = useState(null);\n\n const { data: txHash, isPending: txPending, error: txError, sendTransaction } = useSendTransaction();\n const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({\n hash: txHash,\n });\n\n // Handle two-step PaymentSplitter flow\n const executePaymentTransaction = async () => {\n if (!address || !paymentData?.contractCall) {\n throw new Error('Missing wallet connection or payment data');\n }\n\n const contractCall = paymentData.contractCall;\n\n if (!contractCall.contractAddress) {\n throw new Error('PaymentSplitter contract data missing from payment response');\n }\n\n console.log('🔍 PaymentSplitter Details:', {\n contractAddress: contractCall.contractAddress,\n tokenAddress: contractCall.tokenAddress,\n params: contractCall.params\n });\n\n // ⭐ CRITICAL: Verify and switch to correct network before starting transaction\n if (walletConnection?.ensureCorrectNetwork && selectedNetwork) {\n console.log('🔍 Verifying network before transaction...');\n const networkOk = await walletConnection.ensureCorrectNetwork(selectedNetwork);\n\n if (!networkOk) {\n console.error('❌ Network verification failed - transaction aborted');\n throw new Error('Network verification failed. Please ensure you are on the correct network.');\n }\n\n console.log('✅ Network verified - proceeding with transaction');\n }\n\n // Step 1: Check balance and approve PaymentSplitter contract\n if (selectedToken.contractAddress) {\n console.log('📝 Starting PaymentSplitter flow for ERC-20 token...');\n\n const decimals = selectedToken.decimals || 6;\n const amount = contractCall.approvalAmount || Math.floor(paymentData.totalAmount * Math.pow(10, decimals));\n\n console.log('🔍 Amount calculation debug:', {\n rawAmount: amount,\n amountType: typeof amount,\n decimals,\n totalAmount: paymentData.totalAmount,\n approvalAmount: contractCall.approvalAmount\n });\n\n // Enhanced balance check with fallback RPC\n try {\n let userBalance;\n let balanceCheckMethod = 'unknown';\n\n // Try wallet's RPC first (preferred - uses user's wallet infrastructure)\n try {\n console.log('💰 Checking balance via wallet RPC...');\n userBalance = await readContract(wagmiConfig, {\n address: contractCall.tokenAddress,\n abi: ERC20_BALANCE_ABI,\n functionName: 'balanceOf',\n args: [address]\n });\n balanceCheckMethod = 'wallet-rpc';\n console.log('✅ Balance check via wallet RPC succeeded');\n } catch (walletRpcError) {\n console.warn('⚠️ Balance check via wallet RPC failed:', {\n error: walletRpcError.message,\n isEmptyData: walletRpcError.message?.includes('returned no data') || walletRpcError.message?.includes('0x'),\n wallet: 'Using wallet-controlled RPC'\n });\n\n // Try fallback RPC (app's own multi-endpoint RPC configuration)\n const chainId = selectedNetwork?.chainId || selectedNetwork?.id;\n if (chainId) {\n // Normalize chainId to decimal (handles hex \"0xa86a\" → 43114, decimal \"43114\" → 43114, number 43114 → 43114)\n const chainIdNumber = normalizeChainId(chainId);\n\n console.log(`🔄 Attempting balance check via fallback RPC (chain ${chainId} → ${chainIdNumber})...`);\n const fallbackClient = getFallbackRpcClient(chainIdNumber);\n\n if (fallbackClient) {\n try {\n userBalance = await fallbackClient.readContract({\n address: contractCall.tokenAddress,\n abi: ERC20_BALANCE_ABI,\n functionName: 'balanceOf',\n args: [address]\n });\n balanceCheckMethod = 'fallback-rpc';\n console.log('✅ Balance check via fallback RPC succeeded');\n } catch (fallbackRpcError) {\n console.error('❌ Balance check via fallback RPC also failed:', fallbackRpcError.message);\n throw walletRpcError; // Throw original error\n }\n } else {\n console.error('❌ No fallback RPC client available for chain', chainIdNumber);\n throw walletRpcError; // Throw original error\n }\n } else {\n console.error('❌ No chainId available for fallback RPC');\n throw walletRpcError; // Throw original error\n }\n }\n\n const requiredAmount = BigInt(amount);\n\n console.log('💰 User token balance check result:', {\n balance: userBalance.toString(),\n required: requiredAmount.toString(),\n hasEnough: userBalance >= requiredAmount,\n formatted: `${(Number(userBalance) / Math.pow(10, decimals)).toFixed(6)} ${selectedToken.symbol}`,\n method: balanceCheckMethod,\n wallet: balanceCheckMethod === 'wallet-rpc' ? 'Wallet RPC (Coinbase/MetaMask infrastructure)' : 'App Fallback RPC (Multi-endpoint)'\n });\n\n if (userBalance < requiredAmount) {\n const errorMsg = `Insufficient ${selectedToken.symbol} balance. You have ${(Number(userBalance) / Math.pow(10, decimals)).toFixed(6)} ${selectedToken.symbol} but need ${(Number(requiredAmount) / Math.pow(10, decimals)).toFixed(6)} ${selectedToken.symbol}`;\n throw new Error(errorMsg);\n }\n } catch (balanceError) {\n console.error('Balance check failed:', balanceError);\n if (balanceError.message.includes('Insufficient')) {\n throw balanceError;\n }\n // Continue if balance check fails due to network issues\n console.warn('⚠️ Continuing despite balance check failure - transaction will be validated by wallet');\n }\n\n setTransactionStep('approve');\n console.log(`PaymentSplitter Step 1 - Approve Transaction:`, {\n token: selectedToken.symbol,\n spender: contractCall.contractAddress,\n amount: amount,\n to: contractCall.tokenAddress\n });\n\n // Store contract call data for step 2\n window.coinleyPendingSplitPayment = {\n contractCall,\n selectedToken,\n paymentData,\n selectedNetwork\n };\n\n // Use WAGMI writeContract for ERC20 approve\n try {\n // Special handling for USDT (non-standard ERC20)\n const isUSDT = contractCall.tokenAddress.toLowerCase() === '0xdac17f958d2ee523a2206206994597c13d831ec7' ||\n selectedToken.symbol.toUpperCase() === 'USDT';\n\n let abi = erc20Abi;\n if (isUSDT) {\n abi = USDT_APPROVE_ABI;\n }\n\n // ⭐ SMART ALLOWANCE CHECK: Skip approval if allowance is already sufficient\n // Ensure amount is a valid number or string before converting to BigInt\n let requiredAmount;\n try {\n requiredAmount = BigInt(amount);\n console.log('🔍 Converted amount to BigInt:', {\n originalAmount: amount,\n originalType: typeof amount,\n bigIntAmount: requiredAmount.toString(),\n isBigInt: typeof requiredAmount === 'bigint'\n });\n } catch (conversionError) {\n console.error('❌ Failed to convert amount to BigInt:', {\n amount,\n amountType: typeof amount,\n error: conversionError.message\n });\n throw new Error(`Invalid amount value: ${amount}`);\n }\n\n // Check current allowance for ALL tokens with retry logic (fixes fresh wallet connection issue)\n let currentAllowance = 0n;\n let allowanceCheckAttempts = 0;\n const maxAllowanceCheckAttempts = 3;\n\n while (allowanceCheckAttempts < maxAllowanceCheckAttempts) {\n try {\n currentAllowance = await readContract(wagmiConfig, {\n address: contractCall.tokenAddress,\n abi: erc20Abi,\n functionName: 'allowance',\n args: [address, contractCall.contractAddress]\n });\n\n console.log('🔍 Current allowance check:', {\n token: selectedToken.symbol,\n currentAllowance: currentAllowance.toString(),\n requiredAmount: requiredAmount.toString(),\n hasSufficient: currentAllowance >= requiredAmount,\n attempt: allowanceCheckAttempts + 1\n });\n\n // Success! Exit retry loop\n break;\n\n } catch (allowanceError) {\n allowanceCheckAttempts++;\n\n if (allowanceCheckAttempts < maxAllowanceCheckAttempts) {\n console.warn(`⚠️ Allowance check attempt ${allowanceCheckAttempts} failed, retrying in 2s...`, allowanceError.message);\n await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds before retry\n } else {\n console.warn('⚠️ Could not check allowance after 3 attempts, assuming 0 allowance:', allowanceError.message);\n currentAllowance = 0n; // Assume no allowance, will proceed with approval\n }\n }\n }\n\n // If allowance is already sufficient, skip approval entirely\n if (currentAllowance >= requiredAmount) {\n console.log('✅ Sufficient allowance already exists, skipping approval step');\n setTransactionStep('splitPayment');\n\n // Execute Step 2: Call splitPayment function directly\n const splitPaymentHash = await executeSplitPayment();\n\n // 🔒 CRITICAL FIX: Notify backend after successful transaction\n if (splitPaymentHash) {\n console.log('🔄 Notifying backend with transaction hash:', splitPaymentHash);\n await processFinalPayment(splitPaymentHash);\n }\n\n return splitPaymentHash;\n }\n\n // ⭐ USDT FIX: If changing allowance, reset to 0 first (USDT security requirement)\n if (isUSDT && currentAllowance > 0n) {\n console.log('⚠️ USDT: Changing allowance from', currentAllowance.toString(), 'to', requiredAmount.toString());\n console.log('⚠️ USDT requires reset to 0 before changing allowance...');\n\n // Get gas fees with 20% buffer\n const gasFees = await getGasFeesWithBuffer(wagmiConfig, selectedNetwork.chainId);\n\n // Step 1: Reset allowance to 0\n const resetHash = await writeContract(wagmiConfig, {\n address: contractCall.tokenAddress,\n abi: erc20Abi,\n functionName: 'approve',\n args: [contractCall.contractAddress, 0n],\n ...gasFees // ✅ FIX #2: Add 20% gas price buffer\n });\n\n console.log('🔄 USDT reset to 0 transaction sent:', resetHash);\n\n // Wait for reset confirmation\n console.log('⏳ Waiting for USDT reset confirmation (max 120s)...');\n await waitForTransactionReceipt(wagmiConfig, {\n hash: resetHash,\n confirmations: 1,\n timeout: 120_000 // 120 seconds (same as approve transaction)\n });\n\n console.log('✅ USDT allowance reset to 0 confirmed');\n }\n\n // Get gas fees with 20% buffer to prevent rejection\n const gasFees = await getGasFeesWithBuffer(wagmiConfig, selectedNetwork.chainId);\n\n // Approve the required amount\n console.log('📤 Sending approve transaction:', {\n tokenAddress: contractCall.tokenAddress,\n spenderAddress: contractCall.contractAddress,\n amount: requiredAmount.toString(),\n amountType: typeof requiredAmount,\n network: selectedNetwork?.shortName,\n wallet: address,\n gasBuffer: '20%'\n });\n\n const approveHash = await writeContract(wagmiConfig, {\n address: contractCall.tokenAddress,\n abi: erc20Abi,\n functionName: 'approve',\n args: [contractCall.contractAddress, requiredAmount],\n ...gasFees // ✅ FIX #2: Add 20% gas price buffer to prevent \"max fee < base fee\" errors\n });\n\n console.log('✅ ERC20 Approve transaction sent:', approveHash);\n setCurrentTransactionHash(approveHash);\n\n // ⭐ CRITICAL FIX: Wait for actual transaction confirmation\n // ✅ FIX #1: Increased timeout from 60s (default) to 120s\n // Reason: Wallet RPC caching can delay receipt availability by 5-15s\n // - Coinbase Wallet: Infura RPC cache (5-10s)\n // - Trust Wallet: Requires 3+ confirmations (6-15s)\n // - Avalanche: RPC indexing delay (10-15s)\n console.log('⏳ Waiting for approval confirmation on-chain (max 120s)...');\n const receipt = await waitForTransactionReceipt(wagmiConfig, {\n hash: approveHash,\n confirmations: 1,\n timeout: 120_000 // 120 seconds (2 minutes)\n });\n\n console.log('✅ Approval confirmed on-chain!', {\n blockNumber: receipt.blockNumber,\n status: receipt.status\n });\n\n // ⭐ CRITICAL FIX: Wait for RPC state propagation after approval\n // Some RPCs (especially Optimism with Coinbase Wallet) need 2-5 seconds\n // for the allowance update to propagate through their caching layer\n console.log('⏳ Waiting 3 seconds for RPC state propagation...');\n await new Promise(resolve => setTimeout(resolve, 3000));\n\n // ⭐ VERIFY ALLOWANCE: Double-check that approval actually propagated\n let verificationAttempts = 0;\n const maxVerificationAttempts = 3;\n let allowanceVerified = false;\n\n while (verificationAttempts < maxVerificationAttempts && !allowanceVerified) {\n try {\n const updatedAllowance = await readContract(wagmiConfig, {\n address: contractCall.tokenAddress,\n abi: erc20Abi,\n functionName: 'allowance',\n args: [address, contractCall.contractAddress]\n });\n\n console.log(`🔍 Allowance verification attempt ${verificationAttempts + 1}:`, {\n currentAllowance: updatedAllowance.toString(),\n requiredAmount: requiredAmount.toString(),\n verified: updatedAllowance >= requiredAmount\n });\n\n if (updatedAllowance >= requiredAmount) {\n console.log('✅ Allowance verified! Ready to proceed with splitPayment');\n allowanceVerified = true;\n break;\n }\n\n // If not verified, wait 2 more seconds and try again\n if (verificationAttempts < maxVerificationAttempts - 1) {\n console.log('⚠️ Allowance not yet propagated, waiting 2 more seconds...');\n await new Promise(resolve => setTimeout(resolve, 2000));\n }\n } catch (verifyError) {\n console.warn(`⚠️ Allowance verification attempt ${verificationAttempts + 1} failed:`, verifyError.message);\n if (verificationAttempts < maxVerificationAttempts - 1) {\n await new Promise(resolve => setTimeout(resolve, 2000));\n }\n }\n\n verificationAttempts++;\n }\n\n if (!allowanceVerified) {\n console.warn('⚠️ Could not verify allowance after 3 attempts, proceeding anyway');\n console.warn('⚠️ Transaction will fail if allowance has not propagated');\n }\n\n // Execute Step 2: Call splitPayment function\n const splitPaymentHash = await executeSplitPayment();\n\n // 🔒 CRITICAL FIX: Notify backend after successful transaction\n if (splitPaymentHash) {\n console.log('🔄 Notifying backend with transaction hash:', splitPaymentHash);\n await processFinalPayment(splitPaymentHash);\n }\n\n // Return the transaction hash so component can show success screen\n return splitPaymentHash;\n\n } catch (error) {\n console.error('❌ ERC20 Approve failed:', error);\n\n // Log full error for debugging\n const errorLog = formatErrorForLogging(error, 'approve_transaction');\n console.error('🔍 Detailed error log:', errorLog);\n\n // Parse user-friendly error\n const friendlyError = parseUserFriendlyError(error);\n setTransactionError(friendlyError);\n setTransactionStep('idle');\n\n // Check if user rejected (keep original logic)\n if (error.message?.includes('User rejected') ||\n error.message?.includes('User denied') ||\n error.code === 4001) {\n throw new Error('Transaction was cancelled by user');\n }\n\n throw new Error(`Approve failed: ${error.message}`);\n }\n } else {\n throw new Error('Native token transactions not yet supported with PaymentSplitter. Please use ERC-20 tokens.');\n }\n };\n\n // Execute Step 2: Call splitPayment function on contract\n const executeSplitPayment = async () => {\n try {\n console.log('🔄 Step 2: Executing PaymentSplitter.splitPayment()...');\n setTransactionStep('splitPayment');\n\n const pendingSplitPayment = window.coinleyPendingSplitPayment;\n if (!pendingSplitPayment) {\n throw new Error('Missing split payment data');\n }\n\n const { contractCall, selectedToken, paymentData, selectedNetwork } = pendingSplitPayment;\n\n console.log('🔍 [DEBUG] selectedNetwork object:', {\n fullObject: selectedNetwork,\n chainId: selectedNetwork?.chainId,\n shortName: selectedNetwork?.shortName,\n name: selectedNetwork?.name\n });\n\n const chainId = selectedNetwork.chainId || 10; // Default to Optimism\n console.log('🔍 [DEBUG] Resolved chainId:', chainId);\n\n // Get contract ABI from backend\n console.log('🔍 Fetching contract ABI for chain:', chainId);\n const contractInfo = await api.getContractInfo(chainId);\n const { abi } = contractInfo;\n console.log('✅ Contract ABI fetched successfully');\n\n // Create and validate parameters\n const splitPaymentParams = createSplitPaymentParams(contractCall.params);\n console.log('🔍 Structured parameters for tuple:', splitPaymentParams);\n\n // Simulate the transaction first\n console.log('🔍 Simulating transaction to check for errors...');\n const chainIdNormalized = normalizeChainId(chainId);\n const isEthereum = chainIdNormalized === 1; // Ethereum has stale RPC state issues\n const isAvalanche = chainIdNormalized === 43114; // Avalanche has JSON-RPC errors during simulation\n const shouldBypassSimulationErrors = isEthereum || isAvalanche;\n console.log('🔍 Chain detection:', {\n chainId,\n chainIdType: typeof chainId,\n chainIdNormalized,\n isEthereum,\n isAvalanche,\n networkName: selectedNetwork?.shortName,\n willBypassSimulation: shouldBypassSimulationErrors ? 'YES - Known RPC simulation issues (warnings only)' : 'NO - Will throw on simulation error'\n });\n\n try {\n const { request } = await simulateContract(wagmiConfig, {\n address: contractCall.contractAddress,\n abi: abi,\n functionName: 'splitPayment',\n args: [splitPaymentParams]\n });\n console.log('✅ Transaction simulation successful');\n } catch (simulationError) {\n console.error('❌ Transaction simulation failed:', simulationError);\n\n // Log detailed error information\n console.error('🔍 Simulation Error Details:', {\n message: simulationError.message,\n cause: simulationError.cause,\n data: simulationError.data,\n reason: simulationError.reason,\n code: simulationError.code,\n details: simulationError.details,\n shortMessage: simulationError.shortMessage,\n metaMessages: simulationError.metaMessages,\n name: simulationError.name\n });\n\n // ⭐ ADVANCED: Try to extract revert data (hex error signature)\n const errorData = simulationError.data || simulationError.cause?.data;\n if (errorData) {\n console.error('🔍 Raw Error Data (hex):', errorData);\n // Common error signatures:\n // 0x08c379a0 = Error(string)\n // 0x4e487b71 = Panic(uint256)\n if (typeof errorData === 'string' && errorData.startsWith('0x08c379a0')) {\n console.error('🔍 Error type: Error(string) - contract has custom revert message');\n } else if (typeof errorData === 'string' && errorData.startsWith('0x4e487b71')) {\n console.error('🔍 Error type: Panic - likely assert() failure or array bounds');\n } else if (errorData) {\n console.error('🔍 Error type: Custom error or unknown revert');\n }\n }\n\n // Try to extract revert reason\n const revertReason = simulationError.reason ||\n simulationError.cause?.reason ||\n simulationError.cause?.shortMessage ||\n simulationError.data?.message ||\n 'Unknown revert reason (contract may use require() without message)';\n\n console.error('🔍 Contract Revert Reason:', revertReason);\n\n // Log contract call details for debugging\n console.error('🔍 Failed Contract Call:', {\n contract: contractCall.contractAddress,\n function: 'splitPayment',\n paymentId: splitPaymentParams.paymentId,\n amount: splitPaymentParams.amount.toString(),\n token: splitPaymentParams.token\n });\n\n // ⚠️ BYPASS SIMULATION ERRORS: For chains with known RPC simulation issues\n // Other networks: Throw error immediately\n if (shouldBypassSimulationErrors) {\n const networkName = isEthereum ? 'ETHEREUM' : 'AVALANCHE';\n const reason = isEthereum\n ? 'Stale RPC state, gas estimation quirks, contract has 100% Etherscan success rate'\n : 'JSON-RPC errors during simulation (common with Avalanche RPCs), but transactions succeed on-chain';\n\n console.warn(`⚠️ [${networkName}] Simulation failed but proceeding anyway`);\n console.warn(`⚠️ [${networkName}] The wallet will catch any actual errors`);\n console.warn(`⚠️ [${networkName}] Reason: ${reason}`);\n console.warn('📤 Sending transaction to wallet for real validation...');\n } else {\n const { userFriendlyMessage } = categorizeSimulationError(simulationError);\n throw new Error(userFriendlyMessage);\n }\n }\n\n // Execute the splitPayment transaction\n console.log('📤 Sending PaymentSplitter.splitPayment transaction...');\n\n // Get gas fees with 20% buffer to prevent rejection\n const gasFees = await getGasFeesWithBuffer(wagmiConfig, chainId);\n\n // Special handling for Arbitrum + MetaMask JSON-RPC issues\n const isArbitrum = selectedNetwork.shortName === 'arbitrum';\n const maxRetries = isArbitrum ? 2 : 0;\n\n let splitPaymentHash;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n if (attempt > 0) {\n const waitTime = 2000 * attempt;\n console.log(`⏳ Retrying splitPayment on Arbitrum (attempt ${attempt + 1}) after ${waitTime}ms...`);\n await new Promise(resolve => setTimeout(resolve, waitTime));\n }\n\n splitPaymentHash = await writeContract(wagmiConfig, {\n address: contractCall.contractAddress,\n abi: abi,\n functionName: 'splitPayment',\n args: [splitPaymentParams],\n ...gasFees // ✅ FIX #2: Add 20% gas price buffer to prevent \"max fee < base fee\" errors\n });\n break; // Success, exit retry loop\n } catch (writeError) {\n console.log(`❌ WriteContract attempt ${attempt + 1} failed:`, writeError.message);\n\n const isKnownArbitrumError = writeError.message?.includes('Internal JSON-RPC error') ||\n writeError.message?.includes('-32603') ||\n writeError.message?.includes('nonce');\n\n if (attempt === maxRetries || (!isKnownArbitrumError && !isArbitrum)) {\n throw writeError; // Final attempt or not a retriable error\n }\n }\n }\n\n console.log('✅ PaymentSplitter.splitPayment transaction sent:', splitPaymentHash);\n setCurrentTransactionHash(splitPaymentHash);\n setTransactionStep('processing');\n\n // Clear pending data\n window.coinleyPendingSplitPayment = null;\n\n return splitPaymentHash;\n\n } catch (error) {\n console.error('❌ Step 2 (SplitPayment) failed:', error);\n\n // Log full error for debugging\n const errorLog = formatErrorForLogging(error, 'split_payment_transaction');\n console.error('🔍 Detailed error log:', errorLog);\n\n // Parse user-friendly error\n const friendlyError = parseUserFriendlyError(error);\n setTransactionError(friendlyError);\n setTransactionStep('error');\n throw error;\n }\n };\n\n // Process final payment completion\n const processFinalPayment = async (transactionHash) => {\n try {\n setTransactionStep('processing');\n\n console.log('🔄 Processing final payment with hash:', transactionHash);\n console.log('🔍 API instance check:', {\n hasApi: !!api,\n apiType: typeof api,\n hasProcessPaymentMethod: !!(api?.processPayment),\n paymentId: paymentData?.id,\n network: selectedNetwork?.shortName,\n address: address\n });\n\n if (!api || !api.processPayment) {\n throw new Error('API instance not available or missing processPayment method');\n }\n\n // Wait for blockchain indexers to sync the transaction\n // This prevents \"Payment not found on-chain\" errors caused by RPC lag\n console.log('⏳ Waiting 8 seconds for blockchain indexers to sync transaction...');\n await new Promise(resolve => setTimeout(resolve, 8000));\n\n console.log('📤 Calling API.processPayment...');\n const processResult = await api.processPayment(\n paymentData.id,\n transactionHash,\n selectedNetwork.shortName,\n address\n );\n\n console.log('✅ Payment processing completed:', processResult);\n setTransactionStep('success');\n\n return processResult;\n\n } catch (error) {\n console.error('❌ Final payment processing failed:', error);\n\n // Log full error for debugging\n const errorLog = formatErrorForLogging(error, 'final_payment_processing');\n console.error('🔍 Detailed error log:', errorLog);\n\n // Parse user-friendly error\n const friendlyError = parseUserFriendlyError(error);\n setTransactionError(friendlyError);\n setTransactionStep('error');\n throw error;\n }\n };\n\n const resetTransaction = () => {\n setTransactionStep('idle');\n setTransactionError('');\n setCurrentTransactionHash(null);\n window.coinleyPendingSplitPayment = null;\n };\n\n return {\n // State\n transactionStep,\n transactionError,\n currentTransactionHash,\n txPending,\n isConfirming,\n isConfirmed,\n\n // Actions\n executePaymentTransaction,\n executeSplitPayment,\n processFinalPayment,\n resetTransaction,\n setTransactionError,\n setTransactionStep\n };\n};","import React, { useState, useEffect, useRef } from 'react';\nimport ReactDOM from 'react-dom';\n\nconst ModernDropdown = ({\n options = [],\n value,\n onChange,\n placeholder,\n renderOption,\n getOptionKey,\n getOptionValue,\n getSearchableText,\n disabled = false\n}) => {\n const [isOpen, setIsOpen] = useState(false);\n const [searchTerm, setSearchTerm] = useState('');\n const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 400, maxHeight: 450 });\n const dropdownRef = useRef(null);\n const buttonRef = useRef(null);\n\n const filteredOptions = options.filter(option => {\n const searchableText = getSearchableText ? getSearchableText(option) : '';\n return searchableText.toLowerCase().includes(searchTerm.toLowerCase());\n });\n\n const selectedOption = options.find(option => getOptionValue(option) === value);\n\n const updateDropdownPosition = () => {\n if (buttonRef.current) {\n const viewportWidth = window.innerWidth;\n const viewportHeight = window.innerHeight;\n\n const dropdownWidth = Math.min(400, viewportWidth - 40);\n const dropdownHeight = Math.min(450, viewportHeight - 100);\n\n const centerX = viewportWidth / 2;\n const centerY = viewportHeight / 2;\n\n const left = centerX - (dropdownWidth / 2);\n const top = centerY - (dropdownHeight / 2);\n\n setDropdownPosition({\n top: top,\n left: left,\n width: dropdownWidth,\n maxHeight: dropdownHeight\n });\n }\n };\n\n useEffect(() => {\n const handleClickOutside = (event) => {\n if (dropdownRef.current && !dropdownRef.current.contains(event.target) &&\n buttonRef.current && !buttonRef.current.contains(event.target)) {\n setIsOpen(false);\n setSearchTerm('');\n }\n };\n\n const handleResize = () => {\n if (isOpen) {\n updateDropdownPosition();\n }\n };\n\n if (isOpen) {\n updateDropdownPosition();\n\n // Lock body scroll when dropdown is open\n const scrollY = window.scrollY;\n document.body.style.position = 'fixed';\n document.body.style.top = `-${scrollY}px`;\n document.body.style.width = '100%';\n\n document.addEventListener('mousedown', handleClickOutside);\n window.addEventListener('resize', handleResize);\n }\n\n return () => {\n // Unlock body scroll when dropdown closes\n if (isOpen) {\n const scrollY = document.body.style.top;\n document.body.style.position = '';\n document.body.style.top = '';\n document.body.style.width = '';\n window.scrollTo(0, parseInt(scrollY || '0') * -1);\n }\n\n document.removeEventListener('mousedown', handleClickOutside);\n window.removeEventListener('resize', handleResize);\n };\n }, [isOpen]);\n\n const handleToggle = () => {\n if (!disabled) {\n if (!isOpen) {\n updateDropdownPosition();\n }\n setIsOpen(!isOpen);\n }\n };\n\n const dropdownContent = isOpen && (\n <>\n <div\n className=\"fixed inset-0 bg-black bg-opacity-30 transition-opacity\"\n style={{ zIndex: 999998 }}\n onClick={() => {\n setIsOpen(false);\n setSearchTerm('');\n }}\n />\n\n <div\n ref={dropdownRef}\n className=\"fixed bg-white border-2 border-gray-200 rounded-3xl shadow-2xl overflow-hidden\"\n style={{\n top: dropdownPosition.top,\n left: dropdownPosition.left,\n width: dropdownPosition.width,\n maxHeight: dropdownPosition.maxHeight,\n zIndex: 999999,\n transform: 'translateZ(0)',\n boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(0, 0, 0, 0.05)'\n }}\n >\n <div className=\"flex items-center justify-between p-4 border-b border-gray-200 bg-gradient-to-r from-[#7042D2]/10 to-purple-50\">\n <h3 className=\"text-lg font-semibold text-[#7042D2]\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n {placeholder || 'Select Option'}\n </h3>\n <button\n onClick={() => {\n setIsOpen(false);\n setSearchTerm('');\n }}\n className=\"text-gray-500 hover:text-gray-700 transition-colors p-1 rounded-full hover:bg-gray-100\"\n >\n <svg xmlns=\"http://www.w3.org/2000/svg\" className=\"h-5 w-5\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M6 18L18 6M6 6l12 12\" />\n </svg>\n </button>\n </div>\n\n <div className=\"p-4 border-b border-gray-200 bg-gray-50\">\n <input\n type=\"text\"\n placeholder=\"Search networks and tokens...\"\n value={searchTerm}\n onChange={(e) => setSearchTerm(e.target.value)}\n 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\"\n style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}\n autoFocus\n />\n </div>\n\n <div\n className=\"overflow-y-auto custom-scrollbar\"\n style={{\n maxHeight: `${(dropdownPosition.maxHeight || 450) - 180}px`,\n minHeight: '200px'\n }}\n >\n {filteredOptions.length === 0 ? (\n <div className=\"p-8 text-gray-500 text-center\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n <div className=\"text-4xl mb-3\">🔍</div>\n <div className=\"text-lg mb-2\">No options found</div>\n <div className=\"text-sm text-gray-400\">Try a different search term</div>\n </div>\n ) : (\n <>\n <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' }}>\n <span className=\"font-semibold\">{filteredOptions.length}</span> option{filteredOptions.length !== 1 ? 's' : ''} available\n </div>\n\n <div className=\"p-2\">\n {filteredOptions.map((option) => (\n <button\n key={getOptionKey(option)}\n type=\"button\"\n onClick={() => {\n onChange(getOptionValue(option));\n setIsOpen(false);\n setSearchTerm('');\n }}\n className={`w-full p-4 text-left hover:bg-[#7042D2]/10 transition-all duration-200 rounded-xl mb-2 last:mb-0 ${getOptionValue(option) === value\n ? 'bg-[#7042D2]/20 text-[#7042D2] border-2 border-[#7042D2]/30'\n : 'text-gray-800 border-2 border-transparent hover:border-[#7042D2]/20'\n }`}\n style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}\n >\n {renderOption(option)}\n </button>\n ))}\n </div>\n </>\n )}\n </div>\n\n <div className=\"p-3 bg-gradient-to-r from-gray-50 to-gray-100 border-t border-gray-200 text-center\">\n <div className=\"text-xs text-gray-500\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n {filteredOptions.length > 5 ? '↕️ Scroll to see more options' : '✨ Select your preferred option'}\n </div>\n </div>\n </div>\n </>\n );\n\n return (\n <>\n <div className=\"relative\">\n <button\n ref={buttonRef}\n type=\"button\"\n onClick={handleToggle}\n disabled={disabled}\n 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 ${disabled ? 'opacity-50 cursor-not-allowed' : 'hover:border-[#7042D2]/50 cursor-pointer'\n } ${isOpen ? 'border-[#7042D2] ring-3 ring-[#7042D2]/20' : 'border-gray-200'}`}\n style={{\n minHeight: '60px',\n fontFamily: 'Bricolage Grotesque, sans-serif',\n fontSize: '16px',\n fontWeight: '500'\n }}\n >\n <div className=\"flex items-center justify-between\">\n <div className=\"flex items-center space-x-3\">\n {selectedOption ? renderOption(selectedOption) : (\n <span className=\"text-gray-500\">{placeholder}</span>\n )}\n </div>\n <div className={`transform transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}>\n <svg xmlns=\"http://www.w3.org/2000/svg\" className=\"h-5 w-5 text-[#7042D2]\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M19 9l-7 7-7-7\" />\n </svg>\n </div>\n </div>\n </button>\n </div>\n\n {typeof document !== 'undefined' && document.body &&\n ReactDOM.createPortal(dropdownContent, document.body)\n }\n\n <style jsx>{`\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 `}</style>\n </>\n );\n};\n\nexport default ModernDropdown;","import React, { useState, useEffect } from 'react';\n\n// Screen transition wrapper for smooth animations between payment steps\nconst ScreenTransition = ({\n currentStep,\n targetStep,\n children,\n className = \"\",\n duration = 300\n}) => {\n const [isVisible, setIsVisible] = useState(currentStep === targetStep);\n const [shouldRender, setShouldRender] = useState(currentStep === targetStep);\n\n useEffect(() => {\n if (currentStep === targetStep) {\n setShouldRender(true);\n setTimeout(() => setIsVisible(true), 10);\n } else {\n setIsVisible(false);\n setTimeout(() => setShouldRender(false), duration);\n }\n }, [currentStep, targetStep, duration]);\n\n if (!shouldRender) return null;\n\n return (\n <div\n className={`\n transition-all duration-300 ease-out\n ${isVisible\n ? 'transform translate-y-0 opacity-100'\n : 'transform translate-y-full opacity-0'\n }\n ${className}\n `}\n style={{\n transitionDuration: `${duration}ms`\n }}\n >\n {children}\n </div>\n );\n};\n\nexport default ScreenTransition;","// Formatting utilities for the payment system\n\n// Format amount to display with proper decimal places\nexport const formatAmount = (amount) => {\n return parseFloat(amount).toFixed(2);\n};\n\n// Format wallet address with ellipsis in the middle\nexport const formatWalletAddress = (address) => {\n if (!address || address.length <= 16) return address;\n return `${address.slice(0, 6)}...${address.slice(-4)}`;\n};\n\n// Format transaction hash with ellipsis in the middle\nexport const formatTransactionHash = (hash) => {\n if (!hash) return '';\n if (hash.length <= 16) return hash;\n return `${hash.slice(0, 8)}...${hash.slice(-8)}`;\n};\n\n// Format large numbers with proper separators\nexport const formatNumber = (num, decimals = 2) => {\n if (typeof num !== 'number') {\n num = parseFloat(num) || 0;\n }\n return num.toLocaleString('en-US', {\n minimumFractionDigits: decimals,\n maximumFractionDigits: decimals\n });\n};\n\n// Format percentage values\nexport const formatPercentage = (percentage, decimals = 2) => {\n return `${formatNumber(percentage, decimals)}%`;\n};\n\n// Format currency amounts with symbol\nexport const formatCurrency = (amount, symbol = 'USD', decimals = 2) => {\n const formattedAmount = formatNumber(amount, decimals);\n return symbol === 'USD' ? `$${formattedAmount}` : `${formattedAmount} ${symbol}`;\n};\n\n// Format token amounts with proper decimals based on token type\nexport const formatTokenAmount = (amount, decimals = 6, symbol = '') => {\n const divisor = Math.pow(10, decimals);\n const formattedAmount = (Number(amount) / divisor).toFixed(decimals);\n return symbol ? `${formattedAmount} ${symbol}` : formattedAmount;\n};\n\n// Format time duration (for transaction waiting times)\nexport const formatDuration = (seconds) => {\n if (seconds < 60) {\n return `${seconds} second${seconds !== 1 ? 's' : ''}`;\n }\n const minutes = Math.floor(seconds / 60);\n const remainingSeconds = seconds % 60;\n\n if (remainingSeconds === 0) {\n return `${minutes} minute${minutes !== 1 ? 's' : ''}`;\n }\n return `${minutes}m ${remainingSeconds}s`;\n};\n\n// Format gas amounts and fees\nexport const formatGas = (gasAmount, gasPrice = null) => {\n if (gasPrice) {\n const fee = (Number(gasAmount) * Number(gasPrice)) / 1e18; // Convert from wei\n return `${formatNumber(fee, 6)} ETH`;\n }\n return formatNumber(gasAmount, 0);\n};\n\n// Convert wei to ether and format\nexport const formatWeiToEther = (wei, decimals = 6) => {\n const ether = Number(wei) / 1e18;\n return formatNumber(ether, decimals);\n};\n\n// Format network names consistently\nexport const formatNetworkName = (networkName) => {\n const nameMap = {\n 'ethereum': 'Ethereum',\n 'bsc': 'BSC',\n 'polygon': 'Polygon',\n 'arbitrum': 'Arbitrum',\n 'optimism': 'Optimism',\n 'avalanche': 'Avalanche',\n 'celo': 'Celo',\n 'base': 'Base'\n };\n return nameMap[networkName?.toLowerCase()] || networkName;\n};\n\n// Format status messages for user display\nexport const formatStatusMessage = (status, details = {}) => {\n const messages = {\n pending: 'Transaction pending confirmation...',\n processing: 'Processing your payment...',\n confirming: 'Confirming on blockchain...',\n success: 'Payment completed successfully!',\n failed: 'Payment failed. Please try again.',\n cancelled: 'Payment was cancelled.',\n timeout: 'Transaction timed out. Please check your wallet.',\n insufficient_funds: 'Insufficient funds for this transaction.',\n network_error: 'Network error. Please check your connection.',\n user_rejected: 'Transaction was rejected by user.'\n };\n\n let message = messages[status] || `Status: ${status}`;\n\n // Add additional context if provided\n if (details.transactionHash) {\n message += ` (${formatTransactionHash(details.transactionHash)})`;\n }\n\n if (details.amount && details.currency) {\n message += ` Amount: ${formatCurrency(details.amount, details.currency)}`;\n }\n\n return message;\n};\n\n// Format error messages for user display\nexport const formatErrorMessage = (error) => {\n if (!error) return 'An unknown error occurred';\n\n const message = error.message || error.toString();\n\n // Clean up common error messages\n const cleanedMessage = message\n .replace(/^Error:\\s*/, '') // Remove \"Error: \" prefix\n .replace(/execution reverted:?\\s*/i, '') // Remove execution reverted\n .replace(/VM Exception while processing transaction:?\\s*/i, '') // Remove VM exception\n .trim();\n\n // Capitalize first letter\n return cleanedMessage.charAt(0).toUpperCase() + cleanedMessage.slice(1);\n};\n\n// Format validation error messages\nexport const formatValidationError = (field, value, requirement) => {\n const fieldName = field.charAt(0).toUpperCase() + field.slice(1);\n\n switch (requirement) {\n case 'required':\n return `${fieldName} is required`;\n case 'invalid_format':\n return `${fieldName} format is invalid`;\n case 'too_short':\n return `${fieldName} is too short`;\n case 'too_long':\n return `${fieldName} is too long`;\n case 'invalid_address':\n return `${fieldName} must be a valid Ethereum address`;\n case 'insufficient_balance':\n return `Insufficient ${fieldName} balance`;\n default:\n return `${fieldName} validation failed: ${requirement}`;\n }\n};\n\n// Format loading states with progress\nexport const formatLoadingMessage = (step, total = null, currentAction = null) => {\n let message = currentAction || 'Loading...';\n\n if (total && step <= total) {\n message += ` (${step}/${total})`;\n }\n\n return message;\n};\n\n// Format file sizes\nexport const formatFileSize = (bytes) => {\n if (bytes === 0) return '0 Bytes';\n\n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n};\n\n// Truncate text with ellipsis\nexport const truncateText = (text, maxLength = 50) => {\n if (!text || text.length <= maxLength) return text;\n return text.substring(0, maxLength) + '...';\n};\n\n// Format API responses for display\nexport const formatApiResponse = (response) => {\n if (!response) return 'No response';\n\n if (typeof response === 'string') return response;\n\n if (response.message) return response.message;\n if (response.error) return formatErrorMessage(response.error);\n\n return JSON.stringify(response, null, 2);\n};\n\n// Get blockchain explorer URL for transaction\nexport const getExplorerUrl = (transactionHash, network) => {\n if (!transactionHash || !network) return null;\n\n const networkName = typeof network === 'string' ? network : network.shortName || network.name;\n const normalizedNetwork = networkName?.toLowerCase();\n\n const explorerUrls = {\n 'ethereum': `https://etherscan.io/tx/${transactionHash}`,\n 'bsc': `https://bscscan.com/tx/${transactionHash}`,\n 'polygon': `https://polygonscan.com/tx/${transactionHash}`,\n 'arbitrum': `https://arbiscan.io/tx/${transactionHash}`,\n 'optimism': `https://optimistic.etherscan.io/tx/${transactionHash}`,\n 'avalanche': `https://snowtrace.io/tx/${transactionHash}`,\n 'celo': `https://celoscan.io/tx/${transactionHash}`,\n 'base': `https://basescan.org/tx/${transactionHash}`\n };\n\n return explorerUrls[normalizedNetwork] || null;\n};\n\n// Get blockchain explorer name\nexport const getExplorerName = (network) => {\n if (!network) return 'Explorer';\n\n const networkName = typeof network === 'string' ? network : network.shortName || network.name;\n const normalizedNetwork = networkName?.toLowerCase();\n\n const explorerNames = {\n 'ethereum': 'Etherscan',\n 'bsc': 'BscScan',\n 'polygon': 'PolygonScan',\n 'arbitrum': 'Arbiscan',\n 'optimism': 'Optimistic Etherscan',\n 'avalanche': 'SnowTrace',\n 'celo': 'CeloScan',\n 'base': 'BaseScan'\n };\n\n return explorerNames[normalizedNetwork] || 'Explorer';\n};","import React, { useState, useEffect } from 'react';\nimport { formatTransactionHash, getExplorerUrl, getExplorerName } from '../utils/formatUtils';\n\n// Enhanced Payment Status Component with processing step\nconst PaymentStatus = ({\n status,\n message,\n theme = 'light',\n payment = null,\n transactionHash = null,\n selectedPaymentMethod = null,\n selectedNetwork = null,\n merchantName = 'Merchant',\n onClose = null\n}) => {\n const [copiedHash, setCopiedHash] = useState(false);\n const [processingProgress, setProcessingProgress] = useState(0);\n\n // Handle processing progress animation\n useEffect(() => {\n if (status === 'processing') {\n const interval = setInterval(() => {\n setProcessingProgress(prev => {\n if (prev >= 90) return prev; // Don't go to 100% until success\n return prev + Math.random() * 15;\n });\n }, 500);\n\n return () => clearInterval(interval);\n }\n }, [status]);\n\n const copyTransactionHash = async () => {\n if (transactionHash) {\n try {\n await navigator.clipboard.writeText(transactionHash);\n setCopiedHash(true);\n setTimeout(() => setCopiedHash(false), 2000);\n } catch (err) {\n console.error('Failed to copy transaction hash:', err);\n }\n }\n };\n\n const renderIcon = () => {\n switch (status) {\n case 'processing':\n return (\n <div className=\"relative\">\n <div className=\"animate-spin rounded-full h-12 w-12 border-4 border-t-[#7042D2] border-blue-500/20\"></div>\n <div className=\"absolute inset-0 flex items-center justify-center\">\n <div className=\"w-6 h-6 bg-[#7042D2] rounded-full animate-pulse\"></div>\n </div>\n </div>\n );\n case 'success':\n return (\n <div className=\"rounded-full h-16 w-16 bg-green-500 flex items-center justify-center animate-bounce\">\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n className=\"h-10 w-10 text-white\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n strokeWidth={3}\n >\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M5 13l4 4L19 7\" />\n </svg>\n </div>\n );\n case 'error':\n return (\n <div className=\"rounded-full h-12 w-12 bg-red-100 flex items-center justify-center\">\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n className=\"h-8 w-8 text-red-500\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n strokeWidth={2}\n >\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M6 18L18 6M6 6l12 12\" />\n </svg>\n </div>\n );\n default:\n return null;\n }\n };\n\n // Enhanced processing screen\n if (status === 'processing') {\n return (\n <div className=\"flex flex-col items-center justify-center py-6 px-4\">\n <div className=\"mb-6\">{renderIcon()}</div>\n\n <h3 className=\"text-xl font-bold mb-3 text-gray-900\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Processing Payment\n </h3>\n\n <p className=\"text-center text-gray-600 mb-6\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Your transaction has been sent to the blockchain and is being processed...\n </p>\n\n {/* Progress Bar */}\n <div className=\"w-full max-w-xs mb-4\">\n <div className=\"bg-gray-200 rounded-full h-3\">\n <div\n className=\"bg-[#7042D2] h-3 rounded-full transition-all duration-500 ease-out\"\n style={{ width: `${processingProgress}%` }}\n ></div>\n </div>\n <div className=\"text-center mt-2 text-sm text-gray-500\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Processing... {Math.round(processingProgress)}%\n </div>\n </div>\n\n {/* Processing Steps */}\n <div className=\"text-center space-y-2\">\n <div className=\"flex items-center justify-center space-x-2\">\n <div className=\"w-2 h-2 bg-green-500 rounded-full animate-pulse\"></div>\n <span className=\"text-sm text-gray-600\">Transaction submitted</span>\n </div>\n <div className=\"flex items-center justify-center space-x-2\">\n <div className=\"w-2 h-2 bg-yellow-500 rounded-full animate-pulse\"></div>\n <span className=\"text-sm text-gray-600\">Confirming on blockchain...</span>\n </div>\n <div className=\"flex items-center justify-center space-x-2\">\n <div className=\"w-2 h-2 bg-gray-300 rounded-full\"></div>\n <span className=\"text-sm text-gray-400\">Finalizing payment...</span>\n </div>\n </div>\n\n <div className=\"mt-6 p-3 bg-blue-50 rounded-lg border border-blue-200\">\n <p className=\"text-xs text-blue-800 text-center\">\n Please don't close this window. This usually takes 10-30 seconds.\n </p>\n </div>\n </div>\n );\n }\n\n if (status === 'success') {\n return (\n <div className=\"flex flex-col items-center justify-center py-6 px-4\">\n <div className=\"mb-6\">{renderIcon()}</div>\n\n <h3 className=\"text-2xl font-bold mb-3 text-gray-900\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Payment Successful!\n </h3>\n\n {payment && selectedPaymentMethod && (\n <p className=\"text-center max-w-[235px] mb-6 text-gray-600\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Your payment of <span className='text-[#7042D2] font-semibold'>{payment.totalAmount || payment.amount} {selectedPaymentMethod.currency}</span> has been completed.\n </p>\n )}\n\n {transactionHash && (\n <div className=\"w-full mb-6 px-4\">\n <p className=\"text-sm font-medium mb-2 text-gray-700\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Transaction Details\n </p>\n\n {/* Transaction Hash with Copy Button */}\n <div\n 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\"\n onClick={copyTransactionHash}\n >\n <span className=\"font-mono text-sm text-gray-700\">\n {formatTransactionHash(transactionHash)}\n </span>\n <div className=\"flex items-center\">\n {copiedHash ? (\n <span className=\"text-green-500 text-xs font-medium mr-2\">Copied!</span>\n ) : null}\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n className=\"h-4 w-4 text-gray-500\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <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\" />\n </svg>\n </div>\n </div>\n\n {/* View on Explorer Button */}\n {(() => {\n const explorerUrl = getExplorerUrl(transactionHash, selectedNetwork);\n const explorerName = getExplorerName(selectedNetwork);\n\n console.log('🔍 Explorer link debug:', {\n hasSelectedNetwork: !!selectedNetwork,\n selectedNetwork,\n transactionHash,\n explorerUrl,\n explorerName,\n willShow: !!(selectedNetwork && explorerUrl)\n });\n\n return selectedNetwork && explorerUrl && (\n <a\n href={explorerUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n 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\"\n >\n <span className=\"text-sm font-medium text-[#7042D2]\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n View on {explorerName}\n </span>\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n className=\"h-4 w-4 text-[#7042D2] group-hover:translate-x-1 transition-transform\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n strokeWidth={2}\n >\n <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\" />\n </svg>\n </a>\n );\n })()}\n </div>\n )}\n\n {onClose && (\n <button\n onClick={onClose}\n className=\"w-full py-3 px-4 bg-[#7042D2] text-white font-semibold rounded-2xl text-lg shadow-md hover:bg-[#5b34b1] transition-colors\"\n style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}\n >\n Close\n </button>\n )}\n </div>\n );\n }\n\n return (\n <div className=\"flex flex-col items-center justify-center py-6\">\n <div className=\"mb-4\">{renderIcon()}</div>\n <h3 className=\"text-xl font-bold mb-2 text-gray-900\">\n {status === 'processing' ? 'Processing Payment' : status === 'error' ? 'Payment Failed' : 'Unknown Status'}\n </h3>\n <p className=\"text-center text-gray-600\">{message}</p>\n </div>\n );\n};\n\nexport default PaymentStatus;","// CoinMarketCap logo base URL\nexport const CMC_LOGO_BASE_URL = 'https://s2.coinmarketcap.com/static/img/coins/64x64';\n\n// CoinMarketCap ID mappings for cryptocurrencies\nexport const CMC_IDS = {\n bitcoin: 1,\n ethereum: 1027,\n bsc: 1839,\n polygon: 3890,\n cardano: 2010,\n avalanche: 5805,\n fantom: 3513,\n arbitrum: 11841,\n optimism: 11840,\n USDT: 825,\n USDC: 3408,\n BUSD: 4687,\n DAI: 4943,\n FRAX: 6952,\n TUSD: 2563,\n USDP: 5992,\n USDD: 5994,\n FDUSD: 26081,\n PYUSD: 28295,\n WBTC: 3717,\n LINK: 1975,\n UNI: 7083,\n AAVE: 7278,\n COMP: 5692,\n YFI: 5864,\n MKR: 1518,\n SUSHI: 6758,\n CRV: 6538,\n SNX: 2586,\n UMA: 5617,\n BAL: 5728,\n MANA: 1966,\n SAND: 6210,\n APE: 18876,\n LDO: 8000,\n GRT: 6719,\n ENS: 13855,\n RPL: 2943,\n SHIB: 5994,\n MATIC: 3890,\n BNB: 1839,\n ADA: 2010,\n SOL: 5426,\n DOT: 6636,\n AVAX: 5805,\n TRX: 1958,\n ALGO: 4030,\n FTM: 3513,\n ARB: 11841,\n OP: 11840,\n \"1INCH\": 8104,\n DYDX: 11156,\n ICP: 8916,\n FIL: 2280,\n CAKE: 7186,\n RUNE: 4157,\n ALPHA: 7232,\n BNT: 1727,\n KNC: 1982,\n ZRX: 1896,\n REN: 2539,\n LRC: 1934,\n WETH: 2396,\n WMATIC: 3890,\n WBNB: 1839,\n UST: 7129,\n USTC: 7129,\n LUSD: 8115,\n MIM: 9681,\n FEI: 8642,\n TRIBE: 8741,\n RAI: 8525,\n SUSD: 2927,\n};\n\n// Network logo URLs\nexport const NETWORK_LOGOS = {\n ethereum: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png',\n bsc: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png',\n polygon: 'https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png',\n arbitrum: 'https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png',\n avalanche: 'https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png',\n celo: 'https://s2.coinmarketcap.com/static/img/coins/64x64/5567.png',\n optimism: 'https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png',\n base: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png', // Base uses ETH logo\n eth: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png',\n bnb: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png',\n trx: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1958.png',\n algo: 'https://s2.coinmarketcap.com/static/img/coins/64x64/4030.png',\n sol: 'https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png',\n matic: 'https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png',\n arb: 'https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png',\n avax: 'https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png',\n op: 'https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png'\n};\n\n// Wallet icon mappings\nexport const WALLET_ICONS = {\n metamask: 'https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg',\n coinbase: 'https://avatars.githubusercontent.com/u/18060234?s=280&v=4',\n rabby: 'https://rabby.io/logo-128.png',\n zerion: 'https://app.zerion.io/favicon-32x32.png',\n phantom: 'https://phantom.app/favicons/apple-touch-icon.png',\n trust: 'https://trustwallet.com/favicon-196x196.png',\n okx: 'https://static.okx.com/cdn/assets/imgs/248/58E63FEA47A2B7D7.png',\n binance: 'https://bin.bnbstatic.com/static/images/common/favicon.ico',\n cryptocom: 'https://crypto.com/favicon.ico',\n hot: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIG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ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIxLjUiIHJ4PSIxIi8+CjxjaXJjbGUgY3g9IjE4IiBjeT0iMTYiIHI9IjEiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg=='\n};\n\n// Get CMC logo URL for a symbol\nexport const getCmcLogoUrl = (symbol) => {\n if (!symbol) return null;\n\n const directId = CMC_IDS[symbol.toUpperCase()];\n if (directId) {\n return `${CMC_LOGO_BASE_URL}/${directId}.png`;\n }\n\n return null;\n};\n\n// Get token logo URL\nexport const getTokenLogoUrl = (symbol) => {\n return getCmcLogoUrl(symbol);\n};\n\n// Get network logo URL - Prioritize API logo over hardcoded fallback\nexport const getNetworkLogoUrl = (networkOrShortName) => {\n // If passed a full network object with logo field from API, use it\n if (typeof networkOrShortName === 'object' && networkOrShortName?.logo) {\n return networkOrShortName.logo;\n }\n\n // If passed a network object with shortName, try hardcoded fallback\n if (typeof networkOrShortName === 'object' && networkOrShortName?.shortName) {\n return NETWORK_LOGOS[networkOrShortName.shortName.toLowerCase()];\n }\n\n // If passed a string (shortName), use hardcoded fallback\n if (typeof networkOrShortName === 'string') {\n return NETWORK_LOGOS[networkOrShortName.toLowerCase()];\n }\n\n return null;\n};\n\n// Get wallet icon URL\nexport const getWalletIcon = (connectorName, connectorId) => {\n const name = connectorName.toLowerCase();\n const id = connectorId.toLowerCase();\n\n // Check for specific wallet matches\n for (const [key, icon] of Object.entries(WALLET_ICONS)) {\n if (name.includes(key) || id.includes(key)) {\n return icon;\n }\n }\n\n return WALLET_ICONS.default;\n};","import { getWalletIcon } from '../config/logoConfig';\nimport { getTrustChainId } from '../config/chainConfig';\n\n// Mobile detection utility\nexport const detectMobile = () => {\n return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);\n};\n\n// Helper function to check if a wallet is detected in the browser\nexport const isWalletDetected = (walletType) => {\n switch (walletType) {\n case 'trust':\n return window.ethereum && window.ethereum.isTrust === true;\n case 'metaMask':\n return window.ethereum && window.ethereum.isMetaMask === true;\n case 'injected':\n return window.ethereum && !window.ethereum.isMetaMask && !window.ethereum.isCoinbaseWallet;\n default:\n return false;\n }\n};\n\n// Convert Wagmi connectors to our wallet format\nexport const createWalletFromConnector = (connector, selectedNetwork) => {\n return {\n type: connector.id,\n name: connector.name,\n icon: getWalletIcon(connector.name, connector.id),\n description: `Connect using ${connector.name}`,\n isInstalled: true,\n connector: connector,\n isWagmi: true\n };\n};\n\n// Create custom mobile wallets that aren't covered by wagmi\nexport const getCustomMobileWallets = () => {\n return [\n {\n type: 'trust',\n name: 'Trust Wallet',\n icon: '🛡️',\n description: 'Multi-chain wallet with transaction deep links',\n isInstalled: false,\n connector: null,\n isWagmi: false,\n mobileOnly: true,\n hasTransactionDeepLinks: true\n }\n ];\n};\n\n// Get available wallets based on device and network\nexport const getAvailableWallets = (connectors, selectedNetwork) => {\n console.log('🔍 getAvailableWallets called with:', {\n connectorCount: connectors?.length,\n connectorNames: connectors?.map(c => c.name),\n selectedNetwork: selectedNetwork?.shortName\n });\n\n if (!selectedNetwork) {\n console.warn('⚠️ No network selected');\n return [];\n }\n\n // Check if network is EVM-compatible\n const evmNetworks = ['ethereum', 'bsc', 'polygon', 'arbitrum', 'optimism', 'avalanche', 'celo', 'base'];\n if (!evmNetworks.includes(selectedNetwork.shortName)) {\n console.warn('⚠️ Network not in EVM list:', selectedNetwork.shortName);\n return [];\n }\n\n // Map all connectors (they all support EVM chains)\n const wagmiWallets = (connectors || []).map(connector =>\n createWalletFromConnector(connector, selectedNetwork)\n );\n\n console.log('✅ Wagmi wallets created:', wagmiWallets.map(w => w.name));\n\n const isMobile = detectMobile();\n const customMobileWallets = isMobile ? getCustomMobileWallets() : [];\n\n const allWallets = [...wagmiWallets, ...customMobileWallets];\n console.log('📋 Total available wallets:', allWallets.length);\n\n return allWallets;\n};\n\n// Get wallet store URLs for mobile app downloads\nexport const getWalletStoreUrl = (walletType, platform) => {\n const storeUrls = {\n trust: {\n ios: 'https://apps.apple.com/app/trust-crypto-bitcoin-wallet/id1288339409',\n android: 'https://play.google.com/store/apps/details?id=com.wallet.crypto.trustapp'\n }\n };\n\n return storeUrls[walletType]?.[platform] || storeUrls.trust[platform];\n};\n\n// Helper function to attempt app opening with proper fallback detection\nexport const attemptAppOpen = (deepLink, storeUrls) => {\n return new Promise((resolve) => {\n let appOpened = false;\n let fallbackTimeout;\n\n // Detect if the user navigates away from the page (app opened)\n const handleVisibilityChange = () => {\n if (document.hidden) {\n appOpened = true;\n clearTimeout(fallbackTimeout);\n cleanup();\n resolve(true);\n }\n };\n\n // Detect if the user focuses back after some time (might indicate app was opened)\n const handleFocus = () => {\n // Give a small delay to see if app actually opened\n setTimeout(() => {\n if (!appOpened) {\n appOpened = true;\n clearTimeout(fallbackTimeout);\n cleanup();\n resolve(true);\n }\n }, 100);\n };\n\n const cleanup = () => {\n document.removeEventListener('visibilitychange', handleVisibilityChange);\n window.removeEventListener('focus', handleFocus);\n };\n\n // Set up listeners\n document.addEventListener('visibilitychange', handleVisibilityChange);\n window.addEventListener('focus', handleFocus);\n\n // Try to open the app\n window.location.href = deepLink;\n\n // Fallback to app store if app doesn't open within 3 seconds\n fallbackTimeout = setTimeout(() => {\n if (!appOpened) {\n cleanup();\n\n // Only redirect to store if we're confident the app didn't open\n const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);\n const storeUrl = isIOS ? storeUrls.ios : storeUrls.android;\n\n console.log(`App didn't open, redirecting to: ${storeUrl}`);\n window.location.href = storeUrl;\n resolve(false);\n }\n }, 3000); // Increased to 3 seconds\n });\n};\n\n// Generate session ID for transaction tracking\nexport const generateSessionId = () => {\n return Math.random().toString(36).substring(2, 15) + Date.now().toString(36);\n};\n\n// Store session data for mobile transaction tracking\nexport const storeTransactionSession = (sessionId, sessionData) => {\n localStorage.setItem(`tx_session_${sessionId}`, JSON.stringify(sessionData));\n};\n\n// Retrieve session data for mobile transaction tracking\nexport const getTransactionSession = (sessionId) => {\n const sessionData = localStorage.getItem(`tx_session_${sessionId}`);\n return sessionData ? JSON.parse(sessionData) : null;\n};\n\n// Clear session data for mobile transaction tracking\nexport const clearTransactionSession = (sessionId) => {\n localStorage.removeItem(`tx_session_${sessionId}`);\n};\n\n// Handle transaction callback when user returns from wallet\nexport const handleTransactionCallback = () => {\n const urlParams = new URLSearchParams(window.location.search);\n const txCallback = urlParams.get('tx_callback');\n const sessionId = urlParams.get('sessionId');\n const txHash = urlParams.get('hash');\n const txError = urlParams.get('error');\n\n if (txCallback && sessionId) {\n const sessionData = getTransactionSession(sessionId);\n if (sessionData) {\n clearTransactionSession(sessionId);\n\n // Clean up URL parameters\n const cleanUrl = window.location.origin + window.location.pathname;\n window.history.replaceState({}, document.title, cleanUrl);\n\n return {\n sessionData,\n txHash,\n txError,\n success: !!(txHash && !txError)\n };\n }\n }\n\n return null;\n};","import { getTrustChainId, getChainId } from '../config/chainConfig';\nimport { generateSessionId, storeTransactionSession, clearTransactionSession, getTransactionSession } from './walletUtils';\n\n// Helper function to map chain IDs to Trust Wallet coin IDs\n// IMPORTANT: Trust Wallet's DApp browser (open_url) uses coin_id=60 for ALL EVM chains\n// because they all use the same Ethereum-compatible Web3 provider.\n// Network switching happens AFTER the DApp browser opens via the injected provider.\nconst getCoinIdForChain = (chainId) => {\n // Handle hex chainId (e.g., \"0x89\" for Polygon)\n const normalizedChainId = typeof chainId === 'string' && chainId.startsWith('0x')\n ? parseInt(chainId, 16)\n : parseInt(chainId);\n\n // For Trust Wallet DApp browser, ALL EVM chains use coin_id=60\n // This ensures the DApp browser opens correctly\n const evmChains = [1, 56, 137, 42161, 10, 43114, 42220, 8453]; // Ethereum, BSC, Polygon, Arbitrum, Optimism, Avalanche, Celo, Base\n\n if (evmChains.includes(normalizedChainId)) {\n console.log(`🔍 EVM Chain ${chainId} (normalized: ${normalizedChainId}) -> coin_id: 60 (Trust Wallet DApp browser uses Ethereum mode for all EVM chains)`);\n return 60;\n }\n\n // For non-EVM chains, use specific coin_ids (future use)\n const chainToCoinId = {\n // Non-EVM chains would go here\n };\n\n const coinId = chainToCoinId[normalizedChainId] || 60;\n console.log(`🔍 Chain ${chainId} (normalized: ${normalizedChainId}) -> coin_id: ${coinId}`);\n return coinId;\n};\n\n// Simple QR Payment URI generation - NO COMPLEX VALIDATION\nexport const generateQRPaymentURI = (paymentData, selectedToken, selectedNetwork, config, preferredWallet = 'metamask', apiConfig = null) => {\n if (!paymentData) return null;\n\n try {\n const baseUrl = 'https://paymentscreen.vercel.app';\n\n console.log('🔍 SIMPLE Payment data for QR generation:', {\n paymentData,\n selectedToken,\n selectedNetwork,\n config,\n preferredWallet\n });\n\n // ⭐ OPTIMIZED: Minimal params - payment screen fetches rest from backend\n const params = new URLSearchParams();\n\n // ⭐ ONLY ESSENTIAL PARAMETERS (rest fetched from backend using paymentId)\n const paymentId = paymentData?.id || paymentData?.splitterPaymentId;\n if (!paymentId) {\n console.error('❌ Cannot generate QR: No payment ID');\n return null;\n }\n params.set('paymentId', paymentId);\n\n // Preferred wallet for deep link (essential for UX)\n params.set('preferredWallet', preferredWallet);\n\n // Mobile flag (helps payment screen optimize UI)\n params.set('isMobile', 'true');\n\n const paymentScreenUrl = `${baseUrl}?${params.toString()}`;\n\n console.log('🔗 SIMPLE Generated payment URL:', paymentScreenUrl);\n console.log('🔍 SIMPLE URL Parameters:', Object.fromEntries(params.entries()));\n\n // Generate wallet-specific deep link that opens the payment screen in wallet browser\n let deepLinkUrl;\n\n switch (preferredWallet) {\n case 'metamask':\n const metaMaskUrl = paymentScreenUrl.replace('https://', '');\n deepLinkUrl = `https://metamask.app.link/dapp/${metaMaskUrl}`;\n console.log('🦊 Generated MetaMask deep link for QR');\n break;\n\n case 'trust':\n // ⭐ CRITICAL FIX: Trust Wallet requires 'coin_id' parameter for proper DApp browser mode\n // Format: https://link.trustwallet.com/open_url?coin_id=60&url=ENCODED_URL\n // coin_id=60 is Ethereum (standard for all EVM chains in Trust Wallet)\n const chainIdForCoin = selectedNetwork?.chainId || 1;\n const coinId = getCoinIdForChain(chainIdForCoin); // Default to 60 (Ethereum) for EVM chains\n deepLinkUrl = `https://link.trustwallet.com/open_url?coin_id=${coinId}&url=${encodeURIComponent(paymentScreenUrl)}`;\n console.log('🛡️ Generated Trust Wallet deep link for QR with coin_id:', coinId);\n break;\n\n case 'coinbase':\n deepLinkUrl = `https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(paymentScreenUrl)}`;\n console.log('💙 Generated Coinbase Wallet deep link for QR');\n break;\n\n default:\n // Direct payment screen URL for other wallets\n deepLinkUrl = paymentScreenUrl;\n console.log('🔗 Using direct payment screen URL');\n }\n\n return deepLinkUrl;\n\n } catch (error) {\n console.error('❌ Error generating QR payment URI:', error);\n return null;\n }\n};\n\n// Helper function to get display name for networks\nconst getNetworkDisplayName = (shortName) => {\n const networkNames = {\n 'ethereum': 'Ethereum Mainnet',\n 'bsc': 'BSC',\n 'polygon': 'Polygon',\n 'arbitrum': 'Arbitrum One',\n 'optimism': 'Optimism',\n 'avalanche': 'Avalanche',\n 'celo': 'Celo',\n 'base': 'Base'\n };\n return networkNames[shortName] || shortName;\n};\n\n// Keep other necessary functions from original file\nexport const generateMobilePaymentDeepLink = (walletType, paymentUri) => {\n if (!paymentUri) return null;\n\n try {\n console.log(`🔗 Generating ${walletType} deep link for: ${paymentUri}`);\n\n switch (walletType) {\n case 'metamask':\n const metaMaskUrl = paymentUri.includes('metamask.app.link')\n ? paymentUri\n : `https://metamask.app.link/dapp/${paymentUri.replace('https://', '')}`;\n return metaMaskUrl;\n\n case 'trust':\n // ⭐ CRITICAL: Add coin_id parameter for proper DApp browser activation\n const trustUrl = paymentUri.includes('link.trustwallet.com')\n ? paymentUri\n : `https://link.trustwallet.com/open_url?coin_id=60&url=${encodeURIComponent(paymentUri)}`;\n return trustUrl;\n\n case 'coinbase':\n const coinbaseUrl = paymentUri.includes('go.cb-w.com')\n ? paymentUri\n : `https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(paymentUri)}`;\n return coinbaseUrl;\n\n default:\n return paymentUri;\n }\n } catch (error) {\n console.error(`❌ Error generating ${walletType} deep link:`, error);\n return paymentUri;\n }\n};","import React, { useState, useEffect, useRef } from 'react';\nimport QRCode from 'qrcode';\nimport { detectMobile } from '../utils/walletUtils';\nimport { getTokenInfo, getChainId } from '../config/chainConfig';\nimport { formatWalletAddress } from '../utils/formatUtils';\nimport { generateQRPaymentURI } from '../utils/deepLinkUtils';\n\nconst QRCodeDisplay = ({\n walletAddress,\n amount,\n currency,\n network,\n theme = 'light',\n paymentData = null,\n onPaymentDetected = null,\n config = null,\n selectedToken = null,\n selectedNetwork = null,\n preferredWallet = 'metamask', // Default to MetaMask for best compatibility\n compact = false\n}) => {\n const [qrData, setQrData] = useState('');\n const [qrCodeImage, setQrCodeImage] = useState('');\n const [isGenerating, setIsGenerating] = useState(true);\n const [monitoringPayment, setMonitoringPayment] = useState(false);\n const [transactionDetected, setTransactionDetected] = useState(false);\n\n const monitoringInterval = useRef(null);\n\n useEffect(() => {\n const generateQRCode = async () => {\n if (!paymentData?.id) {\n console.warn('⚠️ No payment data provided for QR code');\n setIsGenerating(false);\n return;\n }\n\n setIsGenerating(true);\n\n try {\n // 🔧 CRITICAL FIX: Use complete objects instead of fallbacks\n // Ensure we have complete selectedToken and selectedNetwork objects\n if (!selectedToken || !selectedToken.contractAddress) {\n console.error('❌ QR Code Error: selectedToken missing or incomplete:', selectedToken);\n throw new Error('Cannot generate QR code: Token contract address required');\n }\n\n if (!selectedNetwork || !selectedNetwork.chainId) {\n console.error('❌ QR Code Error: selectedNetwork missing or incomplete:', selectedNetwork);\n throw new Error('Cannot generate QR code: Network chain ID required');\n }\n\n // Generate Coinley payment URL with wallet deep link for smart QR system\n const paymentUri = generateQRPaymentURI(\n paymentData,\n selectedToken, // ✅ Use complete token object\n selectedNetwork, // ✅ Use complete network object\n config, // ✅ Use complete config object\n preferredWallet // Pass the preferred wallet for deep link generation\n );\n\n console.log('🔍 QR Code Regenerating with:');\n console.log(' - Payment ID:', paymentData.id);\n console.log(' - Network:', network, 'Currency:', currency, 'Amount:', amount);\n console.log(' - Preferred Wallet:', preferredWallet);\n console.log('🔍 COMPLETE QR PAYMENT DATA CHECK:');\n console.log(' - paymentData object:', JSON.stringify(paymentData, null, 2));\n console.log(' - selectedToken object:', JSON.stringify(selectedToken, null, 2));\n console.log(' - selectedNetwork object:', JSON.stringify(selectedNetwork, null, 2));\n console.log(' - config object:', JSON.stringify(config, null, 2));\n console.log('🔗 Generated Coinley deep link URL:', paymentUri);\n\n // Check if the deep link actually contains the wallet-specific URL\n if (paymentUri.includes('metamask.app.link')) {\n console.log('✅ QR contains MetaMask deep link');\n } else if (paymentUri.includes('link.trustwallet.com')) {\n console.log('✅ QR contains Trust Wallet deep link');\n } else if (paymentUri.includes('go.cb-w.com')) {\n console.log('✅ QR contains Coinbase Wallet deep link');\n } else {\n console.log('⚠️ QR contains generic deep link (no wallet-specific wrapper)');\n }\n\n if (!paymentUri) {\n throw new Error('Failed to generate Coinley payment URL');\n }\n\n setQrData(paymentUri);\n\n // Generate actual QR code image - OPTIMIZED FOR COMPACT DISPLAY\n const isMobile = detectMobile();\n const qrImage = await QRCode.toDataURL(paymentUri, {\n width: compact ? 140 : (isMobile ? 350 : 280), // ⭐ COMPACT: 140px for side-by-side layout\n margin: 2, // ⭐ Minimal margin for compact display\n errorCorrectionLevel: 'M', // ⭐ MEDIUM (15%) - good balance for reliability\n color: {\n dark: theme === 'dark' ? '#FFFFFF' : '#000000',\n light: theme === 'dark' ? '#000000' : '#FFFFFF'\n }\n });\n\n setQrCodeImage(qrImage);\n setIsGenerating(false);\n\n console.log('✅ QR Code regenerated with', preferredWallet, 'deep link');\n\n } catch (error) {\n console.error('❌ Failed to generate QR code:', error);\n setIsGenerating(false);\n }\n };\n\n generateQRCode();\n\n // ❌ MONITORING DISABLED - Requires backend blockchain monitoring implementation\n // if (paymentData && !monitoringPayment) {\n // startTransactionMonitoring();\n // }\n }, [paymentData, amount, currency, network, theme, selectedToken, selectedNetwork, config, preferredWallet]);\n\n // Cleanup monitoring on unmount\n useEffect(() => {\n return () => {\n if (monitoringInterval.current) {\n clearInterval(monitoringInterval.current);\n }\n };\n }, []);\n\n const startTransactionMonitoring = async () => {\n if (!paymentData || monitoringPayment) return;\n\n setMonitoringPayment(true);\n console.log('🔍 Starting QR payment monitoring...', {\n paymentId: paymentData.id,\n recipient: walletAddress,\n amount: amount,\n currency: currency\n });\n\n // Monitor transactions every 10 seconds\n monitoringInterval.current = setInterval(async () => {\n try {\n await checkForTransaction();\n } catch (error) {\n console.error('❌ Error monitoring transaction:', error);\n }\n }, 10000);\n\n // Also check immediately\n setTimeout(checkForTransaction, 2000);\n };\n\n const checkForTransaction = async () => {\n if (!paymentData || transactionDetected) return;\n\n try {\n console.log('🔍 Checking for QR payment transaction...');\n\n // ❌ REMOVE THIS - POLLING NOT IMPLEMENTED YET\n // This would require backend blockchain monitoring\n console.log('⚠️ QR payment monitoring disabled - requires backend implementation');\n return;\n\n } catch (error) {\n console.error('❌ Error checking for QR payment:', error);\n }\n };\n\n return (\n <div className=\"flex flex-col items-center\">\n {/* ✅ ULTRA-COMPACT: Side-by-side QR + Info layout to save vertical space */}\n <div className=\"flex gap-3 items-start w-full mb-2\">\n {/* QR Code - Smaller size */}\n <div className=\"p-1.5 rounded-lg bg-white shadow-sm border flex-shrink-0\">\n {isGenerating ? (\n <div className=\"flex items-center justify-center\" style={{ width: 140, height: 140 }}>\n <div className=\"text-center\">\n <div className=\"animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600 mx-auto mb-1\"></div>\n <div className=\"text-xs text-gray-600\">Generating...</div>\n </div>\n </div>\n ) : (\n qrCodeImage ? (\n <img\n src={qrCodeImage}\n alt=\"Payment QR Code\"\n className=\"rounded-lg\"\n style={{ width: 140, height: 140 }}\n />\n ) : (\n <div className=\"flex items-center justify-center bg-gray-100 rounded-lg\" style={{ width: 140, height: 140 }}>\n <div className=\"text-center p-2\">\n <div className=\"text-lg mb-1\">⚠️</div>\n <div className=\"text-xs text-gray-600\">\n {!paymentData?.id ? 'Payment not created' : 'QR Failed'}\n </div>\n </div>\n </div>\n )\n )}\n </div>\n\n {/* Payment Info - Beside QR code */}\n <div className=\"flex-1 flex flex-col justify-center\">\n <div className=\"p-2 bg-gray-50 rounded-lg mb-2\">\n <div className=\"flex justify-between items-center mb-1\">\n <span className=\"text-xs font-medium text-gray-600\">Amount:</span>\n <span className=\"text-sm font-bold text-[#7042D2]\">{amount} {currency}</span>\n </div>\n <div className=\"flex justify-between items-center\">\n <span className=\"text-xs text-gray-500\">Network:</span>\n <span className=\"text-xs font-medium text-gray-700\">{network}</span>\n </div>\n </div>\n\n {/* Status/Instruction */}\n {transactionDetected ? (\n <div className=\"flex items-center justify-center text-xs font-semibold text-green-600 p-1.5 bg-green-50 rounded-lg\">\n <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\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M5 13l4 4L19 7\" />\n </svg>\n Payment Received!\n </div>\n ) : (\n <div className=\"p-1.5 rounded-lg bg-blue-50 border border-blue-200\">\n <p className=\"text-xs text-blue-700 text-center leading-tight\">\n 📱 Scan with phone camera\n </p>\n </div>\n )}\n </div>\n </div>\n </div>\n );\n};\n\nexport default QRCodeDisplay;","import React, { useState } from 'react';\nimport { useConnect, useAccount } from 'wagmi';\nimport ModernDropdown from './ModernDropdown';\nimport { detectMobile } from '../utils/walletUtils';\nimport {\n getAvailableWallets,\n isWalletDetected,\n handleTransactionCallback\n} from '../utils/walletUtils';\nimport { getWalletIcon } from '../config/logoConfig';\n\nconst WalletSelector = ({\n selectedNetwork,\n onWalletSelect,\n onConnect,\n connectedWallet,\n loading,\n paymentData = null,\n selectedToken = null,\n api = null\n}) => {\n const [selectedWalletType, setSelectedWalletType] = useState(null);\n\n // Use Wagmi's built-in connector detection\n const { connectors } = useConnect();\n const { isConnected, address } = useAccount();\n\n // Get available wallets based on device and network\n const availableWallets = getAvailableWallets(connectors, selectedNetwork);\n\n console.log('🔍 WAGMI: Available connectors:', availableWallets.map(w => w.name));\n\n const handleWalletSelection = async (walletType) => {\n setSelectedWalletType(walletType);\n const wallet = availableWallets.find(w => w.type === walletType);\n\n if (wallet) {\n onWalletSelect(walletType);\n\n if (wallet.isWagmi && wallet.connector) {\n // Standard wagmi connector\n await onConnect(wallet.connector);\n } else if (!wallet.isWagmi) {\n // Custom mobile wallet - handle with deep linking\n await handleCustomWalletConnection(wallet, walletType);\n }\n }\n };\n\n const handleCustomWalletConnection = async (wallet, walletType) => {\n const isMobile = detectMobile();\n\n if (!isMobile) {\n // Desktop: Show download instructions\n alert(`Please install ${wallet.name} mobile app or use the browser extension if available.`);\n return;\n }\n\n // For mobile wallets, we need payment data to create deep links\n if (!paymentData) {\n alert('Please create a payment first before selecting a mobile wallet.');\n return;\n }\n\n try {\n console.log(`🚀 Opening mobile wallet: ${wallet.name}`);\n\n // Import deep link utilities\n const { generateQRPaymentURI, generateMobilePaymentDeepLink } = await import('../utils/deepLinkUtils');\n\n // Generate payment URL\n const paymentUri = generateQRPaymentURI(\n paymentData,\n selectedToken,\n selectedNetwork,\n api?.config || {},\n walletType\n );\n\n if (!paymentUri) {\n throw new Error('Failed to generate payment URL');\n }\n\n // Generate mobile deep link\n const mobileDeepLink = generateMobilePaymentDeepLink(walletType, paymentUri);\n\n if (!mobileDeepLink) {\n throw new Error(`Failed to generate ${wallet.name} deep link`);\n }\n\n console.log(`🔗 Opening ${wallet.name} with:`, mobileDeepLink);\n\n // Open wallet app\n window.location.href = mobileDeepLink;\n\n } catch (error) {\n console.error(`❌ Mobile wallet connection failed:`, error);\n alert(`Failed to open ${wallet.name}: ${error.message}`);\n }\n };\n\n // Render wallet option for dropdown\n const renderWalletOption = (wallet) => {\n return (\n <div className=\"flex items-center space-x-3\">\n <div className=\"w-8 h-8 flex items-center justify-center\">\n {wallet.icon.startsWith('http') || wallet.icon.startsWith('data:') ? (\n <img\n src={wallet.icon}\n alt={wallet.name}\n className=\"w-6 h-6 rounded-full object-contain\"\n onError={(e) => {\n e.target.style.display = 'none';\n e.target.nextSibling.style.display = 'block';\n }}\n />\n ) : (\n <div className=\"text-2xl\">{wallet.icon}</div>\n )}\n <div className=\"text-xl\" style={{display: 'none'}}>🔗</div>\n </div>\n <div className=\"flex-1\">\n <div className=\"font-semibold text-gray-800 flex items-center\">\n {wallet.name}\n {isWalletDetected(wallet.type) && (\n <span className=\"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full\">\n DETECTED\n </span>\n )}\n {connectedWallet?.walletType === wallet.type && (\n <span className=\"ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full\">\n CONNECTED\n </span>\n )}\n </div>\n <div className=\"text-sm text-gray-500\">\n {connectedWallet?.walletType === wallet.type\n ? `Connected • ${connectedWallet.account?.slice(0, 6)}...${connectedWallet.account?.slice(-4)}`\n : wallet.description\n }\n </div>\n </div>\n {loading && selectedWalletType === wallet.type && (\n <div className=\"animate-spin rounded-full h-5 w-5 border-b-2 border-[#7042D2]\"></div>\n )}\n </div>\n );\n };\n\n if (!selectedNetwork) {\n return (\n <div className=\"text-center p-4\">\n <p className=\"text-gray-500\">Please select a network first</p>\n </div>\n );\n }\n\n if (availableWallets.length === 0) {\n return (\n <div className=\"text-center p-4\">\n <p className=\"text-gray-500 mb-4\">No compatible wallets found for {selectedNetwork.name}</p>\n <div className=\"p-3 bg-amber-50 rounded-lg border border-amber-200\">\n <div className=\"text-sm text-amber-800\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n <div className=\"font-medium mb-2\">Install a compatible wallet:</div>\n <div className=\"space-y-1 text-xs\">\n <div>• <a href=\"https://metamask.io/download/\" target=\"_blank\" rel=\"noopener noreferrer\" className=\"text-amber-700 underline hover:text-amber-900\">Install MetaMask Wallet</a></div>\n <div>• <a href=\"https://www.coinbase.com/wallet\" target=\"_blank\" rel=\"noopener noreferrer\" className=\"text-amber-700 underline hover:text-amber-900\">Install Coinbase Wallet</a></div>\n </div>\n </div>\n </div>\n </div>\n );\n }\n\n return (\n <div className=\"space-y-4\">\n <label className=\"block text-sm font-medium text-gray-700\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Select Wallet for {selectedNetwork.name}\n </label>\n\n {/* Beautiful Wallet Dropdown */}\n <ModernDropdown\n options={availableWallets}\n value={connectedWallet?.walletType || selectedWalletType || ''}\n onChange={handleWalletSelection}\n placeholder=\"Choose your wallet...\"\n renderOption={renderWalletOption}\n getOptionKey={(wallet) => wallet.type}\n getOptionValue={(wallet) => wallet.type}\n getSearchableText={(wallet) => `${wallet.name} ${wallet.description}`}\n disabled={loading}\n />\n </div>\n );\n};\n\nexport default WalletSelector;","/**\n * Debug Utilities for Production-Safe Logging\n *\n * Controls whether debug logs are shown based on environment\n * In production, only errors are logged\n */\n\n// Check if we're in development mode\nconst isDevelopment = () => {\n // Check multiple conditions\n if (typeof process !== 'undefined' && process.env) {\n return process.env.NODE_ENV === 'development';\n }\n\n // Fallback: check hostname for localhost\n if (typeof window !== 'undefined') {\n const hostname = window.location.hostname;\n return hostname === 'localhost' || hostname === '127.0.0.1' || hostname.includes('192.168.');\n }\n\n return false;\n};\n\n// Check if debug mode is explicitly enabled via URL param\nconst isDebugEnabled = () => {\n if (typeof window !== 'undefined') {\n const urlParams = new URLSearchParams(window.location.search);\n return urlParams.get('debug') === 'true' || urlParams.get('debugMode') === 'true';\n }\n return false;\n};\n\n// Master debug flag\nexport const DEBUG_MODE = isDevelopment() || isDebugEnabled();\n\n/**\n * Safe console.log that only logs in development or when debug=true\n */\nexport const debugLog = (...args) => {\n if (DEBUG_MODE) {\n console.log(...args);\n }\n};\n\n/**\n * Safe console.warn that only logs in development or when debug=true\n */\nexport const debugWarn = (...args) => {\n if (DEBUG_MODE) {\n console.warn(...args);\n }\n};\n\n/**\n * Safe console.error - ALWAYS logs (errors should always be visible)\n */\nexport const debugError = (...args) => {\n console.error(...args);\n};\n\n/**\n * Safe console.info that only logs in development or when debug=true\n */\nexport const debugInfo = (...args) => {\n if (DEBUG_MODE) {\n console.info(...args);\n }\n};\n\n/**\n * Sanitize object for logging (remove sensitive data)\n */\nexport const sanitizeForLog = (obj) => {\n if (!obj || typeof obj !== 'object') return obj;\n\n const sanitized = { ...obj };\n const sensitiveKeys = [\n 'apiKey',\n 'apiSecret',\n 'api_key',\n 'api_secret',\n 'x-api-key',\n 'x-api-secret',\n 'authorization',\n 'password',\n 'privateKey',\n 'private_key',\n 'mnemonic',\n 'seed'\n ];\n\n // Remove sensitive keys\n sensitiveKeys.forEach(key => {\n if (sanitized[key]) {\n sanitized[key] = '[REDACTED]';\n }\n // Also check lowercase\n const lowerKey = key.toLowerCase();\n if (sanitized[lowerKey]) {\n sanitized[lowerKey] = '[REDACTED]';\n }\n });\n\n return sanitized;\n};\n\n/**\n * Log object safely (sanitizes sensitive data)\n */\nexport const debugLogObject = (label, obj) => {\n if (DEBUG_MODE) {\n console.log(label, sanitizeForLog(obj));\n }\n};\n\nexport default {\n DEBUG_MODE,\n debugLog,\n debugWarn,\n debugError,\n debugInfo,\n debugLogObject,\n sanitizeForLog\n};\n","import React, { useState, useEffect } from 'react';\nimport ModernDropdown from './ModernDropdown';\nimport { generateQRPaymentURI, generateMobilePaymentDeepLink } from '../utils/deepLinkUtils';\nimport { DEBUG_MODE, debugLog } from '../../../utils/debugUtils';\n\nconst MobileWalletDropdown = ({\n paymentData,\n selectedToken,\n selectedNetwork,\n config,\n onPaymentStarted = () => {},\n onError = () => {}\n}) => {\n const [selectedWallet, setSelectedWallet] = useState(null);\n const [loading, setLoading] = useState(false);\n const [debugLogs, setDebugLogs] = useState([]);\n const [showDebugPanel, setShowDebugPanel] = useState(false);\n const [dataCheckCount, setDataCheckCount] = useState(0);\n\n // Auto-check data completeness periodically\n useEffect(() => {\n const isComplete = paymentData?.id &&\n selectedToken?.contractAddress &&\n selectedNetwork?.chainId &&\n (paymentData?.contractCall?.contractAddress || paymentData?.contractAddress);\n\n if (!isComplete) {\n // Log what's missing for debugging\n addDebugLog('debug', '⏳ Waiting for complete payment data', {\n hasPaymentId: !!paymentData?.id,\n hasTokenContract: !!selectedToken?.contractAddress,\n hasChainId: !!selectedNetwork?.chainId,\n hasPaymentContract: !!(paymentData?.contractCall?.contractAddress || paymentData?.contractAddress),\n checkCount: dataCheckCount\n });\n\n // Increment check count\n setDataCheckCount(prev => prev + 1);\n } else {\n addDebugLog('success', '✅ Payment data complete', {\n paymentId: paymentData.id,\n tokenContract: selectedToken.contractAddress,\n chainId: selectedNetwork.chainId,\n paymentContract: paymentData?.contractCall?.contractAddress || paymentData?.contractAddress\n });\n }\n }, [paymentData, selectedToken, selectedNetwork, dataCheckCount]);\n\n // Helper function to add debug logs to UI\n const addDebugLog = (type, message, data = null) => {\n const timestamp = new Date().toLocaleTimeString();\n const logEntry = {\n id: Date.now() + Math.random(),\n type,\n message,\n data,\n timestamp\n };\n // Only store logs if debug mode is enabled\n if (DEBUG_MODE) {\n setDebugLogs(prev => [...prev, logEntry].slice(-20)); // Keep last 20 logs\n debugLog(`[${type.toUpperCase()}] ${message}`, data || '');\n }\n };\n\n // Mobile wallet options for dropdown - Only trusted wallets\n const mobileWallets = [\n {\n id: 'metamask',\n name: 'MetaMask',\n icon: '🦊',\n description: 'Connect with MetaMask mobile'\n },\n {\n id: 'trust',\n name: 'Trust Wallet',\n icon: '🛡️',\n description: 'Connect with Trust Wallet'\n },\n {\n id: 'coinbase',\n name: 'Coinbase Wallet',\n icon: '💙',\n description: 'Connect with Coinbase Wallet'\n }\n ];\n\n const handleWalletSelection = async (walletId) => {\n const wallet = mobileWallets.find(w => w.id === walletId);\n if (!wallet) return;\n\n setSelectedWallet(walletId);\n setLoading(true);\n\n try {\n addDebugLog('info', `🚀 Mobile wallet selected: ${wallet.name}`);\n\n if (!paymentData) {\n throw new Error('Payment data not available. Please create payment first.');\n }\n\n // 🔍 SIMPLE DATA CHECK - just log what we have\n addDebugLog('debug', '🔍 Payment Data Check', {\n hasPaymentData: !!paymentData,\n hasSelectedToken: !!selectedToken,\n hasSelectedNetwork: !!selectedNetwork,\n hasConfig: !!config,\n paymentId: paymentData?.id || paymentData?.splitterPaymentId,\n tokenAddress: selectedToken?.contractAddress,\n networkChainId: selectedNetwork?.chainId,\n amount: paymentData?.totalAmount || paymentData?.amount || config?.amount\n });\n\n // Generate payment URL - let the URL generation function handle all the logic\n const paymentUri = generateQRPaymentURI(\n paymentData,\n selectedToken,\n selectedNetwork,\n config,\n walletId\n );\n\n if (!paymentUri) {\n throw new Error('Failed to generate payment URL');\n }\n\n addDebugLog('success', '📱 Generated payment URL', {\n url: paymentUri,\n length: paymentUri.length\n });\n\n // Generate wallet-specific deep link\n const mobileDeepLink = generateMobilePaymentDeepLink(walletId, paymentUri);\n\n if (!mobileDeepLink) {\n throw new Error(`Failed to generate ${wallet.name} deep link`);\n }\n\n addDebugLog('success', `🔗 Deep link generated for ${wallet.name}`, {\n deepLink: mobileDeepLink\n });\n\n // Notify parent that payment was started\n onPaymentStarted({\n walletType: walletId,\n walletName: wallet.name,\n paymentUrl: paymentUri,\n deepLink: mobileDeepLink\n });\n\n // Simple redirect with minimal feedback\n setTimeout(() => {\n addDebugLog('info', `📱 Opening ${wallet.name}...`);\n window.location.href = mobileDeepLink;\n }, 500);\n\n } catch (error) {\n addDebugLog('error', `❌ Mobile wallet connection failed`, {\n error: error.message,\n walletId,\n hasPaymentData: !!paymentData,\n hasSelectedToken: !!selectedToken,\n hasSelectedNetwork: !!selectedNetwork\n });\n onError(error.message);\n setLoading(false);\n setSelectedWallet(null);\n }\n };\n\n // Render wallet option for dropdown\n const renderWalletOption = (wallet) => {\n return (\n <div className=\"flex items-center space-x-3\">\n <div className=\"w-8 h-8 flex items-center justify-center\">\n <div className=\"text-2xl\">{wallet.icon}</div>\n </div>\n <div className=\"flex-1\">\n <div className=\"font-semibold text-gray-800\">\n {wallet.name}\n {selectedWallet === wallet.id && loading && (\n <span className=\"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full animate-pulse\">\n Opening...\n </span>\n )}\n </div>\n <div className=\"text-sm text-gray-500\">\n {wallet.description}\n </div>\n </div>\n </div>\n );\n };\n\n if (!paymentData) {\n return (\n <div className=\"p-4 bg-amber-50 rounded-lg border border-amber-200\">\n <div className=\"text-center\">\n <div className=\"text-amber-800 font-medium mb-2\">⚠️ Payment Required</div>\n <div className=\"text-sm text-amber-700\">\n Please create a payment before selecting a wallet\n </div>\n </div>\n </div>\n );\n }\n\n // Check if payment data is fully loaded with all required fields\n const isPaymentDataComplete = paymentData?.id &&\n selectedToken?.contractAddress &&\n selectedNetwork?.chainId &&\n (paymentData?.contractCall?.contractAddress || paymentData?.contractAddress);\n\n return (\n <div className=\"space-y-4\">\n {/* Show loading state if payment data is incomplete */}\n {!isPaymentDataComplete ? (\n <div className=\"p-4 bg-amber-50 rounded-lg border border-amber-200\">\n <div className=\"text-center\">\n <div className=\"text-amber-800 font-medium mb-2\">⏳ Preparing Payment...</div>\n <div className=\"text-sm text-amber-700\">\n Payment is being prepared. Please wait a moment...\n </div>\n <div className=\"mt-3\">\n <div className=\"animate-spin rounded-full h-6 w-6 border-2 border-amber-600 border-t-transparent mx-auto\"></div>\n </div>\n </div>\n </div>\n ) : (\n <>\n {/* Wallet Selection Dropdown */}\n <div className=\"space-y-2\">\n <label className=\"block text-sm font-medium text-gray-700\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Select Mobile Wallet\n </label>\n\n <ModernDropdown\n options={mobileWallets}\n value={selectedWallet || ''}\n onChange={handleWalletSelection}\n placeholder=\"Choose your wallet...\"\n renderOption={renderWalletOption}\n getOptionKey={(wallet) => wallet.id}\n getOptionValue={(wallet) => wallet.id}\n getSearchableText={(wallet) => `${wallet.name} ${wallet.description}`}\n disabled={loading}\n />\n\n {/* Help text */}\n <div className=\"text-xs text-gray-500 mt-2\">\n Select a wallet to open it with your payment details\n </div>\n </div>\n\n {/* Status message when loading */}\n {loading && selectedWallet && (\n <div className=\"p-3 bg-blue-50 border border-blue-200 rounded-lg animate-pulse\">\n <div className=\"flex items-center space-x-2\">\n <div className=\"animate-spin rounded-full h-4 w-4 border-2 border-blue-600 border-t-transparent\"></div>\n <div className=\"text-sm text-blue-700\">\n Opening {mobileWallets.find(w => w.id === selectedWallet)?.name}...\n </div>\n </div>\n </div>\n )}\n\n {/* Payment Details Summary */}\n <div className=\"p-3 bg-gray-50 rounded-lg\">\n <div className=\"flex justify-between items-center text-sm\">\n <span className=\"text-gray-600\">Amount:</span>\n <span className=\"font-semibold text-gray-800\">\n {paymentData.totalAmount} {selectedToken?.symbol || 'USDC'}\n </span>\n </div>\n <div className=\"flex justify-between items-center text-sm mt-1\">\n <span className=\"text-gray-600\">Network:</span>\n <span className=\"text-gray-800\">{selectedNetwork?.name || 'Ethereum'}</span>\n </div>\n </div>\n\n {/* Mobile Info */}\n <div className=\"p-3 bg-purple-50 border border-purple-200 rounded-lg\">\n <div className=\"text-xs text-purple-700\">\n <div className=\"font-medium mb-1\">📱 Mobile Payment</div>\n <div>Your selected wallet app will open with payment details pre-filled</div>\n </div>\n </div>\n\n {/* Mobile Debug Panel - Only show in development mode */}\n {DEBUG_MODE && (\n <div className=\"mt-4\">\n <button\n onClick={() => setShowDebugPanel(!showDebugPanel)}\n className=\"w-full text-xs py-2 px-3 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition-colors\"\n >\n {showDebugPanel ? '🔽 Hide Debug Info' : '🔧 Show Debug Info'} ({debugLogs.length} logs)\n </button>\n\n {showDebugPanel && (\n <div className=\"mt-2 p-3 bg-gray-900 text-green-400 rounded-lg text-xs font-mono max-h-80 overflow-y-auto\">\n <div className=\"text-white mb-2 font-bold\">📱 Mobile Debug Panel</div>\n {debugLogs.length === 0 ? (\n <div className=\"text-gray-400\">No debug logs yet. Try selecting a wallet...</div>\n ) : (\n debugLogs.map(log => (\n <div key={log.id} className=\"mb-3 pb-2 border-b border-gray-700\">\n <div className=\"flex items-center justify-between mb-1\">\n <span className={`px-2 py-1 rounded text-xs font-bold ${\n log.type === 'error' ? 'bg-red-600 text-white' :\n log.type === 'success' ? 'bg-green-600 text-white' :\n log.type === 'debug' ? 'bg-blue-600 text-white' :\n 'bg-gray-600 text-white'\n }`}>\n {log.type.toUpperCase()}\n </span>\n <span className=\"text-gray-400\">{log.timestamp}</span>\n </div>\n <div className=\"text-yellow-300 mb-1\">{log.message}</div>\n {log.data && (\n <div className=\"text-gray-300 text-xs\">\n <details>\n <summary className=\"cursor-pointer text-blue-300 hover:text-blue-200\">\n 📊 Data\n </summary>\n <pre className=\"mt-1 p-2 bg-gray-800 rounded overflow-x-auto whitespace-pre-wrap\">\n {JSON.stringify(log.data, null, 2)}\n </pre>\n </details>\n </div>\n )}\n </div>\n ))\n )}\n <button\n onClick={() => setDebugLogs([])}\n className=\"mt-2 px-3 py-1 bg-red-600 text-white rounded text-xs hover:bg-red-700\"\n >\n Clear Logs\n </button>\n </div>\n )}\n </div>\n )}\n </>\n )}\n </div>\n );\n};\n\nexport default MobileWalletDropdown;","import React from 'react';\nimport { parseUserFriendlyError, getErrorSeverity, getErrorActionText } from '../utils/errorUtils';\n\nconst ErrorDisplay = ({\n error,\n onRetry,\n onDismiss,\n context = 'payment',\n className = ''\n}) => {\n if (!error) return null;\n\n const friendlyError = parseUserFriendlyError(error);\n const severity = getErrorSeverity(friendlyError.type);\n const actionText = getErrorActionText(friendlyError.type);\n\n // Color schemes based on severity\n const severityStyles = {\n info: {\n container: 'bg-blue-50 border-blue-200',\n title: 'text-blue-800',\n message: 'text-blue-700',\n icon: 'ℹ️',\n button: 'bg-blue-600 hover:bg-blue-700'\n },\n warning: {\n container: 'bg-amber-50 border-amber-200',\n title: 'text-amber-800',\n message: 'text-amber-700',\n icon: '⚠️',\n button: 'bg-amber-600 hover:bg-amber-700'\n },\n error: {\n container: 'bg-red-50 border-red-200',\n title: 'text-red-800',\n message: 'text-red-700',\n icon: '❌',\n button: 'bg-red-600 hover:bg-red-700'\n },\n critical: {\n container: 'bg-red-50 border-red-300',\n title: 'text-red-900',\n message: 'text-red-800',\n icon: '🚨',\n button: 'bg-red-700 hover:bg-red-800'\n }\n };\n\n const styles = severityStyles[severity] || severityStyles.error;\n\n return (\n <div className={`p-4 border rounded-lg ${styles.container} ${className}`}>\n <div className=\"flex items-start space-x-3\">\n {/* Icon */}\n <div className=\"flex-shrink-0 text-xl\">\n {styles.icon}\n </div>\n\n {/* Content */}\n <div className=\"flex-1 min-w-0\">\n <div className={`font-semibold ${styles.title} mb-1`}>\n {friendlyError.title}\n </div>\n <div className={`text-sm ${styles.message} mb-2`}>\n {friendlyError.message}\n </div>\n {friendlyError.suggestion && (\n <div className={`text-xs ${styles.message} opacity-90`}>\n 💡 {friendlyError.suggestion}\n </div>\n )}\n </div>\n\n {/* Dismiss button */}\n {onDismiss && (\n <button\n onClick={onDismiss}\n className={`flex-shrink-0 text-gray-400 hover:text-gray-600 transition-colors`}\n aria-label=\"Dismiss error\"\n >\n <svg className=\"w-4 h-4\" fill=\"currentColor\" viewBox=\"0 0 20 20\">\n <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 </svg>\n </button>\n )}\n </div>\n\n {/* Action buttons */}\n {onRetry && (\n <div className=\"mt-3 flex justify-end space-x-2\">\n {onDismiss && severity === 'info' && (\n <button\n onClick={onDismiss}\n className=\"px-3 py-1.5 text-xs text-gray-600 hover:text-gray-800 transition-colors\"\n >\n Cancel\n </button>\n )}\n <button\n onClick={onRetry}\n className={`px-4 py-2 text-sm font-medium text-white rounded-md transition-colors ${styles.button}`}\n >\n {actionText}\n </button>\n </div>\n )}\n\n {/* Debug info in development */}\n {process.env.NODE_ENV === 'development' && (\n <details className=\"mt-3 text-xs opacity-50\">\n <summary className=\"cursor-pointer\">Debug Info</summary>\n <pre className=\"mt-1 p-2 bg-gray-100 rounded text-xs overflow-x-auto\">\n {JSON.stringify({\n type: friendlyError.type,\n originalError: error?.message || error?.toString(),\n code: error?.code,\n severity\n }, null, 2)}\n </pre>\n </details>\n )}\n </div>\n );\n};\n\nexport default ErrorDisplay;","// Payment flow steps\nexport const PAYMENT_STEPS = {\n METHOD: 'method',\n CONFIRM: 'confirm',\n PROCESSING: 'processing',\n SUCCESS: 'success',\n ERROR: 'error'\n};\n\n// Payment types\nexport const PAYMENT_TYPES = {\n WALLET: 'wallet',\n QR: 'qr'\n};\n\n// Transaction steps for PaymentSplitter flow\nexport const TRANSACTION_STEPS = {\n IDLE: 'idle',\n APPROVE: 'approve',\n SPLIT_PAYMENT: 'splitPayment',\n PROCESSING: 'processing',\n SUCCESS: 'success',\n ERROR: 'error'\n};\n\n// Payment statuses\nexport const PAYMENT_STATUS = {\n PENDING: 'pending',\n PROCESSING: 'processing',\n CONFIRMING: 'confirming',\n SUCCESS: 'success',\n FAILED: 'failed',\n CANCELLED: 'cancelled',\n TIMEOUT: 'timeout',\n INSUFFICIENT_FUNDS: 'insufficient_funds',\n NETWORK_ERROR: 'network_error',\n USER_REJECTED: 'user_rejected'\n};\n\n// Supported networks for EVM compatibility\nexport const SUPPORTED_NETWORKS = [\n 'ethereum',\n 'bsc',\n 'polygon',\n 'arbitrum',\n 'optimism',\n 'avalanche',\n 'celo',\n 'base'\n];\n\n// Supported stablecoins\nexport const SUPPORTED_TOKENS = ['USDC', 'USDT'];\n\n// Error codes for better error handling\nexport const ERROR_CODES = {\n USER_REJECTED: 4001,\n UNAUTHORIZED: 4100,\n UNSUPPORTED_METHOD: 4200,\n DISCONNECTED: 4900,\n CHAIN_DISCONNECTED: 4901,\n INSUFFICIENT_FUNDS: -32000,\n INVALID_PARAMS: -32602,\n INTERNAL_ERROR: -32603\n};\n\n// Timeouts and delays\nexport const TIMEOUTS = {\n TRANSACTION_TIMEOUT: 30000, // 30 seconds\n NETWORK_SWITCH_DELAY: 1000, // 1 second\n APPROVE_DELAY: 3000, // 3 seconds\n RETRY_DELAY: 2000, // 2 seconds\n APP_OPEN_TIMEOUT: 3000 // 3 seconds\n};\n\n// QR Code configuration\nexport const QR_CONFIG = {\n WIDTH_MOBILE: 300,\n WIDTH_DESKTOP: 200,\n MARGIN: 2,\n ERROR_CORRECTION_LEVEL: 'M' // 15% error correction\n};\n\n// Font family for consistent styling\nexport const FONT_FAMILY = 'Bricolage Grotesque, sans-serif';\n\n// Color scheme\nexport const COLORS = {\n PRIMARY: '#7042D2',\n PRIMARY_HOVER: '#5b34b1',\n PRIMARY_LIGHT: '#7042D2',\n SUCCESS: '#10B981',\n ERROR: '#EF4444',\n WARNING: '#F59E0B',\n INFO: '#3B82F6',\n GRAY: {\n 50: '#F9FAFB',\n 100: '#F3F4F6',\n 200: '#E5E7EB',\n 300: '#D1D5DB',\n 400: '#9CA3AF',\n 500: '#6B7280',\n 600: '#4B5563',\n 700: '#374151',\n 800: '#1F2937',\n 900: '#111827'\n }\n};\n\n// Validation patterns\nexport const VALIDATION = {\n EMAIL_REGEX: /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/,\n ETHEREUM_ADDRESS_REGEX: /^0x[a-fA-F0-9]{40}$/,\n TRANSACTION_HASH_REGEX: /^0x[a-fA-F0-9]{64}$/,\n MIN_AMOUNT: 0.01,\n MAX_AMOUNT: 1000000\n};\n\n// API endpoints\nexport const API_ENDPOINTS = {\n NETWORKS: '/api/networks',\n TOKENS: '/api/networks/stablecoins',\n CREATE_PAYMENT: '/api/payments/create',\n VERIFY_QR: '/api/payments/verify-qr',\n PROCESS_PAYMENT: '/api/payments/process',\n FAIL_PAYMENT: '/api/payments/fail',\n CONTRACT_INFO: '/api/payments/contract'\n};\n\n// Mobile user agent patterns\nexport const MOBILE_PATTERNS = [\n /Android/i,\n /webOS/i,\n /iPhone/i,\n /iPad/i,\n /iPod/i,\n /BlackBerry/i,\n /Windows Phone/i\n];\n\n// Default fallback data for when API fails\nexport const FALLBACK_NETWORKS = [\n { id: '1', name: 'Ethereum', shortName: 'ethereum', chainId: '0x1', type: 'ethereum' },\n { id: '56', name: 'BSC', shortName: 'bsc', chainId: '0x38', type: 'bsc' },\n { id: '137', name: 'Polygon', shortName: 'polygon', chainId: '0x89', type: 'polygon' },\n { id: '42161', name: 'Arbitrum', shortName: 'arbitrum', chainId: '0xa4b1', type: 'arbitrum' },\n { id: '10', name: 'Optimism', shortName: 'optimism', chainId: '0xa', type: 'optimism' },\n { id: '43114', name: 'Avalanche', shortName: 'avalanche', chainId: '0xa86a', type: 'avalanche' },\n { id: '42220', name: 'Celo', shortName: 'celo', chainId: '0xa4ec', type: 'celo' },\n { id: '8453', name: 'Base', shortName: 'base', chainId: '0x2105', type: 'base' }\n];\n\n// Browser extension detection\nexport const WALLET_DETECTION = {\n metamask: () => window.ethereum && window.ethereum.isMetaMask === true,\n trust: () => window.ethereum && window.ethereum.isTrust === true,\n coinbase: () => window.ethereum && window.ethereum.isCoinbaseWallet === true,\n injected: () => window.ethereum && !window.ethereum.isMetaMask && !window.ethereum.isCoinbaseWallet\n};\n\n// Deep link schemes\nexport const DEEP_LINK_SCHEMES = {\n EIP681: 'ethereum:',\n TRUST_WALLET: 'https://link.trustwallet.com/send',\n METAMASK: 'https://metamask.app.link/send'\n};\n\n// Payment processing retry configuration\nexport const RETRY_CONFIG = {\n MAX_RETRIES: 3,\n RETRY_DELAY: 8000, // 8 seconds\n EXPONENTIAL_BACKOFF: true\n};\n\n// Network specific configurations\nexport const NETWORK_CONFIG = {\n ethereum: {\n gasMultiplier: 1.2,\n confirmationBlocks: 3\n },\n arbitrum: {\n gasMultiplier: 1.0,\n confirmationBlocks: 1,\n hasJsonRpcIssues: true,\n maxRetries: 2\n },\n polygon: {\n gasMultiplier: 1.5,\n confirmationBlocks: 10\n },\n bsc: {\n gasMultiplier: 1.1,\n confirmationBlocks: 3\n },\n optimism: {\n gasMultiplier: 1.0,\n confirmationBlocks: 1\n },\n avalanche: {\n gasMultiplier: 1.3,\n confirmationBlocks: 3,\n syncDelay: 2500\n },\n celo: {\n gasMultiplier: 1.0,\n confirmationBlocks: 1\n },\n base: {\n gasMultiplier: 1.0,\n confirmationBlocks: 1\n }\n};","import React, { useEffect, useState } from 'react';\nimport { WagmiProvider } from 'wagmi';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\n\n// Modular imports\nimport { wagmiConfig } from './enhanced-payment/config/wagmiConfig';\nimport { usePaymentFlow } from './enhanced-payment/hooks/usePaymentFlow';\nimport { useWalletConnection } from './enhanced-payment/hooks/useWalletConnection';\nimport { useTransactionHandling } from './enhanced-payment/hooks/useTransactionHandling';\nimport ModernDropdown from './enhanced-payment/components/ModernDropdown';\nimport ScreenTransition from './enhanced-payment/components/ScreenTransition';\nimport PaymentStatus from './enhanced-payment/components/PaymentStatus';\nimport QRCodeDisplay from './enhanced-payment/components/QRCodeDisplay';\nimport WalletSelector from './enhanced-payment/components/WalletSelector';\nimport MobilePaymentButtons from './enhanced-payment/components/MobilePaymentButtons';\nimport MobileWalletDropdown from './enhanced-payment/components/MobileWalletDropdown';\nimport ErrorDisplay from './enhanced-payment/components/ErrorDisplay';\nimport { detectMobile } from './enhanced-payment/utils/walletUtils';\nimport {\n getNetworkLogoUrl,\n getTokenLogoUrl\n} from './enhanced-payment/config/logoConfig';\nimport { formatAmount } from './enhanced-payment/utils/formatUtils';\nimport { PAYMENT_STEPS, PAYMENT_TYPES, FONT_FAMILY } from './enhanced-payment/constants';\nimport logo from \"../assets/Logomark.png\";\n\n// Create Query Client for Wagmi\nconst queryClient = new QueryClient();\n\n// Internal component that uses Wagmi hooks\nconst EnhancedSimpleCoinleyPaymentInternal = ({\n publicKey, // New: Single public key for authentication (recommended)\n apiKey, // Legacy: API key (used with apiSecret)\n apiSecret, // Legacy: API secret (used with apiKey)\n apiUrl,\n config,\n onSuccess,\n onError,\n onClose,\n isOpen,\n theme = 'light'\n}) => {\n // Use our custom hooks for state management\n // Pass publicKey if available, otherwise fall back to legacy apiKey+apiSecret\n const paymentFlow = usePaymentFlow(apiUrl, publicKey || apiKey, publicKey ? null : apiSecret);\n const walletConnection = useWalletConnection();\n\n // State for QR code wallet preference\n const [qrWalletPreference, setQrWalletPreference] = useState('metamask');\n\n // Auto-detect mobile device\n const [isMobile, setIsMobile] = useState(false);\n\n // State for mobile payment verification - persist across page reloads\n const [mobilePaymentStarted, setMobilePaymentStarted] = useState(() => {\n // Check if user already started a mobile payment\n if (typeof window !== 'undefined' && window.sessionStorage) {\n return sessionStorage.getItem('coinley_mobile_payment_started') === 'true';\n }\n return false;\n });\n const [verifyingPayment, setVerifyingPayment] = useState(false);\n\n useEffect(() => {\n setIsMobile(detectMobile());\n }, []);\n\n const {\n currentStep,\n networks,\n tokens,\n selectedNetwork,\n selectedToken,\n paymentData,\n loading,\n error,\n paymentType,\n loadData,\n createPayment,\n failPayment,\n resetState,\n setSelectedNetwork,\n setSelectedToken,\n setPaymentType,\n setCurrentStep,\n setError\n } = paymentFlow;\n\n const {\n connectedWallet,\n address,\n connectWallet,\n handleWalletSelection\n } = walletConnection;\n\n // Use transaction handling hook\n const transactionHandling = useTransactionHandling(\n paymentData,\n selectedToken,\n selectedNetwork,\n address,\n paymentFlow.api,\n walletConnection\n );\n\n const {\n executePaymentTransaction,\n processFinalPayment,\n transactionStep,\n transactionError,\n currentTransactionHash\n } = transactionHandling;\n\n // Clear mobile payment started flag on success\n useEffect(() => {\n if (currentStep === PAYMENT_STEPS.SUCCESS && typeof window !== 'undefined' && window.sessionStorage) {\n sessionStorage.removeItem('coinley_mobile_payment_started');\n }\n }, [currentStep]);\n\n useEffect(() => {\n if (isOpen) {\n loadData();\n resetState();\n\n // Lock body scroll when modal is open\n const scrollY = window.scrollY;\n document.body.style.position = 'fixed';\n document.body.style.top = `-${scrollY}px`;\n document.body.style.width = '100%';\n document.body.style.overflow = 'hidden';\n } else {\n // Unlock body scroll when modal closes\n const scrollY = document.body.style.top;\n document.body.style.position = '';\n document.body.style.top = '';\n document.body.style.width = '';\n document.body.style.overflow = '';\n window.scrollTo(0, parseInt(scrollY || '0') * -1);\n }\n\n return () => {\n // Cleanup on unmount\n if (isOpen) {\n const scrollY = document.body.style.top;\n document.body.style.position = '';\n document.body.style.top = '';\n document.body.style.width = '';\n document.body.style.overflow = '';\n window.scrollTo(0, parseInt(scrollY || '0') * -1);\n }\n };\n }, [isOpen]);\n\n // Monitor transaction steps and handle timeouts\n useEffect(() => {\n if (transactionStep === 'processing' || transactionStep === 'approve' || transactionStep === 'splitPayment') {\n // Set a timeout to reset if transaction takes too long\n const timeout = setTimeout(() => {\n console.warn('⚠️ Transaction timeout - resetting state');\n setError('Transaction timed out. Please try again.');\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n transactionHandling.resetTransaction();\n }, 120000); // 2 minutes timeout\n\n return () => clearTimeout(timeout);\n }\n }, [transactionStep]);\n\n // Handle payment cancellation\n const handleCancel = async () => {\n await failPayment();\n onClose();\n };\n\n // Handle wallet connection\n const handleConnect = async (connector) => {\n const success = await connectWallet(connector, selectedNetwork);\n if (success && onSuccess) {\n console.log('✅ Wallet connected successfully');\n }\n };\n\n // Get wallet address for the selected network\n const getWalletAddressForNetwork = () => {\n if (!selectedNetwork) return null;\n\n // First check config for merchant wallet addresses\n const networkAddress = config?.merchantWalletAddresses?.[selectedNetwork.shortName];\n if (networkAddress) return networkAddress;\n\n // Then check paymentData\n if (paymentData?.recipientWallet) return paymentData.recipientWallet;\n if (paymentData?.merchantWalletAddress) return paymentData.merchantWalletAddress;\n\n return null;\n };\n\n // Render network option for dropdown\n const renderNetworkOption = (network) => {\n // Pass full network object to get logo from API data\n const networkLogoUrl = getNetworkLogoUrl(network);\n\n return (\n <div className=\"flex items-center space-x-3\">\n {networkLogoUrl ? (\n <img\n src={networkLogoUrl}\n alt={network.name}\n className=\"w-8 h-8 rounded-full\"\n onError={(e) => {\n e.target.style.display = 'none';\n e.target.nextSibling.style.display = 'flex';\n }}\n />\n ) : null}\n <div\n className=\"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center\"\n style={{ display: networkLogoUrl ? 'none' : 'flex' }}\n >\n <span className=\"text-xs font-bold text-gray-600\">{network.shortName?.slice(0, 2).toUpperCase()}</span>\n </div>\n <div>\n <div className=\"font-semibold text-gray-800\">{network.name}</div>\n <div className=\"text-sm text-gray-500\">{network.shortName?.toUpperCase()}</div>\n </div>\n </div>\n );\n };\n\n // Render token option for dropdown\n const renderTokenOption = (token) => {\n const tokenLogoUrl = getTokenLogoUrl(token.symbol);\n\n return (\n <div className=\"flex items-center space-x-3\">\n {tokenLogoUrl ? (\n <img\n src={tokenLogoUrl}\n alt={token.symbol}\n className=\"w-8 h-8 rounded-full\"\n onError={(e) => {\n e.target.style.display = 'none';\n e.target.nextSibling.style.display = 'flex';\n }}\n />\n ) : null}\n <div\n className=\"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center\"\n style={{ display: tokenLogoUrl ? 'none' : 'flex' }}\n >\n <span className=\"text-xs font-bold text-gray-600\">{token.symbol?.slice(0, 2)}</span>\n </div>\n <div>\n <div className=\"font-semibold text-gray-800\">{token.name} ({token.symbol})</div>\n <div className=\"text-sm text-gray-500\">\n {token.Network?.name || 'Unknown Network'}\n {token.isStablecoin && <span className=\"ml-2 text-green-600\">• Stablecoin</span>}\n </div>\n </div>\n </div>\n );\n };\n\n if (!isOpen) return null;\n\n return (\n <div className=\"fixed inset-0 z-50\">\n <div className=\"fixed inset-0 bg-black bg-opacity-50 transition-opacity\" onClick={handleCancel} aria-hidden=\"true\" />\n <div className=\"fixed inset-0 flex items-center justify-center p-4\" style={{ zIndex: 51 }}>\n <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 }}>\n\n {/* Modern Header with Logo - FIXED HEIGHT */}\n <div className=\"flex-shrink-0 bg-white flex justify-between items-center mb-3 mr-3 ml-3 py-3 px-2 rounded-full\">\n <div className=\"flex-1 flex items-center gap-2 px-4\">\n <div className=\"w-7 h-7 rounded-full flex items-center justify-center\">\n <img src={logo} alt=\"Coinley\" />\n </div>\n <span className=\"text-base font-semibold text-gray-800\" style={{ fontFamily: FONT_FAMILY }}>Payment Details</span>\n </div>\n {currentStep !== PAYMENT_STEPS.SUCCESS && currentStep !== PAYMENT_STEPS.PROCESSING && (\n <button\n onClick={handleCancel}\n className=\"text-gray-500 hover:text-gray-700 focus:outline-none\"\n >\n <svg xmlns=\"http://www.w3.org/2000/svg\" className=\"h-5 w-5 mr-2\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M6 18L18 6M6 6l12 12\" />\n </svg>\n </button>\n )}\n </div>\n\n {/* Payment Summary - COMPACT */}\n {config && currentStep !== PAYMENT_STEPS.SUCCESS && (\n <div className=\"flex-shrink-0 mb-3 px-4\">\n <div className=\"text-center\">\n <div className=\"text-xs text-gray-600\">Total Amount</div>\n <div className=\"text-3xl font-bold text-[#7042D2] mt-1 leading-tight tracking-tight\" style={{ fontFamily: FONT_FAMILY }}>\n ${formatAmount(config.amount)}\n </div>\n <div className=\"mt-1 text-xs text-gray-500\">No additional fees</div>\n <div className=\"text-xs text-gray-600 mt-2\">Payment to:</div>\n <div className=\"text-sm font-semibold mt-0.5 flex gap-1.5 items-center justify-center\" style={{ fontFamily: FONT_FAMILY }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <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\" />\n </svg>\n {config.merchantName || 'Merchant'}\n </div>\n </div>\n </div>\n )}\n\n {/* Main Content Area - SCROLLABLE */}\n <div className=\"flex-1 overflow-y-auto overscroll-contain\">\n\n {/* Step 1: Select Network & Token */}\n <ScreenTransition currentStep={currentStep} targetStep={PAYMENT_STEPS.METHOD}>\n <div className=\"pb-4 pt-3 px-5 bg-white rounded-t-2xl\">\n <h3 className=\"font-semibold text-center mb-3 text-sm\" style={{ fontFamily: FONT_FAMILY }}>Choose Payment Method</h3>\n\n {/* Network Selection */}\n <div className=\"space-y-3 mb-4\">\n <label className=\"block text-sm font-medium text-gray-700\" style={{ fontFamily: FONT_FAMILY }}>Select Network</label>\n <ModernDropdown\n options={networks}\n value={selectedNetwork?.id || ''}\n onChange={(networkId) => {\n const network = networks.find(n => n.id === networkId);\n setSelectedNetwork(network);\n setSelectedToken(null);\n }}\n placeholder=\"Choose your network...\"\n renderOption={renderNetworkOption}\n getOptionKey={(network) => network.id}\n getOptionValue={(network) => network.id}\n getSearchableText={(network) => `${network.name} ${network.shortName}`}\n disabled={loading}\n />\n </div>\n\n {/* Token Selection */}\n {selectedNetwork && (\n <div className=\"space-y-3 mb-4\">\n <label className=\"block text-sm font-medium text-gray-700\" style={{ fontFamily: FONT_FAMILY }}>Select Token</label>\n <ModernDropdown\n options={tokens.filter(token =>\n token.Network?.shortName === selectedNetwork?.shortName ||\n token.networkId === selectedNetwork?.id\n )}\n value={selectedToken?.id || ''}\n onChange={(tokenId) => {\n const token = tokens\n .filter(token =>\n token.Network?.shortName === selectedNetwork?.shortName ||\n token.networkId === selectedNetwork?.id\n )\n .find(t => t.id === tokenId);\n setSelectedToken(token);\n }}\n placeholder=\"Choose your token...\"\n renderOption={renderTokenOption}\n getOptionKey={(token) => token.id}\n getOptionValue={(token) => token.id}\n getSearchableText={(token) => `${token.name} ${token.symbol}`}\n disabled={loading}\n />\n </div>\n )}\n\n {/* Continue Button */}\n {selectedNetwork && selectedToken && (\n <button\n onClick={() => createPayment(config)}\n disabled={loading}\n 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\"\n style={{ fontFamily: FONT_FAMILY }}\n >\n {loading ? 'Creating Payment...' : 'Continue'}\n </button>\n )}\n </div>\n </ScreenTransition>\n\n {/* Step 2: Confirm Payment */}\n <ScreenTransition currentStep={currentStep} targetStep={PAYMENT_STEPS.CONFIRM}>\n {selectedNetwork && selectedToken && paymentData && (\n <div className=\"pb-4 pt-4 px-4 bg-white rounded-t-2xl\">\n {/* Payment Method Tabs - Only show tabs on desktop */}\n {!isMobile && (\n <div className=\"mb-4\">\n <div className=\"flex border-b border-gray-200\">\n <button\n onClick={() => setPaymentType(PAYMENT_TYPES.WALLET)}\n className={`py-3 px-6 text-sm font-semibold transition-all duration-200 ${paymentType === PAYMENT_TYPES.WALLET\n ? 'border-b-2 border-[#7042D2] text-[#7042D2]'\n : 'text-gray-500 hover:text-gray-700'\n }`}\n style={{ fontFamily: FONT_FAMILY }}\n >\n Connect Wallet\n </button>\n <button\n onClick={() => setPaymentType(PAYMENT_TYPES.QR)}\n className={`py-3 px-6 text-sm font-semibold transition-all duration-200 ${paymentType === PAYMENT_TYPES.QR\n ? 'border-b-2 border-[#7042D2] text-[#7042D2]'\n : 'text-gray-500 hover:text-gray-700'\n }`}\n style={{ fontFamily: FONT_FAMILY }}\n >\n QR Code\n </button>\n </div>\n </div>\n )}\n\n {/* AUTO-SELECT: Show mobile dropdown on mobile, extension wallet on desktop */}\n {isMobile ? (\n // Mobile: Show dropdown with deep link wallets\n <MobileWalletDropdown\n paymentData={paymentData}\n selectedToken={selectedToken}\n selectedNetwork={selectedNetwork}\n config={config}\n onPaymentStarted={(details) => {\n console.log('🚀 Mobile payment started:', details);\n setMobilePaymentStarted(true);\n if (typeof window !== 'undefined' && window.sessionStorage) {\n sessionStorage.setItem('coinley_mobile_payment_started', 'true');\n }\n // Optional: Show a success message or track event\n if (details.walletName) {\n console.log(`Opening ${details.walletName} with payment...`);\n }\n }}\n onError={(error) => {\n console.error('❌ Mobile payment error:', error);\n setError(error);\n }}\n />\n ) : (\n // Desktop: Show extension wallet or QR based on tab\n paymentType === PAYMENT_TYPES.WALLET ? (\n <WalletSelector\n selectedNetwork={selectedNetwork}\n onWalletSelect={handleWalletSelection}\n onConnect={handleConnect}\n connectedWallet={connectedWallet}\n loading={loading}\n />\n ) : null\n )}\n\n {/* QR Code Display */}\n {paymentType === PAYMENT_TYPES.QR && (\n <>\n {/* ✅ ULTRA-COMPACT: Horizontal wallet pills instead of dropdown */}\n <div className=\"mb-2\">\n <div className=\"text-xs font-medium text-gray-600 mb-1.5 text-center\" style={{ fontFamily: FONT_FAMILY }}>\n Optimize QR for:\n </div>\n <div className=\"flex gap-1.5 justify-center flex-wrap\">\n {[\n { id: 'metamask', name: 'MetaMask', icon: '🦊' },\n { id: 'trust', name: 'Trust', icon: '🛡️' },\n { id: 'coinbase', name: 'Coinbase', icon: '💙' }\n ].map((wallet) => (\n <button\n key={wallet.id}\n onClick={() => setQrWalletPreference(wallet.id)}\n className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all duration-200 ${\n qrWalletPreference === wallet.id\n ? 'bg-[#7042D2] text-white shadow-md'\n : 'bg-gray-100 text-gray-700 hover:bg-gray-200'\n }`}\n style={{ fontFamily: FONT_FAMILY }}\n >\n <span className=\"text-sm\">{wallet.icon}</span>\n <span>{wallet.name}</span>\n </button>\n ))}\n </div>\n </div>\n\n <QRCodeDisplay\n amount={paymentData?.totalAmount || paymentData?.amount || config?.amount}\n currency={selectedToken?.symbol}\n network={selectedNetwork?.shortName}\n theme={theme}\n paymentData={paymentData}\n config={config}\n selectedToken={selectedToken}\n selectedNetwork={selectedNetwork}\n preferredWallet={qrWalletPreference}\n compact={true}\n />\n </>\n )}\n\n {/* Error Display */}\n {(error || transactionError) && (\n <div className=\"mt-4\">\n <ErrorDisplay\n error={transactionError || error}\n onRetry={() => {\n setError('');\n transactionHandling.resetTransaction();\n // Retry the current step\n if (transactionStep === 'error' && connectedWallet) {\n executePaymentTransaction();\n }\n }}\n onDismiss={() => {\n setError('');\n transactionHandling.resetTransaction();\n }}\n context=\"payment\"\n />\n </div>\n )}\n\n {/* Action Buttons - ✅ COMPACT */}\n <div className=\"grid grid-cols-2 gap-2 mt-4\">\n <button\n type=\"button\"\n onClick={() => setCurrentStep(PAYMENT_STEPS.METHOD)}\n 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\"\n style={{ fontFamily: FONT_FAMILY }}\n >\n Back\n </button>\n <button\n type=\"button\"\n onClick={async () => {\n // For mobile deep link payments, verify payment on blockchain\n if (isMobile && mobilePaymentStarted) {\n if (!paymentData?.id) {\n setError('Payment ID not found. Please refresh and try again.');\n return;\n }\n\n try {\n setVerifyingPayment(true);\n setCurrentStep(PAYMENT_STEPS.PROCESSING);\n setError('');\n\n console.log('🔍 Verifying mobile payment:', paymentData.id);\n\n // First check if backend already knows about completed payment\n const statusResult = await paymentFlow.api.checkPaymentStatus(paymentData.id);\n\n if (statusResult.payment?.status === 'completed') {\n console.log('✅ Payment already completed:', statusResult.payment);\n setCurrentStep(PAYMENT_STEPS.SUCCESS);\n if (onSuccess) {\n onSuccess({\n paymentId: paymentData.id,\n transactionHash: statusResult.payment.transactionHash,\n paymentDetails: statusResult.payment\n });\n }\n } else if (statusResult.payment?.status === 'pending') {\n // Payment exists but not completed yet - try blockchain verification\n console.log('⏳ Payment pending, verifying on blockchain...');\n\n const verificationResult = await paymentFlow.api.verifyQRPayment(paymentData.id);\n\n if (verificationResult.success && verificationResult.verified) {\n console.log('✅ Payment verified on blockchain:', verificationResult.onChainData);\n setCurrentStep(PAYMENT_STEPS.SUCCESS);\n if (onSuccess) {\n onSuccess({\n paymentId: paymentData.id,\n transactionHash: verificationResult.onChainData?.transactionHash,\n paymentDetails: verificationResult.payment\n });\n }\n } else {\n // Payment not yet confirmed on blockchain\n const message = verificationResult.message || 'Payment not yet confirmed on blockchain';\n setError(`${message}. Please complete the payment in your wallet and try again.`);\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n }\n } else if (statusResult.payment?.status === 'failed') {\n setError('Payment failed. Please try creating a new payment.');\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n } else {\n setError('Payment not found. Please verify the payment ID and try again.');\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n }\n } catch (error) {\n console.error('❌ Mobile payment verification failed:', error);\n setError(`Verification failed: ${error.message}. Please ensure payment was completed and try again.`);\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n } finally {\n setVerifyingPayment(false);\n }\n return;\n }\n\n // For QR code, verify payment on blockchain\n if (paymentType === PAYMENT_TYPES.QR) {\n if (!paymentData?.id) {\n setError('Payment ID not found. Please refresh and try again.');\n return;\n }\n\n try {\n setCurrentStep(PAYMENT_STEPS.PROCESSING);\n setError('');\n\n console.log('🔍 Checking payment status:', paymentData.id);\n\n // First check if backend already knows about completed payment\n const statusResult = await paymentFlow.api.checkPaymentStatus(paymentData.id);\n\n if (statusResult.payment?.status === 'completed') {\n console.log('✅ Payment already completed:', statusResult.payment);\n setCurrentStep(PAYMENT_STEPS.SUCCESS);\n if (onSuccess) {\n onSuccess({\n paymentId: paymentData.id,\n transactionHash: statusResult.payment.transactionHash,\n paymentDetails: statusResult.payment\n });\n }\n } else if (statusResult.payment?.status === 'pending') {\n // Payment exists but not completed yet - try blockchain verification\n console.log('⏳ Payment pending, verifying on blockchain...');\n\n const verificationResult = await paymentFlow.api.verifyQRPayment(paymentData.id);\n\n if (verificationResult.success && verificationResult.verified) {\n console.log('✅ Payment verified on blockchain:', verificationResult.onChainData);\n setCurrentStep(PAYMENT_STEPS.SUCCESS);\n if (onSuccess) {\n onSuccess({\n paymentId: paymentData.id,\n transactionHash: verificationResult.onChainData?.transactionHash,\n paymentDetails: verificationResult.payment\n });\n }\n } else {\n // Payment not yet confirmed on blockchain\n const message = verificationResult.message || 'Payment not yet confirmed on blockchain';\n setError(`${message}. Please complete the payment and try again.`);\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n }\n } else if (statusResult.payment?.status === 'failed') {\n setError('Payment failed. Please try creating a new payment.');\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n } else {\n setError('Payment not found. Please verify the payment ID and try again.');\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n }\n } catch (error) {\n console.error('❌ QR payment verification failed:', error);\n setError(`Verification failed: ${error.message}. Please ensure payment was completed and try again.`);\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n }\n return;\n } else if (connectedWallet && address) {\n // Handle wallet transaction\n try {\n setCurrentStep(PAYMENT_STEPS.PROCESSING);\n setError('');\n\n // Execute the payment transaction (handles backend notification internally)\n const txHash = await executePaymentTransaction();\n\n if (txHash) {\n // ✅ FIX: Clear any previous errors before success\n setError('');\n transactionHandling.setTransactionError('');\n\n // Payment processed successfully, show success screen\n setCurrentStep(PAYMENT_STEPS.SUCCESS);\n\n console.log('✅ Payment SUCCESS - calling onSuccess callback', {\n paymentId: paymentData.id,\n transactionHash: txHash,\n isRetry: !!error // Log if this was a retry after error\n });\n\n if (onSuccess) {\n // ✅ FIX: Ensure callback is called even on retry\n onSuccess({\n paymentId: paymentData.id,\n transactionHash: txHash,\n paymentDetails: paymentData\n });\n }\n }\n } catch (error) {\n console.error('Transaction failed:', error);\n\n // ✅ FIX: Clear previous success state to allow retry\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n\n // Check if user rejected the transaction\n if (error.message?.includes('User rejected') ||\n error.message?.includes('User denied') ||\n error.code === 4001 ||\n error.code === 'ACTION_REJECTED') {\n setError('Transaction was cancelled by user. Please try again.');\n } else {\n setError(error.message || 'Transaction failed. Please try again.');\n }\n\n // Reset transaction state\n transactionHandling.resetTransaction();\n\n // ✅ FIX: Don't call onError on first failure to allow retry\n // Only log the error, don't close the modal\n console.log('⚠️ Transaction failed, user can retry');\n }\n }\n }}\n 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\"\n disabled={(paymentType === PAYMENT_TYPES.WALLET && !connectedWallet && !isMobile) ||\n (isMobile && !mobilePaymentStarted) ||\n transactionStep === 'processing' ||\n verifyingPayment}\n style={{ fontFamily: FONT_FAMILY }}\n >\n {verifyingPayment ? 'Verifying...' :\n transactionStep === 'processing' ? 'Processing...' :\n isMobile && mobilePaymentStarted ? 'I Have Paid' :\n isMobile ? 'Select Wallet' :\n paymentType === PAYMENT_TYPES.QR ? 'I Have Paid' :\n 'Pay Now'}\n </button>\n </div>\n </div>\n )}\n </ScreenTransition>\n\n {/* Processing Screen */}\n <ScreenTransition currentStep={currentStep} targetStep={PAYMENT_STEPS.PROCESSING}>\n <PaymentStatus\n status=\"processing\"\n message={\n transactionStep === 'approve' ? \"Approving token spending...\" :\n transactionStep === 'splitPayment' ? \"Processing payment split...\" :\n currentTransactionHash ? \"Confirming transaction on blockchain...\" :\n \"Processing your payment...\"\n }\n theme={theme}\n transactionHash={currentTransactionHash}\n selectedNetwork={selectedNetwork}\n />\n </ScreenTransition>\n\n {/* Success Screen */}\n <ScreenTransition currentStep={currentStep} targetStep={PAYMENT_STEPS.SUCCESS}>\n <PaymentStatus\n status=\"success\"\n message=\"Payment completed successfully!\"\n theme={theme}\n payment={paymentData}\n transactionHash={currentTransactionHash || paymentData?.transactionHash}\n selectedPaymentMethod={selectedToken}\n selectedNetwork={selectedNetwork}\n merchantName={config?.merchantName || 'Merchant'}\n onClose={onClose}\n />\n </ScreenTransition>\n\n {/* Error Display */}\n {(error || transactionError) && (\n <div className=\"p-4 bg-red-50 border border-red-200 rounded-lg mx-6 mb-4\">\n <p className=\"text-red-800 text-sm\">{error || transactionError}</p>\n <button\n onClick={() => {\n setError('');\n transactionHandling.setTransactionError('');\n }}\n className=\"mt-2 text-red-600 hover:text-red-800 text-xs underline\"\n >\n Dismiss\n </button>\n </div>\n )}\n </div>\n\n {/* Enhanced Footer */}\n {currentStep !== PAYMENT_STEPS.SUCCESS && (\n <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: FONT_FAMILY }}>\n <p>Powered by <span className='text-[#7042D2] font-semibold'>Coinley</span> - Multi-Wallet Support</p>\n <svg className=\"inline w-4 h-4 text-green-500 ml-1\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" viewBox=\"0 0 24 24\">\n <circle cx=\"12\" cy=\"12\" r=\"10\" stroke=\"currentColor\" strokeWidth=\"2\" fill=\"none\" />\n <path d=\"M9 12l2 2 4-4\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n </div>\n )}\n </div>\n </div>\n </div>\n );\n};\n\n// Main export with Wagmi provider wrapper\nconst EnhancedSimpleCoinleyPayment = (props) => {\n return (\n <WagmiProvider config={wagmiConfig}>\n <QueryClientProvider client={queryClient}>\n <EnhancedSimpleCoinleyPaymentInternal {...props} />\n </QueryClientProvider>\n </WagmiProvider>\n );\n};\n\nexport default EnhancedSimpleCoinleyPayment;","//src/CoinleyProvider.jsx - coinley-test\nimport React, { createContext, useContext, useRef, forwardRef, useImperativeHandle } from 'react';\n// import CoinleyPayment from './CoinleyPayment';\nimport CoinleyPayment from './components/EnhancedSimpleCoinleyPayment';\n\nconst CoinleyContext = createContext(null);\n\n// CoinleyProvider supports both new publicKey auth and legacy apiKey+apiSecret auth\n// New usage: <CoinleyProvider publicKey=\"pk_xxx\" apiUrl=\"...\" />\n// Legacy usage: <CoinleyProvider apiKey=\"xxx\" apiSecret=\"xxx\" apiUrl=\"...\" />\nexport const CoinleyProvider = ({\n publicKey, // New: Single public key for authentication (recommended)\n apiKey, // Legacy: API key (used with apiSecret)\n apiSecret, // Legacy: API secret (used with apiKey)\n apiUrl,\n theme = 'light',\n debug = false,\n children\n}) => {\n const [isOpen, setIsOpen] = React.useState(false);\n const [paymentConfig, setPaymentConfig] = React.useState(null);\n const [callbacks, setCallbacks] = React.useState({});\n const [merchantName, setMerchantName] = React.useState('');\n\n const openPayment = (config, checkoutCallbacks) => {\n setPaymentConfig(config);\n if (checkoutCallbacks) {\n setCallbacks(checkoutCallbacks);\n }\n setIsOpen(true);\n };\n\n const closePayment = () => {\n setIsOpen(false);\n setPaymentConfig(null);\n if (callbacks.onClose) {\n callbacks.onClose();\n }\n };\n\n const contextValue = {\n openPayment,\n closePayment\n };\n\n return (\n <CoinleyContext.Provider value={contextValue}>\n {children}\n {isOpen && paymentConfig && (\n <CoinleyPayment\n publicKey={publicKey}\n apiKey={apiKey}\n apiSecret={apiSecret}\n apiUrl={apiUrl}\n isOpen={isOpen}\n config={paymentConfig}\n theme={theme}\n debug={debug}\n merchantName={merchantName}\n onSuccess={callbacks.onSuccess}\n onError={callbacks.onError}\n onClose={closePayment}\n />\n )}\n </CoinleyContext.Provider>\n );\n};\n\nexport const CoinleyCheckout = forwardRef((\n {\n customerEmail = '',\n merchantName = '',\n onSuccess,\n onError,\n onClose,\n theme = 'light',\n autoOpen = false,\n testMode = false,\n debug = false,\n merchantWalletAddresses = {}\n },\n ref\n) => {\n const context = useContext(CoinleyContext);\n\n if (!context) {\n throw new Error('CoinleyCheckout must be used within a CoinleyProvider');\n }\n\n const { openPayment, closePayment } = context;\n\n const open = (config) => {\n try {\n if (debug) {\n console.log('Opening Coinley checkout with config:', config);\n }\n\n if (!config.amount || config.amount <= 0) {\n throw new Error('Amount must be greater than 0');\n }\n\n const finalConfig = {\n ...config,\n customerEmail: config.customerEmail || customerEmail,\n merchantWalletAddresses: {\n ...merchantWalletAddresses,\n ...config.merchantWalletAddresses\n },\n metadata: {\n ...config.metadata,\n testMode,\n checkoutVersion: '1.0.0'\n }\n };\n\n const checkoutCallbacks = {\n onSuccess,\n onError,\n onClose\n };\n\n openPayment(finalConfig, checkoutCallbacks);\n } catch (error) {\n console.error('Failed to open Coinley checkout:', error);\n if (onError) {\n onError(error);\n }\n }\n };\n\n const close = () => {\n closePayment();\n };\n\n useImperativeHandle(ref, () => ({\n open,\n close\n }));\n\n return null;\n});\n\nCoinleyCheckout.displayName = 'CoinleyCheckout';\n\nexport const useCoinley = () => {\n const context = useContext(CoinleyContext);\n if (!context) {\n throw new Error('useCoinley must be used within a CoinleyProvider');\n }\n return context;\n};\n\nexport const ThemeProvider = ({\n initialTheme = 'light',\n children\n}) => {\n const [theme, setTheme] = React.useState(initialTheme);\n\n React.useEffect(() => {\n document.documentElement.setAttribute('data-coinley-theme', theme);\n }, [theme]);\n\n const toggleTheme = () => {\n setTheme(prev => prev === 'light' ? 'dark' : 'light');\n };\n\n return (\n <div className={`coinley-theme-${theme}`}>\n {children}\n </div>\n );\n};","//src/PaymentAPI.js\nimport axios from 'axios';\n\nexport class PaymentAPI {\n // Supports both new publicKey auth and legacy apiKey+apiSecret auth\n constructor(baseURL, publicKeyOrApiKey, apiSecret = null) {\n // Determine if using new publicKey auth (starts with 'pk_') or legacy auth\n if (publicKeyOrApiKey && publicKeyOrApiKey.startsWith('pk_')) {\n // New public key authentication\n this.publicKey = publicKeyOrApiKey;\n this.apiKey = null;\n this.apiSecret = null;\n } else {\n // Legacy authentication with apiKey + apiSecret\n this.publicKey = null;\n this.apiKey = publicKeyOrApiKey;\n this.apiSecret = apiSecret;\n }\n\n this.api = axios.create({\n baseURL: baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL,\n timeout: 30000,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n // Add request interceptor\n this.api.interceptors.request.use(\n (config) => {\n // Use public key if available (new method)\n if (this.publicKey) {\n config.headers['x-public-key'] = this.publicKey;\n } else {\n // Fall back to legacy apiKey + apiSecret\n config.headers['x-api-key'] = this.apiKey;\n config.headers['x-api-secret'] = this.apiSecret;\n\n const token = this.generateMerchantToken();\n if (token) {\n config.headers['Authorization'] = `Bearer ${token}`;\n }\n }\n\n console.log('API Request:', {\n method: config.method?.toUpperCase(),\n url: config.url,\n data: config.data\n });\n\n return config;\n },\n (error) => {\n console.error('Request interceptor error:', error);\n return Promise.reject(error);\n }\n );\n\n // Add response interceptor\n this.api.interceptors.response.use(\n (response) => {\n console.log('API Response:', {\n status: response.status,\n url: response.config.url,\n data: response.data\n });\n return response;\n },\n (error) => {\n console.error('API Error:', {\n status: error.response?.status,\n data: error.response?.data,\n message: error.message\n });\n\n if (error.response?.status === 401) {\n throw new Error('Authentication failed. Please check your API credentials.');\n } else if (error.response?.status === 404) {\n throw new Error('API endpoint not found. Please check your API URL.');\n } else if (error.response?.status >= 500) {\n throw new Error('Server error. Please try again later.');\n }\n\n throw error;\n }\n );\n }\n\n generateMerchantToken() {\n try {\n const credentials = `${this.apiKey}:${this.apiSecret}`;\n return btoa(credentials);\n } catch (error) {\n console.error('Failed to generate token:', error);\n return null;\n }\n }\n\n // ✅ FIXED: Add generic request method for internal use\n async request(endpoint, options = {}) {\n try {\n const response = await this.api({\n url: endpoint,\n method: options.method || 'GET',\n data: options.data || options.body ? JSON.parse(options.body || '{}') : undefined,\n ...options\n });\n return response.data;\n } catch (error) {\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Request failed');\n }\n }\n\n async createPayment(params) {\n try {\n const response = await this.api.post('/api/payments/create', params);\n return response.data;\n } catch (error) {\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Failed to create payment');\n }\n }\n\n async getPayment(paymentId) {\n try {\n const response = await this.api.get(`/api/payments/${paymentId}`);\n return response.data;\n } catch (error) {\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Failed to get payment details');\n }\n }\n\n async getNetworks() {\n try {\n const response = await this.api.get('/api/networks');\n return response.data;\n } catch (error) {\n console.error('Get networks failed:', error);\n \n // Return fallback networks\n // ✅ FIXED: chainId now returned as decimal integers for consistency with backend\n return {\n networks: [\n {\n id: 'ethereum',\n name: 'Ethereum',\n shortName: 'ethereum',\n chainId: 1, // ✅ Decimal integer\n type: 'ethereum',\n explorerUrl: 'https://etherscan.io',\n isTestnet: false,\n },\n {\n id: 'bsc',\n name: 'Binance Smart Chain',\n shortName: 'bsc',\n chainId: 56, // ✅ Decimal integer\n type: 'bsc',\n explorerUrl: 'https://bscscan.com',\n isTestnet: false,\n },\n {\n id: 'polygon',\n name: 'Polygon',\n shortName: 'polygon',\n chainId: 137, // ✅ Decimal integer\n type: 'ethereum',\n explorerUrl: 'https://polygonscan.com',\n isTestnet: false,\n },\n ]\n };\n }\n }\n\n async getStablecoins() {\n try {\n const response = await this.api.get('/api/networks/stablecoins');\n return response.data;\n } catch (error) {\n console.error('Get stablecoins failed:', error);\n \n // Return fallback stablecoins\n return {\n stablecoins: [\n {\n id: 'usdt-eth',\n name: 'Tether USD',\n symbol: 'USDT',\n contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n decimals: 6,\n isStablecoin: true,\n networkId: 'ethereum',\n Network: {\n id: 'ethereum',\n name: 'Ethereum',\n shortName: 'ethereum',\n type: 'ethereum',\n }\n },\n {\n id: 'usdc-eth',\n name: 'USD Coin',\n symbol: 'USDC',\n contractAddress: '0xA0b86a33E6441d81d0B93bF9EE0f74ca32F7e6f6',\n decimals: 6,\n isStablecoin: true,\n networkId: 'ethereum',\n Network: {\n id: 'ethereum',\n name: 'Ethereum',\n shortName: 'ethereum',\n type: 'ethereum',\n }\n }\n ]\n };\n }\n }\n\n async verifyQRPayment(paymentId) {\n try {\n const response = await this.api.post('/api/payments/verify-qr', {\n paymentId\n });\n return response.data;\n } catch (error) {\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Failed to verify payment');\n }\n }\n\n // ✅ PaymentSplitter: Process payment with transaction hash (ENHANCED ERROR HANDLING)\n async processPayment(paymentId, transactionHash, network, senderAddress) {\n try {\n console.log('🔄 PaymentAPI: Processing PaymentSplitter transaction:', {\n paymentId,\n transactionHash,\n network,\n senderAddress\n });\n\n const response = await this.api.post('/api/payments/process', {\n paymentId,\n transactionHash,\n network,\n senderAddress\n });\n\n console.log('✅ PaymentAPI: PaymentSplitter transaction processed:', response.data);\n return response.data;\n } catch (error) {\n console.error('❌ PaymentAPI: PaymentSplitter transaction failed:', error);\n\n // ✅ ENHANCED: Better error categorization for frontend handling\n if (error.response?.data) {\n const errorData = error.response.data;\n const errorMessage = errorData.error || errorData.message || 'Payment processing failed';\n\n // Create enhanced error with additional context\n const enhancedError = new Error(errorMessage);\n enhancedError.isAlreadyCompleted = errorData.isAlreadyCompleted || false;\n enhancedError.verificationAttempts = errorData.verificationAttempts || 0;\n enhancedError.statusCode = error.response.status;\n enhancedError.originalData = errorData;\n\n throw enhancedError;\n }\n\n throw new Error(error.message || 'Failed to process PaymentSplitter transaction');\n }\n }\n\n // ✅ PaymentSplitter: Get contract information for a specific chain\n async getContractInfo(chainId) {\n try {\n console.log('🔍 PaymentAPI: Getting contract info for chain:', chainId);\n\n const response = await this.api.get(`/api/payments/contract/${chainId}`);\n \n console.log('✅ PaymentAPI: Contract info retrieved:', response.data.contractInfo);\n return response.data.contractInfo;\n } catch (error) {\n console.error('❌ PaymentAPI: Failed to get contract info:', error);\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Failed to get contract information');\n }\n }\n\n // ✅ PaymentSplitter: Get payment splitter status\n async getPaymentSplitterStatus(paymentId) {\n try {\n console.log('🔍 PaymentAPI: Getting PaymentSplitter status for:', paymentId);\n\n const response = await this.api.get(`/api/payments/splitter-status/${paymentId}`);\n \n console.log('✅ PaymentAPI: PaymentSplitter status:', response.data.paymentSplitterStatus);\n return response.data.paymentSplitterStatus;\n } catch (error) {\n console.error('❌ PaymentAPI: Failed to get PaymentSplitter status:', error);\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Failed to get PaymentSplitter status');\n }\n }\n\n // ✅ PaymentSplitter: Health check\n async checkPaymentSplitterHealth() {\n try {\n const response = await this.api.get('/api/payments/health');\n return response.data.paymentSplitterHealth;\n } catch (error) {\n console.error('PaymentSplitter health check failed:', error);\n return { error: error.message };\n }\n }\n\n async healthCheck() {\n try {\n const response = await this.api.get('/api/health');\n return response.status === 200;\n } catch (error) {\n console.error('Health check failed:', error);\n return false;\n }\n }\n}","// Balance checking utilities for both ERC-20 tokens and native currencies\nimport { createPublicClient, http, formatUnits, getContract } from 'viem';\nimport { mainnet, bsc, polygon, arbitrum, optimism, avalanche } from 'viem/chains';\n\n// Network chain configurations\nconst NETWORK_CHAINS = {\n ethereum: mainnet,\n bsc: bsc,\n polygon: polygon,\n arbitrum: arbitrum,\n optimism: optimism,\n avalanche: avalanche\n};\n\n// ERC-20 ABI for balance checking\nconst ERC20_ABI = [\n {\n constant: true,\n inputs: [{ name: '_owner', type: 'address' }],\n name: 'balanceOf',\n outputs: [{ name: 'balance', type: 'uint256' }],\n type: 'function',\n },\n {\n constant: true,\n inputs: [],\n name: 'decimals',\n outputs: [{ name: '', type: 'uint8' }],\n type: 'function',\n },\n {\n constant: true,\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '', type: 'string' }],\n type: 'function',\n },\n];\n\nclass BalanceChecker {\n constructor() {\n this.clients = new Map();\n }\n\n // Get or create viem client for network\n getClient(networkShortName) {\n if (!this.clients.has(networkShortName)) {\n const chain = NETWORK_CHAINS[networkShortName];\n if (!chain) {\n throw new Error(`Unsupported network: ${networkShortName}`);\n }\n \n const client = createPublicClient({\n chain,\n transport: http()\n });\n this.clients.set(networkShortName, client);\n }\n \n return this.clients.get(networkShortName);\n }\n\n // Check native token balance (ETH, BNB, MATIC, etc.)\n async checkNativeBalance(walletAddress, networkShortName) {\n try {\n console.log(`🔍 Checking native balance for ${walletAddress} on ${networkShortName}`);\n \n const client = this.getClient(networkShortName);\n const balanceWei = await client.getBalance({ \n address: walletAddress \n });\n const balanceEther = formatUnits(balanceWei, 18);\n \n console.log(`💰 Native balance: ${balanceEther} ${this.getNativeTokenSymbol(networkShortName)}`);\n \n return {\n balance: parseFloat(balanceEther),\n balanceWei: balanceWei.toString(),\n symbol: this.getNativeTokenSymbol(networkShortName),\n decimals: 18\n };\n } catch (error) {\n console.error(`❌ Failed to check native balance:`, error);\n throw new Error(`Failed to check native balance: ${error.message}`);\n }\n }\n\n // Check ERC-20 token balance\n async checkTokenBalance(walletAddress, tokenAddress, networkShortName) {\n try {\n console.log(`🔍 Checking token balance for ${walletAddress} on ${networkShortName}`);\n console.log(`🪙 Token contract: ${tokenAddress}`);\n \n const client = this.getClient(networkShortName);\n \n // Create contract instance\n const contract = getContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n client\n });\n \n // Get token info and balance in parallel\n const [balanceWei, decimals, symbol] = await Promise.all([\n contract.read.balanceOf([walletAddress]),\n contract.read.decimals().catch(() => 18), // Default to 18 if fails\n contract.read.symbol().catch(() => 'TOKEN')\n ]);\n \n const balance = parseFloat(formatUnits(balanceWei, decimals));\n \n console.log(`💰 Token balance: ${balance} ${symbol}`);\n \n return {\n balance: balance,\n balanceWei: balanceWei.toString(),\n symbol: symbol,\n decimals: decimals,\n tokenAddress: tokenAddress\n };\n } catch (error) {\n console.error(`❌ Failed to check token balance:`, error);\n throw new Error(`Failed to check token balance: ${error.message}`);\n }\n }\n\n // Check if user has sufficient balance for transaction\n async validateBalance(walletAddress, token, requiredAmount, networkShortName, includeGasFee = true) {\n try {\n console.log(`🔍 Validating balance for payment:`);\n console.log(` Required: ${requiredAmount} ${token.symbol}`);\n console.log(` Network: ${networkShortName}`);\n console.log(` Include gas fee check: ${includeGasFee}`);\n \n let tokenBalance;\n let nativeBalance = null;\n \n // Check token balance\n if (token.contractAddress) {\n // ERC-20 token\n tokenBalance = await this.checkTokenBalance(walletAddress, token.contractAddress, networkShortName);\n } else {\n // Native token\n tokenBalance = await this.checkNativeBalance(walletAddress, networkShortName);\n }\n \n // Always check native balance for gas fees (unless it's the same as the payment token)\n if (token.contractAddress && includeGasFee) {\n nativeBalance = await this.checkNativeBalance(walletAddress, networkShortName);\n }\n \n // Validate token balance\n const hasEnoughTokens = tokenBalance.balance >= requiredAmount;\n const tokenShortfall = hasEnoughTokens ? 0 : requiredAmount - tokenBalance.balance;\n \n // Estimate gas fees\n let estimatedGasFee = 0;\n let hasEnoughForGas = true;\n let gasShortfall = 0;\n \n if (includeGasFee) {\n estimatedGasFee = this.estimateGasFee(networkShortName, !!token.contractAddress);\n \n if (token.contractAddress) {\n // ERC-20 payment - need native tokens for gas\n hasEnoughForGas = nativeBalance.balance >= estimatedGasFee;\n gasShortfall = hasEnoughForGas ? 0 : estimatedGasFee - nativeBalance.balance;\n } else {\n // Native token payment - need extra for gas\n const totalRequired = requiredAmount + estimatedGasFee;\n hasEnoughForGas = tokenBalance.balance >= totalRequired;\n gasShortfall = hasEnoughForGas ? 0 : totalRequired - tokenBalance.balance;\n }\n }\n \n const validationResult = {\n isValid: hasEnoughTokens && hasEnoughForGas,\n tokenBalance: tokenBalance,\n nativeBalance: nativeBalance,\n requiredAmount: requiredAmount,\n estimatedGasFee: estimatedGasFee,\n hasEnoughTokens: hasEnoughTokens,\n hasEnoughForGas: hasEnoughForGas,\n tokenShortfall: tokenShortfall,\n gasShortfall: gasShortfall,\n errors: []\n };\n \n // Add specific error messages\n if (!hasEnoughTokens) {\n validationResult.errors.push(\n `Insufficient ${token.symbol} balance. Need ${requiredAmount} ${token.symbol}, have ${tokenBalance.balance.toFixed(6)} ${token.symbol}`\n );\n }\n \n if (!hasEnoughForGas) {\n const gasTokenSymbol = nativeBalance?.symbol || this.getNativeTokenSymbol(networkShortName);\n if (token.contractAddress) {\n validationResult.errors.push(\n `Insufficient ${gasTokenSymbol} for gas fees. Need ~${estimatedGasFee.toFixed(6)} ${gasTokenSymbol}, have ${nativeBalance.balance.toFixed(6)} ${gasTokenSymbol}`\n );\n } else {\n validationResult.errors.push(\n `Insufficient ${gasTokenSymbol} for payment + gas. Need ${(requiredAmount + estimatedGasFee).toFixed(6)} ${gasTokenSymbol} total, have ${tokenBalance.balance.toFixed(6)} ${gasTokenSymbol}`\n );\n }\n }\n \n console.log(`✅ Balance validation complete:`, validationResult);\n return validationResult;\n \n } catch (error) {\n console.error(`❌ Balance validation failed:`, error);\n return {\n isValid: false,\n errors: [`Failed to check balance: ${error.message}`],\n tokenBalance: null,\n nativeBalance: null\n };\n }\n }\n\n // Estimate gas fee for the transaction\n estimateGasFee(networkShortName, isERC20 = false) {\n // Conservative gas fee estimates (in native token)\n const gasEstimates = {\n ethereum: isERC20 ? 0.001 : 0.0005, // ETH - higher for ERC-20\n bsc: isERC20 ? 0.0005 : 0.0003, // BNB - cheaper than ETH\n polygon: isERC20 ? 0.01 : 0.005, // MATIC - very cheap\n arbitrum: isERC20 ? 0.0003 : 0.0002, // ETH on L2 - very cheap\n optimism: isERC20 ? 0.0003 : 0.0002, // ETH on L2 - very cheap\n avalanche: isERC20 ? 0.001 : 0.0005 // AVAX - moderate fees\n };\n \n return gasEstimates[networkShortName] || 0.001; // Default conservative estimate\n }\n\n // Get native token symbol for network\n getNativeTokenSymbol(networkShortName) {\n const nativeTokens = {\n ethereum: 'ETH',\n bsc: 'BNB',\n polygon: 'MATIC',\n arbitrum: 'ETH',\n optimism: 'ETH',\n avalanche: 'AVAX'\n };\n \n return nativeTokens[networkShortName] || 'ETH';\n }\n\n // Quick balance check (just returns balance, no validation)\n async getBalance(walletAddress, token, networkShortName) {\n if (token.contractAddress) {\n return await this.checkTokenBalance(walletAddress, token.contractAddress, networkShortName);\n } else {\n return await this.checkNativeBalance(walletAddress, networkShortName);\n }\n }\n\n // Format balance for display\n formatBalance(balance, symbol, decimals = 6) {\n if (balance === null || balance === undefined) return 'Unknown';\n \n if (balance === 0) return `0 ${symbol}`;\n \n // Show more decimals for small amounts\n if (balance < 0.001) {\n return `${balance.toFixed(8)} ${symbol}`;\n } else if (balance < 1) {\n return `${balance.toFixed(6)} ${symbol}`;\n } else {\n return `${balance.toFixed(4)} ${symbol}`;\n }\n }\n\n // Check multiple token balances at once\n async checkMultipleBalances(walletAddress, tokens, networkShortName) {\n try {\n const balancePromises = tokens.map(token => \n this.getBalance(walletAddress, token, networkShortName)\n .catch(error => ({\n error: error.message,\n symbol: token.symbol,\n balance: 0\n }))\n );\n \n const results = await Promise.all(balancePromises);\n return results;\n } catch (error) {\n console.error('❌ Failed to check multiple balances:', error);\n throw error;\n }\n }\n}\n\n// Singleton instance\nconst balanceChecker = new BalanceChecker();\n\n// Export both the class and instance\nexport { BalanceChecker, balanceChecker };\nexport default balanceChecker;","import React, { useState, useEffect, useRef } from 'react';\nimport QRCode from 'qrcode';\nimport balanceChecker from '../utils/balanceChecker';\n\n// Simple Payment API (reusing same structure)\nclass SimplePaymentAPI {\n constructor(baseURL, apiKey, apiSecret) {\n this.baseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;\n this.apiKey = apiKey;\n this.apiSecret = apiSecret;\n }\n\n async request(endpoint, options = {}) {\n const url = `${this.baseURL}${endpoint}`;\n const headers = {\n 'Content-Type': 'application/json',\n 'X-API-Key': this.apiKey,\n 'X-API-Secret': this.apiSecret,\n ...options.headers\n };\n\n const response = await fetch(url, {\n ...options,\n headers\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new Error(error.error || `HTTP ${response.status}`);\n }\n\n return response.json();\n }\n\n async getNetworks() {\n try {\n return await this.request('/api/networks');\n } catch (error) {\n console.error('Failed to fetch networks:', error);\n return {\n networks: [\n { id: '1', name: 'Ethereum', shortName: 'ethereum', chainId: '0x1', type: 'ethereum' },\n { id: '56', name: 'BSC', shortName: 'bsc', chainId: '0x38', type: 'bsc' },\n { id: '137', name: 'Polygon', shortName: 'polygon', chainId: '0x89', type: 'polygon' },\n { id: '42161', name: 'Arbitrum', shortName: 'arbitrum', chainId: '0xa4b1', type: 'arbitrum' },\n { id: '10', name: 'Optimism', shortName: 'optimism', chainId: '0xa', type: 'optimism' },\n { id: '43114', name: 'Avalanche', shortName: 'avalanche', chainId: '0xa86a', type: 'avalanche' },\n { id: '42220', name: 'Celo', shortName: 'celo', chainId: '0xa4ec', type: 'celo' },\n { id: '8453', name: 'Base', shortName: 'base', chainId: '0x2105', type: 'base' }\n ]\n };\n }\n }\n\n async getTokens() {\n try {\n return await this.request('/api/networks/stablecoins');\n } catch (error) {\n console.error('Failed to fetch tokens:', error);\n return {\n stablecoins: [\n {\n id: '1', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n decimals: 6, networkId: '1',\n Network: { shortName: 'ethereum', name: 'Ethereum' }\n },\n {\n id: '2', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xA0b86a33E641a3FA62e50A9da1CE0647a2bFBC5A',\n decimals: 6, networkId: '1',\n Network: { shortName: 'ethereum', name: 'Ethereum' }\n },\n {\n id: '3', name: 'Binance USD', symbol: 'BUSD',\n contractAddress: '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56',\n decimals: 18, networkId: '56',\n Network: { shortName: 'bsc', name: 'BSC' }\n },\n {\n id: '4', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',\n decimals: 18, networkId: '56',\n Network: { shortName: 'bsc', name: 'BSC' }\n },\n {\n id: '5', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174',\n decimals: 6, networkId: '137',\n Network: { shortName: 'polygon', name: 'Polygon' }\n },\n {\n id: '6', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F',\n decimals: 6, networkId: '137',\n Network: { shortName: 'polygon', name: 'Polygon' }\n },\n \n // Arbitrum Network\n {\n id: '7', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',\n decimals: 6, networkId: '42161',\n Network: { shortName: 'arbitrum', name: 'Arbitrum' }\n },\n {\n id: '8', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n decimals: 6, networkId: '42161',\n Network: { shortName: 'arbitrum', name: 'Arbitrum' }\n },\n \n // Optimism Network\n {\n id: '9', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58',\n decimals: 6, networkId: '10',\n Network: { shortName: 'optimism', name: 'Optimism' }\n },\n {\n id: '10', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n decimals: 6, networkId: '10',\n Network: { shortName: 'optimism', name: 'Optimism' }\n },\n \n // Avalanche Network\n {\n id: '11', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7',\n decimals: 6, networkId: '43114',\n Network: { shortName: 'avalanche', name: 'Avalanche' }\n },\n {\n id: '12', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',\n decimals: 6, networkId: '43114',\n Network: { shortName: 'avalanche', name: 'Avalanche' }\n },\n \n // Celo Network\n {\n id: '13', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e',\n decimals: 6, networkId: '42220',\n Network: { shortName: 'celo', name: 'Celo' }\n },\n {\n id: '14', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xcebA9300f2b948710d2653dD7B07f33A8B32118C',\n decimals: 6, networkId: '42220',\n Network: { shortName: 'celo', name: 'Celo' }\n },\n\n // Base Network\n {\n id: '15', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2',\n decimals: 6, networkId: '8453',\n Network: { shortName: 'base', name: 'Base' }\n },\n {\n id: '16', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n decimals: 6, networkId: '8453',\n Network: { shortName: 'base', name: 'Base' }\n }\n ]\n };\n }\n }\n\n async createPayment(data) {\n return await this.request('/api/payments/create', {\n method: 'POST',\n body: JSON.stringify(data)\n });\n }\n\n async updatePaymentStatus(paymentId, status, transactionHash = null) {\n return await this.request(`/api/payments/${paymentId}/status`, {\n method: 'PUT',\n body: JSON.stringify({ status, transactionHash })\n });\n }\n}\n\n// QR Code Payment Component\nconst QRCodePayment = ({\n apiKey,\n apiSecret,\n apiUrl,\n config,\n onSuccess,\n onError,\n onClose,\n isOpen,\n theme = 'light',\n mode = 'splitpayment', // Always use split payment mode for QR codes\n splitPaymentUrl = 'https://paymentscreen.vercel.app/'\n}) => {\n const [currentStep, setCurrentStep] = useState('network');\n const [networks, setNetworks] = useState([]);\n const [tokens, setTokens] = useState([]);\n const [selectedNetwork, setSelectedNetwork] = useState(null);\n const [selectedToken, setSelectedToken] = useState(null);\n const [paymentData, setPaymentData] = useState(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState('');\n const [qrCodeData, setQrCodeData] = useState('');\n const [qrCodeImage, setQrCodeImage] = useState('');\n const [connectionId, setConnectionId] = useState('');\n const [walletConnected, setWalletConnected] = useState(false);\n const [walletAddress, setWalletAddress] = useState('');\n const [checkingPayment, setCheckingPayment] = useState(false);\n const [balanceValidation, setBalanceValidation] = useState(null);\n \n const api = useRef(new SimplePaymentAPI(apiUrl, apiKey, apiSecret));\n const checkInterval = useRef(null);\n\n useEffect(() => {\n if (isOpen) {\n loadData();\n resetState();\n }\n return () => {\n if (checkInterval.current) {\n clearInterval(checkInterval.current);\n }\n };\n }, [isOpen]);\n\n const resetState = () => {\n setCurrentStep('network');\n setSelectedNetwork(null);\n setSelectedToken(null);\n setPaymentData(null);\n setError('');\n setQrCodeData('');\n setQrCodeImage('');\n setConnectionId('');\n setWalletConnected(false);\n setWalletAddress('');\n setCheckingPayment(false);\n setBalanceValidation(null);\n if (checkInterval.current) {\n clearInterval(checkInterval.current);\n }\n };\n\n const loadData = async () => {\n try {\n setLoading(true);\n setError('');\n \n const [networksRes, tokensRes] = await Promise.all([\n api.current.getNetworks(),\n api.current.getTokens()\n ]);\n \n setNetworks(networksRes.networks || []);\n setTokens(tokensRes.stablecoins || []);\n \n } catch (err) {\n console.error('Failed to load data:', err);\n setError('Failed to load payment options.');\n } finally {\n setLoading(false);\n }\n };\n\n const createPayment = async () => {\n try {\n setLoading(true);\n setError('');\n \n const paymentPayload = {\n amount: config.amount,\n currency: selectedToken.symbol,\n network: selectedNetwork.shortName,\n customerEmail: config.customerEmail,\n callbackUrl: config.callbackUrl,\n metadata: {\n ...config.metadata,\n merchantWalletAddresses: config.merchantWalletAddresses,\n paymentMethod: 'qr_code',\n selectedNetwork: selectedNetwork.shortName,\n selectedToken: selectedToken.symbol\n }\n };\n\n const payment = await api.current.createPayment(paymentPayload);\n setPaymentData(payment.payment);\n \n // Generate connection ID for this payment session\n const connId = `qr_${payment.payment.id}_${Date.now()}`;\n setConnectionId(connId);\n \n // Generate QR code with payment details\n await generateQRCode(payment.payment, connId);\n \n setCurrentStep('scan');\n \n } catch (err) {\n console.error('Payment creation failed:', err);\n setError(err.message);\n } finally {\n setLoading(false);\n }\n };\n\n // Helper function to convert amounts to base units (no floating point)\n const toBaseUnits = (amountStr, decimals) => {\n const [intPart, fracPart = ''] = String(amountStr).split('.');\n const frac = (fracPart + '0'.repeat(decimals)).slice(0, decimals);\n const raw = (intPart || '0') + frac;\n return BigInt(raw.replace(/^0+/, '') || '0').toString();\n };\n\n // Build EIP-681 compliant URI for wallet compatibility\n const buildEip681 = ({ recipient, token, network, totalAmount }) => {\n // 1) Convert chain ID to decimal\n const chainId = typeof network.chainId === 'string' && network.chainId.startsWith('0x')\n ? parseInt(network.chainId, 16)\n : Number(network.chainId);\n \n if (!Number.isFinite(chainId)) {\n throw new Error(`Invalid chain ID: ${network.chainId}`);\n }\n\n // 2) Validate required fields\n if (!recipient) throw new Error(`No merchant address configured for ${network.shortName}`);\n if (!token?.contractAddress) throw new Error('Missing token contract address');\n if (totalAmount == null) throw new Error('Missing payment amount');\n\n // 3) Convert amount to base units using token decimals\n const amountBase = toBaseUnits(String(totalAmount), token.decimals ?? 18);\n\n // 4) Build EIP-681 URI for ERC-20 transfer(address,uint256)\n return `ethereum:${token.contractAddress}@${chainId}/transfer?address=${recipient}&uint256=${amountBase}`;\n };\n\n // Generate Split Payment QR with backend record creation\n const generateSplitPaymentQRDirect = async (token) => {\n try {\n setLoading(true);\n setError('');\n\n // First create payment record in backend (same as before)\n const paymentPayload = {\n amount: config.amount,\n currency: token.symbol,\n network: selectedNetwork.shortName,\n customerEmail: config.customerEmail,\n callbackUrl: config.callbackUrl,\n metadata: {\n ...config.metadata,\n merchantWalletAddresses: config.merchantWalletAddresses,\n paymentMethod: 'split_payment_qr',\n selectedNetwork: selectedNetwork.shortName,\n selectedToken: token.symbol\n }\n };\n\n const payment = await api.current.createPayment(paymentPayload);\n setPaymentData(payment.payment);\n\n const contractAddress = config.merchantWalletAddresses?.splitPaymentContract ||\n config.merchantWalletAddresses?.[selectedNetwork.shortName];\n\n if (!contractAddress) {\n throw new Error('Split payment contract address not found in config');\n }\n\n // Generate payment screen URL instead of EIP-681\n const params = new URLSearchParams({\n merchant: config.merchantName || 'Coinley Merchant',\n amount: payment.payment.totalAmount.toString(),\n productAmount: (payment.payment.totalAmount * 0.95).toFixed(2),\n platformFee: (payment.payment.totalAmount * 0.03).toFixed(2),\n networkFee: (payment.payment.totalAmount * 0.02).toFixed(2),\n token: token.symbol,\n network: selectedNetwork.name,\n merchantAddress: contractAddress,\n paymentId: payment.payment.id // Include payment ID for backend tracking\n });\n\n const splitPaymentUri = splitPaymentUrl + '?' + params.toString();\n setQrCodeData(splitPaymentUri);\n\n // Generate QR code image\n const qrImage = await QRCode.toDataURL(splitPaymentUri, {\n width: 256,\n margin: 2,\n color: {\n dark: '#7c3aed',\n light: '#ffffff'\n }\n });\n\n setQrCodeImage(qrImage);\n setCurrentStep('scan');\n\n console.log('🔗 Split Payment QR Code generated with backend record:', splitPaymentUri);\n console.log('📋 Payment ID:', payment.payment.id);\n\n } catch (error) {\n console.error('❌ Failed to generate split payment QR code:', error);\n setError(error.message || 'Failed to generate split payment QR code');\n } finally {\n setLoading(false);\n }\n };\n\n // Generate Split Payment QR (redirects to payment screen)\n const generateSplitPaymentQR = async (payment) => {\n try {\n const contractAddress = config.merchantWalletAddresses?.splitPaymentContract ||\n config.merchantWalletAddresses?.[selectedNetwork.shortName];\n\n if (!contractAddress) {\n throw new Error('Split payment contract address not found');\n }\n\n // Build payment screen URL with parameters\n const params = new URLSearchParams({\n merchant: config.merchantName || 'Coinley Merchant',\n amount: payment.totalAmount.toString(),\n productAmount: (payment.totalAmount * 0.95).toFixed(2),\n platformFee: (payment.totalAmount * 0.03).toFixed(2),\n networkFee: (payment.totalAmount * 0.02).toFixed(2),\n token: selectedToken.symbol,\n network: selectedNetwork.name,\n merchantAddress: contractAddress\n });\n\n const splitPaymentUri = splitPaymentUrl + '?' + params.toString();\n setQrCodeData(splitPaymentUri);\n\n // Generate QR code image\n const qrImage = await QRCode.toDataURL(splitPaymentUri, {\n width: 256,\n margin: 2,\n color: {\n dark: '#7c3aed',\n light: '#ffffff'\n }\n });\n\n setQrCodeImage(qrImage);\n\n console.log('🔗 Split Payment QR Code generated:', splitPaymentUri);\n console.log('📋 Payment ID:', payment.id);\n\n } catch (error) {\n console.error('❌ Failed to generate split payment QR code:', error);\n setError(error.message || 'Failed to generate split payment QR code');\n }\n };\n\n const generateQRCode = async (payment, connId) => {\n try {\n if (mode === 'splitpayment') {\n // Generate split payment QR (redirects to payment screen)\n await generateSplitPaymentQR(payment);\n } else {\n // Generate wallet QR (EIP-681 format)\n const recipient = config.merchantWalletAddresses?.[selectedNetwork.shortName];\n\n // Build standards-compliant EIP-681 URI\n const eip681Uri = buildEip681({\n recipient,\n token: selectedToken,\n network: selectedNetwork,\n totalAmount: payment.totalAmount\n });\n\n setQrCodeData(eip681Uri);\n\n // Generate QR code image\n const qrImage = await QRCode.toDataURL(eip681Uri, {\n width: 256,\n margin: 2,\n color: {\n dark: theme === 'dark' ? '#FFFFFF' : '#000000',\n light: theme === 'dark' ? '#000000' : '#FFFFFF'\n }\n });\n\n setQrCodeImage(qrImage);\n\n console.log('🔍 EIP-681 QR Code generated:', eip681Uri);\n console.log('📋 Payment ID:', payment.id);\n }\n\n } catch (error) {\n console.error('❌ Failed to generate QR code:', error);\n setError(error.message || 'Failed to generate QR code');\n }\n };\n\n // Mock wallet connection via QR scan (simulate mobile wallet scanning)\n const simulateWalletScan = async () => {\n try {\n setLoading(true);\n setError('');\n \n // Simulate wallet address from scan\n const mockWalletAddress = '0x742d35Cc6634C0532925a3b8D9a5C7C47C77E4';\n setWalletAddress(mockWalletAddress);\n setWalletConnected(true);\n \n // Check balance\n await checkWalletBalance(mockWalletAddress);\n \n setCurrentStep('confirm');\n \n } catch (error) {\n console.error('❌ Wallet simulation failed:', error);\n setError('Failed to simulate wallet connection');\n } finally {\n setLoading(false);\n }\n };\n\n const checkWalletBalance = async (address) => {\n if (!selectedToken || !selectedNetwork || !paymentData) {\n return false;\n }\n\n try {\n console.log('🔍 Checking QR wallet balance...');\n \n const validation = await balanceChecker.validateBalance(\n address,\n selectedToken,\n paymentData.totalAmount,\n selectedNetwork.shortName,\n true\n );\n\n setBalanceValidation(validation);\n\n if (!validation.isValid) {\n setError(`Insufficient balance: ${validation.errors.join(', ')}`);\n return false;\n }\n\n console.log('✅ QR balance validation passed');\n return true;\n\n } catch (error) {\n console.error('❌ QR balance check failed:', error);\n setError(`Failed to check balance: ${error.message}`);\n return false;\n }\n };\n\n // Simulate transaction confirmation\n const simulateTransaction = async () => {\n try {\n setCheckingPayment(true);\n setError('');\n \n // Simulate transaction hash\n const mockTxHash = `0x${Math.random().toString(16).substring(2, 66)}`;\n \n // Simulate delay for blockchain confirmation\n await new Promise(resolve => setTimeout(resolve, 3000));\n \n console.log('✅ QR payment transaction confirmed:', mockTxHash);\n setCurrentStep('success');\n \n onSuccess?.(paymentData.id, mockTxHash, {\n network: selectedNetwork.name,\n token: selectedToken.symbol,\n amount: paymentData.totalAmount,\n method: 'qr_code',\n walletAddress: walletAddress\n });\n\n } catch (error) {\n console.error('❌ QR transaction failed:', error);\n setError('Transaction confirmation failed');\n } finally {\n setCheckingPayment(false);\n }\n };\n\n if (!isOpen) return null;\n\n const isDark = theme === 'dark';\n\n return (\n <div className=\"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50\">\n <div className={`rounded-lg shadow-xl max-w-md w-full mx-4 ${isDark ? 'bg-gray-900 text-white' : 'bg-white text-gray-900'}`}>\n \n {/* Header */}\n <div className={`p-4 border-b flex justify-between items-center ${isDark ? 'border-gray-700' : 'border-gray-200'}`}>\n <div className=\"text-center flex-1\">\n <h2 className=\"text-lg font-semibold\">\n {mode === 'splitpayment' ? 'Split Payment QR' : 'QR Code Payment'}\n </h2>\n {config.amount && (\n <p className=\"text-2xl font-bold text-purple-600\">${config.amount.toFixed(2)}</p>\n )}\n <p className=\"text-xs text-blue-600\">\n {mode === 'splitpayment'\n ? '📱 Scan to redirect to payment screen'\n : '📱 Scan with mobile wallet'\n }\n </p>\n </div>\n <button\n onClick={onClose}\n className={`ml-4 text-gray-500 hover:text-gray-700 ${isDark ? 'hover:text-gray-300' : ''}`}\n >\n ✕\n </button>\n </div>\n\n {/* Content */}\n <div className=\"p-4 min-h-[400px]\">\n {error && (\n <div className=\"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200\">\n {error}\n <button \n onClick={() => setError('')}\n className=\"ml-2 text-red-500 hover:text-red-700\"\n >\n ✕\n </button>\n </div>\n )}\n\n {/* Step 1: Select Network */}\n {currentStep === 'network' && (\n <div className=\"space-y-4\">\n <h3 className=\"font-medium text-center\">Select Network</h3>\n <div className=\"space-y-2\">\n {networks.map((network) => {\n const hasAddress = config.merchantWalletAddresses?.[network.shortName];\n return (\n <button\n key={network.id}\n onClick={() => { setSelectedNetwork(network); setCurrentStep('token'); }}\n disabled={!hasAddress}\n className={`w-full p-3 border rounded-lg text-left transition-colors ${\n hasAddress \n ? `hover:border-purple-500 ${isDark ? 'border-gray-600 hover:bg-gray-800' : 'border-gray-200 hover:bg-gray-50'}`\n : `opacity-50 cursor-not-allowed ${isDark ? 'border-gray-700' : 'border-gray-100'}`\n }`}\n >\n <div className=\"font-medium\">{network.name}</div>\n <div className={`text-sm ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>\n {network.shortName.toUpperCase()}\n {!hasAddress && ' (No merchant address configured)'}\n </div>\n </button>\n );\n })}\n </div>\n </div>\n )}\n\n {/* Step 2: Select Token */}\n {currentStep === 'token' && (\n <div className=\"space-y-4\">\n <div className=\"flex items-center space-x-2\">\n <button \n onClick={() => setCurrentStep('network')} \n className={`${isDark ? 'text-gray-400 hover:text-gray-200' : 'text-gray-500 hover:text-gray-700'}`}\n >\n ←\n </button>\n <h3 className=\"font-medium\">Select Token on {selectedNetwork?.name}</h3>\n </div>\n <div className=\"space-y-2\">\n {tokens\n .filter(token => token.Network?.shortName === selectedNetwork?.shortName)\n .map((token) => (\n <button\n key={token.id}\n onClick={() => {\n setSelectedToken(token);\n generateSplitPaymentQRDirect(token);\n }}\n disabled={loading}\n className={`w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors disabled:opacity-50 ${isDark ? 'border-gray-600 hover:bg-gray-800' : 'border-gray-200 hover:bg-gray-50'}`}\n >\n <div className=\"font-medium\">{token.name}</div>\n <div className={`text-sm ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>{token.symbol}</div>\n </button>\n ))\n }\n </div>\n </div>\n )}\n\n {/* Step 3: Scan QR Code */}\n {currentStep === 'scan' && (\n <div className=\"space-y-4\">\n <div className=\"text-center\">\n <h3 className=\"font-medium mb-4\">\n {mode === 'splitpayment'\n ? 'Scan QR Code to Open Payment Screen'\n : 'Scan QR Code with Mobile Wallet'\n }\n </h3>\n\n {qrCodeImage ? (\n <div className=\"flex flex-col items-center space-y-4\">\n <div className={`p-4 rounded-lg ${isDark ? 'bg-gray-800' : 'bg-gray-50'}`}>\n <img\n src={qrCodeImage}\n alt=\"Payment QR Code\"\n className=\"mx-auto\"\n style={{ width: '200px', height: '200px' }}\n />\n </div>\n\n <div className={`text-sm space-y-1 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>\n <div className=\"flex justify-between\">\n <span>Amount:</span>\n <span className=\"font-medium\">{paymentData?.totalAmount} {selectedToken?.symbol}</span>\n </div>\n <div className=\"flex justify-between\">\n <span>Network:</span>\n <span className=\"font-medium\">{selectedNetwork?.name}</span>\n </div>\n {mode === 'splitpayment' && (\n <div className=\"flex justify-between\">\n <span>Merchant:</span>\n <span className=\"font-medium\">{config.merchantName || 'Coinley Merchant'}</span>\n </div>\n )}\n </div>\n\n <div className={`p-3 rounded-lg text-xs ${isDark ? 'bg-blue-900 text-blue-200' : 'bg-blue-50 text-blue-600'}`}>\n {mode === 'splitpayment' ? (\n <>\n 📱 Scan this QR code with your mobile wallet to open the payment screen.\n <br />The payment screen will auto-connect your wallet and execute the split payment.\n </>\n ) : (\n '📱 Open your mobile wallet and scan this QR code to connect and pay'\n )}\n </div>\n\n {/* Test buttons */}\n {mode === 'splitpayment' ? (\n <button\n onClick={() => window.open(qrCodeData, '_blank')}\n className=\"w-full bg-purple-600 text-white py-2 px-4 rounded hover:bg-purple-700 text-sm\"\n >\n 🔗 Test Payment Screen (Opens in new tab)\n </button>\n ) : (\n <button\n onClick={simulateWalletScan}\n disabled={loading}\n className=\"w-full bg-gray-600 text-white py-2 px-4 rounded hover:bg-gray-700 disabled:opacity-50 text-sm\"\n >\n {loading ? 'Connecting...' : '🧪 Simulate Wallet Scan (Test)'}\n </button>\n )}\n </div>\n ) : (\n <div className=\"flex items-center justify-center py-8\">\n <div className=\"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600\"></div>\n <span className=\"ml-2\">Generating QR Code...</span>\n </div>\n )}\n </div>\n </div>\n )}\n\n {/* Step 4: Confirm Payment */}\n {currentStep === 'confirm' && (\n <div className=\"space-y-4\">\n <div className=\"text-center\">\n <div className=\"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4\">\n <span className=\"text-2xl\">📱</span>\n </div>\n <h3 className=\"font-medium\">Mobile Wallet Connected</h3>\n <p className={`text-sm mt-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>\n Ready to complete payment\n </p>\n </div>\n \n <div className=\"space-y-4\">\n <div className=\"p-3 bg-green-50 rounded-lg border border-green-200\">\n <p className=\"text-green-600 text-sm font-medium\">✅ Wallet Connected</p>\n <p className=\"font-mono text-xs text-green-700 mt-1\">\n {walletAddress?.slice(0, 6)}...{walletAddress?.slice(-4)}\n </p>\n </div>\n\n {balanceValidation && (\n <div className={`p-3 rounded-lg border ${\n balanceValidation.isValid \n ? 'bg-green-50 border-green-200' \n : 'bg-red-50 border-red-200'\n }`}>\n <div className=\"space-y-2 text-sm\">\n <div className=\"flex justify-between\">\n <span>Required:</span>\n <span className=\"font-medium\">{paymentData?.totalAmount} {selectedToken?.symbol}</span>\n </div>\n <div className=\"flex justify-between\">\n <span>Your Balance:</span>\n <span className={`font-medium ${\n balanceValidation.hasEnoughTokens ? 'text-green-600' : 'text-red-600'\n }`}>\n {balanceChecker.formatBalance(\n balanceValidation.tokenBalance?.balance, \n selectedToken?.symbol\n )}\n </span>\n </div>\n {balanceValidation.nativeBalance && (\n <div className=\"flex justify-between\">\n <span>Gas Balance:</span>\n <span className={`font-medium ${\n balanceValidation.hasEnoughForGas ? 'text-green-600' : 'text-red-600'\n }`}>\n {balanceChecker.formatBalance(\n balanceValidation.nativeBalance.balance, \n balanceValidation.nativeBalance.symbol\n )}\n </span>\n </div>\n )}\n </div>\n </div>\n )}\n\n <button\n onClick={simulateTransaction}\n disabled={checkingPayment || !balanceValidation?.isValid}\n className=\"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium\"\n >\n {checkingPayment ? 'Processing Payment...' : \n !balanceValidation?.isValid ? 'Insufficient Balance' :\n `Confirm Payment of ${paymentData?.totalAmount} ${selectedToken?.symbol}`}\n </button>\n </div>\n </div>\n )}\n\n {/* Success */}\n {currentStep === 'success' && (\n <div className=\"text-center space-y-4\">\n <div className=\"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto\">\n <span className=\"text-2xl\">✅</span>\n </div>\n <h3 className=\"font-medium text-green-600\">Payment Successful!</h3>\n <p className={`text-sm ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>\n Transaction completed via QR code scan\n </p>\n <button\n onClick={onClose}\n className=\"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 font-medium\"\n >\n Close\n </button>\n </div>\n )}\n\n {/* Loading */}\n {loading && currentStep !== 'scan' && currentStep !== 'confirm' && (\n <div className=\"flex items-center justify-center py-8\">\n <div className=\"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600\"></div>\n </div>\n )}\n </div>\n </div>\n </div>\n );\n};\n\nexport default QRCodePayment;","/**\n * Coinley Vanilla JS SDK\n * Version: 2.0.0\n *\n * A framework-agnostic payment SDK for cryptocurrency payments.\n * Works with vanilla JavaScript, WordPress, and any other platform.\n *\n * @example\n * const coinley = new CoinleyVanilla({\n * apiKey: 'your-api-key',\n * apiSecret: 'your-api-secret',\n * apiUrl: 'https://hub.coinley.io/api',\n * theme: 'light',\n * debug: false\n * });\n *\n * coinley.open({\n * amount: 100.00,\n * customerEmail: 'customer@example.com',\n * merchantName: 'My Store',\n * merchantWalletAddresses: {\n * ethereum: '0x...',\n * bsc: '0x...',\n * polygon: '0x...',\n * arbitrum: '0x...',\n * optimism: '0x...',\n * avalanche: '0x...',\n * celo: '0x...',\n * base: '0x...'\n * },\n * metadata: { orderId: '12345' }\n * }, {\n * onSuccess: (paymentId, txHash, details) => { ... },\n * onError: (error) => { ... },\n * onClose: () => { ... }\n * });\n */\n\nimport React from 'react';\nimport { createRoot } from 'react-dom/client';\nimport EnhancedSimpleCoinleyPayment from '../components/EnhancedSimpleCoinleyPayment';\nimport '../styles/index.css';\n\n/**\n * CoinleyVanilla - Vanilla JavaScript SDK for Coinley Payments\n */\nclass CoinleyVanilla {\n /**\n * Initialize Coinley payment SDK\n * @param {Object} config - SDK configuration\n * @param {string} config.apiKey - Merchant API key (required)\n * @param {string} config.apiSecret - Merchant API secret (required)\n * @param {string} config.apiUrl - API base URL (required)\n * @param {string} [config.theme='light'] - UI theme ('light' or 'dark')\n * @param {boolean} [config.debug=false] - Enable debug logging\n */\n constructor(config = {}) {\n // Validate required configuration\n if (!config.apiKey) {\n throw new Error('CoinleyVanilla: apiKey is required');\n }\n if (!config.apiSecret) {\n throw new Error('CoinleyVanilla: apiSecret is required');\n }\n if (!config.apiUrl) {\n throw new Error('CoinleyVanilla: apiUrl is required');\n }\n\n // Store configuration with defaults\n this.config = {\n apiKey: config.apiKey,\n apiSecret: config.apiSecret,\n apiUrl: config.apiUrl.replace(/\\/$/, ''), // Remove trailing slash\n theme: config.theme || 'light',\n debug: config.debug || false,\n ...config\n };\n\n // Internal state\n this.isOpen = false;\n this.root = null;\n this.container = null;\n this.callbacks = {};\n this.currentPayment = null;\n\n // Log initialization\n if (this.config.debug) {\n console.log('✅ CoinleyVanilla SDK initialized', {\n apiUrl: this.config.apiUrl,\n theme: this.config.theme,\n version: '2.0.0'\n });\n }\n }\n\n /**\n * Open payment modal\n * @param {Object} paymentConfig - Payment configuration\n * @param {number} paymentConfig.amount - Payment amount (required)\n * @param {string} paymentConfig.customerEmail - Customer email (required)\n * @param {string} [paymentConfig.merchantName] - Merchant display name\n * @param {string} [paymentConfig.callbackUrl] - Webhook callback URL\n * @param {Object} paymentConfig.merchantWalletAddresses - Network-specific wallet addresses\n * @param {string} [paymentConfig.preferredNetwork] - Default network to select\n * @param {string} [paymentConfig.preferredCurrency] - Default token to select\n * @param {Object} [paymentConfig.metadata] - Custom metadata to attach\n * @param {Object} callbacks - Event callbacks\n * @param {Function} callbacks.onSuccess - Called when payment succeeds (paymentId, txHash, details)\n * @param {Function} callbacks.onError - Called when payment fails (error)\n * @param {Function} callbacks.onClose - Called when modal closes\n */\n open(paymentConfig, callbacks = {}) {\n // Check if already open\n if (this.isOpen) {\n console.warn('⚠️ CoinleyVanilla: Payment modal is already open');\n return;\n }\n\n try {\n // Validate payment configuration\n this._validatePaymentConfig(paymentConfig);\n\n // Store callbacks and payment config\n this.callbacks = callbacks;\n this.currentPayment = paymentConfig;\n\n // Create container for React component\n this._createContainer();\n\n // Create React root and render component\n this.root = createRoot(this.container);\n this.isOpen = true;\n\n // Render payment component\n this.root.render(\n React.createElement(EnhancedSimpleCoinleyPayment, {\n apiKey: this.config.apiKey,\n apiSecret: this.config.apiSecret,\n apiUrl: this.config.apiUrl,\n isOpen: true,\n theme: this.config.theme,\n config: {\n amount: paymentConfig.amount,\n customerEmail: paymentConfig.customerEmail,\n merchantName: paymentConfig.merchantName || 'Merchant',\n callbackUrl: paymentConfig.callbackUrl || this._getDefaultCallbackUrl(),\n merchantWalletAddresses: paymentConfig.merchantWalletAddresses || {},\n preferredNetwork: paymentConfig.preferredNetwork,\n preferredCurrency: paymentConfig.preferredCurrency,\n metadata: {\n ...paymentConfig.metadata,\n source: 'vanilla-sdk',\n sdkVersion: '2.0.0',\n timestamp: new Date().toISOString()\n }\n },\n onSuccess: this._handleSuccess.bind(this),\n onError: this._handleError.bind(this),\n onClose: this._handleClose.bind(this)\n })\n );\n\n if (this.config.debug) {\n console.log('🚀 CoinleyVanilla: Payment modal opened', {\n amount: paymentConfig.amount,\n customerEmail: paymentConfig.customerEmail,\n networks: Object.keys(paymentConfig.merchantWalletAddresses || {})\n });\n }\n\n } catch (error) {\n console.error('❌ CoinleyVanilla: Failed to open payment modal', error);\n\n if (callbacks.onError) {\n callbacks.onError(error.message || 'Failed to open payment modal');\n }\n }\n }\n\n /**\n * Close payment modal programmatically\n */\n close() {\n if (!this.isOpen) {\n return;\n }\n\n this._cleanup();\n\n if (this.config.debug) {\n console.log('🔒 CoinleyVanilla: Payment modal closed');\n }\n }\n\n /**\n * Check if payment modal is currently open\n * @returns {boolean}\n */\n isPaymentOpen() {\n return this.isOpen;\n }\n\n /**\n * Update SDK configuration\n * @param {Object} newConfig - Configuration updates\n */\n updateConfig(newConfig) {\n this.config = { ...this.config, ...newConfig };\n\n if (this.config.debug) {\n console.log('🔧 CoinleyVanilla: Configuration updated', this.config);\n }\n }\n\n /**\n * Get current configuration (read-only)\n * @returns {Object}\n */\n getConfig() {\n return { ...this.config };\n }\n\n /**\n * Get current payment details\n * @returns {Object|null}\n */\n getCurrentPayment() {\n return this.currentPayment ? { ...this.currentPayment } : null;\n }\n\n // ==================== PRIVATE METHODS ====================\n\n /**\n * Validate payment configuration\n * @private\n */\n _validatePaymentConfig(config) {\n if (!config) {\n throw new Error('Payment configuration is required');\n }\n\n if (!config.amount || typeof config.amount !== 'number' || config.amount <= 0) {\n throw new Error('Valid amount (number > 0) is required');\n }\n\n if (!config.customerEmail || typeof config.customerEmail !== 'string') {\n throw new Error('Customer email is required');\n }\n\n // Email format validation\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n if (!emailRegex.test(config.customerEmail)) {\n throw new Error('Invalid email format');\n }\n\n // Validate merchant wallet addresses if provided\n if (config.merchantWalletAddresses) {\n if (typeof config.merchantWalletAddresses !== 'object') {\n throw new Error('merchantWalletAddresses must be an object');\n }\n\n const walletCount = Object.keys(config.merchantWalletAddresses).length;\n if (walletCount === 0) {\n console.warn('⚠️ CoinleyVanilla: No merchant wallet addresses provided. Networks will be fetched from backend.');\n }\n }\n }\n\n /**\n * Create DOM container for payment modal\n * @private\n */\n _createContainer() {\n if (this.container) {\n return; // Already exists\n }\n\n this.container = document.createElement('div');\n this.container.id = 'coinley-payment-container';\n this.container.style.cssText = `\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 999999;\n `;\n\n document.body.appendChild(this.container);\n }\n\n /**\n * Get default callback URL\n * @private\n */\n _getDefaultCallbackUrl() {\n if (typeof window !== 'undefined') {\n return `${window.location.origin}/api/webhooks/coinley`;\n }\n return '';\n }\n\n /**\n * Handle successful payment\n * @private\n */\n _handleSuccess(paymentId, transactionHash, paymentDetails) {\n if (this.config.debug) {\n console.log('✅ CoinleyVanilla: Payment successful', {\n paymentId,\n transactionHash,\n details: paymentDetails\n });\n }\n\n if (this.callbacks.onSuccess) {\n this.callbacks.onSuccess(paymentId, transactionHash, paymentDetails);\n }\n\n // Don't auto-close - let component handle it or user calls close()\n }\n\n /**\n * Handle payment error\n * @private\n */\n _handleError(error) {\n if (this.config.debug) {\n console.error('❌ CoinleyVanilla: Payment error', error);\n }\n\n if (this.callbacks.onError) {\n this.callbacks.onError(error);\n }\n }\n\n /**\n * Handle modal close\n * @private\n */\n _handleClose() {\n this._cleanup();\n\n if (this.callbacks.onClose) {\n this.callbacks.onClose();\n }\n }\n\n /**\n * Cleanup resources\n * @private\n */\n _cleanup() {\n this.isOpen = false;\n\n // Unmount React component\n if (this.root) {\n try {\n this.root.unmount();\n } catch (error) {\n console.error('Error unmounting React root:', error);\n }\n this.root = null;\n }\n\n // Remove DOM container\n if (this.container && this.container.parentNode) {\n this.container.parentNode.removeChild(this.container);\n this.container = null;\n }\n\n // Clear current payment\n this.currentPayment = null;\n }\n}\n\n// Export as ES module\nexport default CoinleyVanilla;\n\n// Make available globally for vanilla JS/WordPress usage\nif (typeof window !== 'undefined') {\n window.CoinleyVanilla = CoinleyVanilla;\n\n // Auto-initialize from script tag data attributes\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', autoInitialize);\n } else {\n autoInitialize();\n }\n}\n\n/**\n * Auto-initialize from script tag attributes\n * @private\n */\nfunction autoInitialize() {\n const scripts = document.querySelectorAll('script[src*=\"coinley-vanilla\"]');\n\n scripts.forEach(script => {\n const apiKey = script.getAttribute('data-api-key');\n const apiSecret = script.getAttribute('data-api-secret');\n const apiUrl = script.getAttribute('data-api-url');\n const theme = script.getAttribute('data-theme') || 'light';\n const debug = script.hasAttribute('data-debug');\n\n if (apiKey && apiSecret && apiUrl) {\n try {\n window.coinley = new CoinleyVanilla({\n apiKey,\n apiSecret,\n apiUrl,\n theme,\n debug\n });\n\n console.log('✅ Coinley SDK auto-initialized from script tag');\n } catch (error) {\n console.error('❌ Failed to auto-initialize Coinley SDK:', error);\n }\n }\n });\n}","// Payment QR Generator for Coinley SDK\n// Generates QR codes that point to the payment screen for split payments\n\nimport QRCode from 'qrcode';\n\nexport class PaymentQRGenerator {\n constructor(basePaymentUrl = 'https://paymentscreen.vercel.app/') {\n this.basePaymentUrl = basePaymentUrl.endsWith('/') ? basePaymentUrl : basePaymentUrl + '/';\n }\n\n /**\n * Generate a payment URL for QR code scanning\n * @param {Object} paymentData - Payment configuration\n * @param {string} paymentData.merchant - Merchant name\n * @param {number} paymentData.amount - Total amount\n * @param {number} paymentData.productAmount - Product amount (before fees)\n * @param {number} paymentData.platformFee - Platform fee\n * @param {number} paymentData.networkFee - Network fee\n * @param {string} paymentData.token - Token symbol (USDC, USDT, etc.)\n * @param {string} paymentData.network - Network name\n * @param {string} paymentData.merchantAddress - Smart contract address for split payment\n * @returns {string} - Payment URL for QR code\n */\n generatePaymentURL(paymentData) {\n const {\n merchant,\n amount,\n productAmount,\n platformFee,\n networkFee,\n token = 'USDC',\n network = 'Ethereum Mainnet',\n merchantAddress\n } = paymentData;\n\n // Validate required fields\n if (!merchant) throw new Error('Merchant name is required');\n if (!amount) throw new Error('Amount is required');\n if (!merchantAddress) throw new Error('Merchant address (smart contract) is required');\n\n // Auto-calculate fees if not provided\n const calculatedProductAmount = productAmount || (amount * 0.95);\n const calculatedPlatformFee = platformFee || (amount * 0.03);\n const calculatedNetworkFee = networkFee || (amount * 0.02);\n\n // Create URL parameters\n const params = new URLSearchParams({\n merchant: merchant,\n amount: amount.toString(),\n productAmount: calculatedProductAmount.toString(),\n platformFee: calculatedPlatformFee.toString(),\n networkFee: calculatedNetworkFee.toString(),\n token: token,\n network: network,\n merchantAddress: merchantAddress\n });\n\n return this.basePaymentUrl + '?' + params.toString();\n }\n\n /**\n * Generate QR code data URL for the payment\n * @param {Object} paymentData - Payment configuration\n * @param {Object} options - QR code options\n * @param {number} options.width - QR code width (default: 300)\n * @param {number} options.margin - QR code margin (default: 2)\n * @param {string} options.colorDark - Dark color (default: '#7c3aed')\n * @param {string} options.colorLight - Light color (default: '#ffffff')\n * @returns {Promise<string>} - QR code data URL\n */\n async generateQRCode(paymentData, options = {}) {\n const {\n width = 300,\n margin = 2,\n colorDark = '#7c3aed',\n colorLight = '#ffffff'\n } = options;\n\n try {\n const paymentURL = this.generatePaymentURL(paymentData);\n\n const qrCodeDataURL = await QRCode.toDataURL(paymentURL, {\n width,\n margin,\n color: {\n dark: colorDark,\n light: colorLight\n }\n });\n\n return {\n qrCodeDataURL,\n paymentURL,\n paymentData: {\n ...paymentData,\n qrCodeUrl: paymentURL\n }\n };\n } catch (error) {\n throw new Error(`Failed to generate QR code: ${error.message}`);\n }\n }\n\n /**\n * Generate QR code as canvas element\n * @param {Object} paymentData - Payment configuration\n * @param {HTMLCanvasElement} canvas - Canvas element to render to\n * @param {Object} options - QR code options\n * @returns {Promise<string>} - Payment URL\n */\n async generateQRCodeToCanvas(paymentData, canvas, options = {}) {\n const {\n width = 300,\n margin = 2,\n colorDark = '#7c3aed',\n colorLight = '#ffffff'\n } = options;\n\n try {\n const paymentURL = this.generatePaymentURL(paymentData);\n\n await QRCode.toCanvas(canvas, paymentURL, {\n width,\n margin,\n color: {\n dark: colorDark,\n light: colorLight\n }\n });\n\n return paymentURL;\n } catch (error) {\n throw new Error(`Failed to generate QR code to canvas: ${error.message}`);\n }\n }\n\n /**\n * Validate payment data structure\n * @param {Object} paymentData - Payment configuration to validate\n * @returns {Object} - Validation result\n */\n validatePaymentData(paymentData) {\n const errors = [];\n const warnings = [];\n\n // Required fields\n if (!paymentData.merchant) errors.push('Merchant name is required');\n if (!paymentData.amount || paymentData.amount <= 0) errors.push('Valid amount is required');\n if (!paymentData.merchantAddress) errors.push('Merchant address (smart contract) is required');\n\n // Address format validation\n if (paymentData.merchantAddress && !/^0x[a-fA-F0-9]{40}$/.test(paymentData.merchantAddress)) {\n errors.push('Invalid Ethereum address format for merchantAddress');\n }\n\n // Amount validation\n if (paymentData.amount > 10000) {\n warnings.push('Large payment amount detected');\n }\n\n // Fee validation\n const totalFees = (paymentData.platformFee || 0) + (paymentData.networkFee || 0);\n if (totalFees > paymentData.amount * 0.1) {\n warnings.push('High fees detected (>10% of total amount)');\n }\n\n return {\n isValid: errors.length === 0,\n errors,\n warnings\n };\n }\n\n /**\n * Create a comprehensive payment QR for SDK usage\n * @param {Object} config - Payment configuration from SDK\n * @returns {Promise<Object>} - Complete QR payment package\n */\n async createPaymentQR(config) {\n const {\n merchantName,\n amount,\n productAmount,\n platformFee,\n networkFee,\n token,\n network,\n merchantWalletAddresses,\n selectedNetwork = 'ethereum',\n ...otherConfig\n } = config;\n\n // Extract smart contract address from merchant wallet addresses\n const merchantAddress = merchantWalletAddresses?.[selectedNetwork] ||\n merchantWalletAddresses?.ethereum ||\n merchantWalletAddresses?.splitPaymentContract;\n\n const paymentData = {\n merchant: merchantName || 'Coinley Merchant',\n amount,\n productAmount,\n platformFee,\n networkFee,\n token: token || 'USDC',\n network: network || 'Ethereum Mainnet',\n merchantAddress,\n ...otherConfig\n };\n\n // Validate payment data\n const validation = this.validatePaymentData(paymentData);\n if (!validation.isValid) {\n throw new Error(`Payment validation failed: ${validation.errors.join(', ')}`);\n }\n\n // Generate QR code\n const qrResult = await this.generateQRCode(paymentData);\n\n return {\n ...qrResult,\n validation,\n instructions: {\n userAction: 'Scan this QR code with your mobile wallet to pay',\n expectedFlow: 'QR Scan → Payment Screen → Wallet Connect → Split Payment → Confirmation',\n supportedWallets: ['MetaMask', 'Trust Wallet', 'Coinbase Wallet', 'WalletConnect compatible wallets']\n }\n };\n }\n}\n\n// Default instance for easy usage\nexport const paymentQR = new PaymentQRGenerator();\n\n// Utility functions for quick access\nexport const generatePaymentQR = (paymentData, options) => {\n return paymentQR.generateQRCode(paymentData, options);\n};\n\nexport const generatePaymentURL = (paymentData) => {\n return paymentQR.generatePaymentURL(paymentData);\n};\n\nexport default PaymentQRGenerator;","\n// src/index.js - Updated to include vanilla exports\n\n// Original React exports (keep these for backward compatibility)\nexport {\n CoinleyProvider,\n CoinleyCheckout,\n ThemeProvider,\n useCoinley\n} from './CoinleyProvider';\n\nexport { PaymentAPI } from './PaymentAPI';\n\n\n// Keep the original simple component (working version)\n// export { default as SimpleCoinleyPayment } from './components/SimpleCoinleyPayment';\n\n// Enhanced component with modern design\nexport { default as EnhancedSimpleCoinleyPayment } from './components/EnhancedSimpleCoinleyPayment';\n\n// QR Code Payment component (supports both wallet and split payment modes)\nexport { default as QRCodePayment } from './components/QRCodePayment';\n\n// Simple provider for both components\nexport const SimpleCoinleyProvider = ({ children, ...props }) => children;\n\n// NEW: Vanilla JavaScript wrapper (for those who want to import it in React too)\nexport { default as CoinleyVanilla } from './vanilla/index';\n\n// NEW: Payment QR Generator for split payments\nexport {\n PaymentQRGenerator,\n paymentQR,\n generatePaymentQR,\n generatePaymentURL\n} from './utils/paymentQRGenerator';\n\n// Import styles\nimport './styles/index.css';\n\n// Version\nexport const VERSION = '0.0.26';\n\n// Utils (keep your existing utils)\nexport const utils = {\n formatAmount: (amount, decimals = 2) => amount.toFixed(decimals),\n \n truncateAddress: (address, startChars = 6, endChars = 4) => {\n if (!address) return '';\n if (address.length <= startChars + endChars) return address;\n return `${address.slice(0, startChars)}...${address.slice(-endChars)}`;\n },\n \n isValidAddress: (address, network) => {\n if (!address) return false;\n \n switch (network.toLowerCase()) {\n case 'ethereum':\n case 'bsc':\n case 'polygon':\n return /^0x[a-fA-F0-9]{40}$/.test(address);\n case 'tron':\n return /^T[a-zA-Z0-9]{33}$/.test(address);\n case 'solana':\n return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);\n default:\n return address.length > 0;\n }\n },\n \n copyToClipboard: async (text) => {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n return false;\n }\n }\n};\n\n// Error classes\nexport class CoinleyError extends Error {\n constructor(message, code) {\n super(message);\n this.name = 'CoinleyError';\n this.code = code;\n }\n}\n\n// Default config\nexport const DEFAULT_CONFIG = {\n theme: 'light',\n debug: false,\n testMode: false,\n autoOpen: false\n};\n\n// Usage examples for documentation\nexport const USAGE_EXAMPLES = {\n // React usage with new publicKey (recommended)\n 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 `,\n\n // Vanilla JavaScript usage\n vanilla: `\n<!-- Include via CDN -->\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 `\n};"],"names":["mainnet","bsc","polygon","arbitrum","optimism","avalanche","celo","base","SimplePaymentAPI","_a","_b","error","size","encoder","toBytes","size_","formatAuthorizationList","isLE","_32n","sha256","sha256n","noble_sha256","version","serializeTransaction","blobs","commitments","proofs","v","formatters","serializeTransaction_","serializers","chainConfig","sourceId","serializeTransaction_op","wagmiConfig","http","fallback","splitPaymentHash","gasFees","selectedToken","paymentData","selectedNetwork","generateQRPaymentURI","generateMobilePaymentDeepLink","token","CoinleyPayment","formatUnits"],"mappings":";;;;;;;;;;;;AAAA,MAAA,OAAe;ACMf,MAAM,0BAA0B;AAChC,MAAM,4BAA4B;AAGlC,MAAM,uBAAuB;AAC7B,QAAQ,IAAI,+BAA+B,oBAAoB;AAC/D,QAAQ,IAAI,sBAAsB,+FAA+F;AACjI,QAAQ,IAAI,sGAAsG;AAClH,QAAQ,IAAI,6FAA6F;AACzG,QAAQ,IAAI,+EAA+E;AAC3F,QAAQ,IAAI,8EAA8E;AAC1F,QAAQ,IAAI,sEAAsE;AAClF,QAAQ,IAAI,yFAAyF;AACrG,QAAQ,IAAI,sFAAsF;AAClG,QAAQ,IAAI,kFAAkF;AAG9F,MAAM,gBAAgB,MAAM;AACxB,QAAM,iBAAiB;AAAA,IACnB,SAAQ;AAAA,IACR,SAAS;AAAA,MACL,cAAc;AAAA,QACV,MAAM;AAAA,QACN,MAAM;AAAA,MACtB;AAAA,IACA,CAAS;AAAA,IACD,eAAe;AAAA,MACX,SAAS;AAAA,MACT,YAAY;AAAA,IACxB,CAAS;AAAA,EACT;AAEI,SAAO;AACX;AAEO,MAA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I;AACxC,aAAO;AAAA,IACT,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAGO,MAAM,qBAAqB,MAAM;AAAA,EACtC,YAAY,SAAS,MAAM;AACzB,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAGY,MAAC,iBAAiB;AAAA,EAC5B,OAAO;AAAA,EACP,OAAO;AAAA,EACP,UAAU;AAAA,EACV,UAAU;AACZ;AAGY,MAAC,iBAAiB;AAAA;AAAA,EAE5B,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2BP,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqCX;","x_google_ignoreList":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78]}
1
+ {"version":3,"file":"index.esm.js","sources":["../src/assets/Logomark.png","../src/components/enhanced-payment/config/wagmiConfig.js","../src/components/enhanced-payment/api/paymentAPI.js","../src/components/enhanced-payment/hooks/usePaymentFlow.js","../src/components/enhanced-payment/config/chainConfig.js","../src/components/enhanced-payment/hooks/useWalletConnection.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/chain/defineChain.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/version.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/base.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/encoding.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/isHex.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/size.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/trim.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/data.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/pad.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/encoding/toHex.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/encoding/toBytes.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/encoding/fromHex.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/formatter.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/transaction.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/block.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/log.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/transactionReceipt.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/formatters/transactionRequest.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/constants/number.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/concat.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/cursor.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/cursor.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/encoding/toRlp.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/constants/unit.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/unit/formatUnits.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/unit/formatGwei.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/transaction.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/blobsToCommitments.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/blobsToProofs.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/hash/sha256.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/constants/blob.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/constants/kzg.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/blob.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/toBlobs.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/blob/toBlobSidecars.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/address.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/chain.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/errors/node.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/lru.js","../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/hash/keccak256.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/address/getAddress.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/address/isAddress.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/data/slice.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/transaction/assertTransaction.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/transaction/getTransactionType.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/transaction/serializeAccessList.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/utils/transaction/serializeTransaction.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/op-stack/contracts.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/op-stack/formatters.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/op-stack/serializers.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/op-stack/chainConfig.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/arbitrum.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/avalanche.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/base.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/bsc.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/celo/fees.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/celo/utils.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/celo/formatters.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/celo/serializers.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/celo/chainConfig.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/celo.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/mainnet.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/optimism.js","../node_modules/.pnpm/viem@2.39.0_bufferutil@4.0.9_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.1.12/node_modules/viem/_esm/chains/definitions/polygon.js","../src/components/enhanced-payment/utils/contractUtils.js","../src/components/enhanced-payment/utils/errorUtils.js","../src/components/enhanced-payment/hooks/useTransactionHandling.js","../src/components/enhanced-payment/components/ModernDropdown.jsx","../src/components/enhanced-payment/components/ScreenTransition.jsx","../src/components/enhanced-payment/utils/formatUtils.js","../src/components/enhanced-payment/components/PaymentStatus.jsx","../src/components/enhanced-payment/config/logoConfig.js","../src/components/enhanced-payment/utils/walletUtils.js","../src/components/enhanced-payment/utils/deepLinkUtils.js","../src/components/enhanced-payment/components/QRCodeDisplay.jsx","../src/components/enhanced-payment/components/WalletSelector.jsx","../src/utils/debugUtils.js","../src/components/enhanced-payment/components/MobileWalletDropdown.jsx","../src/components/enhanced-payment/components/ErrorDisplay.jsx","../src/components/enhanced-payment/constants/index.js","../src/components/EnhancedSimpleCoinleyPayment.jsx","../src/CoinleyProvider.jsx","../src/PaymentAPI.js","../src/utils/balanceChecker.js","../src/components/QRCodePayment.jsx","../src/vanilla/index.js","../src/utils/paymentQRGenerator.js","../src/index.js"],"sourcesContent":["export default \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABxCAYAAAAj+QZ8AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAzrSURBVHgB7V3dcRs5Em4MtXWPq41gZ1+v7mwrgh3rArAUgagITNcFYDmAK9ERSBuBfQGsxY3Aku26V/MiOO7j1nqAQwMgRQ4xQONnhqOfr8q2TA4H1HzoRqO70c1g4JhUH/dhNKqgrhfT2cEMOoQaqxidyx+P5J8F8PpYjnkNPYLBgPGq+vxSFOJM/rhvXpp39ZAkGaUk40r+WK69jKT8JMdbQE8oYKDAByTJmMItGQj10OR7zyA3itFr2CQD1NhFMYYeMVhCHA8C1co7pV4yYXL4aSz/GVvfFFBBjxguIcCeOt4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PKP0fdvaunQMFuh9iBQEgkLJP8QqkEcI6OOjfVprbsQPfgLt3Ldn5qI7pBSKAlNZJnEZI7h25uidvO/xJU428fdNmnI5zICEupL1GSpvqbO2Tgkjt9JlXXalSftsHQI36II7lXSeorvL92OjgihSA99YLVJ8Uu+XVU6dPAlx1FQty//OFNzbBxW9ARYTaWgKlUYYLjtsdkuLMRng8IUWLoy4UusL0gbPIJSt+Btq9CA87oPuzYLRxHdDGSUudep1EsYF4QqgmpAuqYICq3tD6kIL619JapdIJoXWf9kJ5iTHJo7nYW0pSpaislLDlQkXZrp74S2mMlGlNA6FVqmlb4b1uDVkMl7XFvlFpadMzkNILN/QX0xDq5O0BOeRJlY6QVqkhXaiLIgshCCRlevV0DJvZPUjGaow0sxe73VDThjQRz0lSsQ7q+hEyOYKaDjN6u1Yi5GJ/KScFtoc9bVqWGc6pOytTL1Lrmci4AlZM9etxDseU7pzB98WGXldPD6AnJCdbm9k+lsScgSpEY2qb6JomQR0Umghqlwr1DEKAXagpnoY+6oStIVv2uyFmDnlB1d/hR+GwCzUbUVw/+6E5XynotOVROogLKrWz8yZQgkkP2ZwM7gXDJoTSkJ7Y2bkJPeNpxT5r/sdP0BMGLiHMX6FUQHy7V+oxjFxeCcpQMGQwRljQ48+29NZfNwADlxAvLpOzz/vqQk3E3SYkw7n2oUnJsAkRwmEFiXzn/gYkJQOXEGFP51Eue07zhREwJCkZupVldxYWLH/VB1cXat5fdaJhE8JriwUl3nTRrk4T3Bbdq1NCDUEYNCFm87Z8SAtzUukMOoK94bHo7Yw6orMjbTmxDOD05U/SBz2l2wab3ncgjS78H0eagrHjdQciAAAAAElFTkSuQmCC\"","import { createConfig, http, fallback } from '@wagmi/core';\nimport { mainnet, bsc, polygon, arbitrum, optimism, avalanche, celo, base } from '@wagmi/core/chains';\nimport { injected, metaMask, coinbaseWallet } from '@wagmi/connectors';\nimport logo from \"../../../assets/Logomark.png\";\n\n// Alchemy API configuration - Dual keys for failover\nconst ALCHEMY_API_KEY_PRIMARY = 'YWG990wOlIikc1tU7-WWTepfU8d1f4dp';\nconst ALCHEMY_API_KEY_SECONDARY = 'qtIcCe_-8t4rIWktnWJm0';\n\n// Version tracking for debugging\nconst WAGMI_CONFIG_VERSION = '2.7.0-dual-alchemy-keys';\nconsole.log('🔧 SDK wagmiConfig version:', WAGMI_CONFIG_VERSION);\n\n// Dynamic connectors based on device\nconst getConnectors = () => {\n const baseConnectors = [\n injected(),\n metaMask({\n dappMetadata: {\n name: 'Coinley Payment',\n icon: logo\n }\n }),\n coinbaseWallet({\n appName: 'Coinley Payment',\n appLogoUrl: logo\n })\n ];\n\n return baseConnectors;\n};\n\nexport const wagmiConfig = createConfig({\n chains: [mainnet, bsc, polygon, arbitrum, optimism, avalanche, celo, base],\n connectors: getConnectors(),\n transports: {\n // Dual Alchemy keys (primary + secondary) + Public fallbacks for maximum reliability\n [mainnet.id]: fallback([\n http(`https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://cloudflare-eth.com', { timeout: 10_000, retryCount: 1 }),\n http('https://eth.llamarpc.com', { timeout: 10_000, retryCount: 1 }),\n http('https://ethereum.publicnode.com', { timeout: 10_000, retryCount: 1 }),\n ]),\n [bsc.id]: fallback([\n http(`https://bnb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://bnb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://bsc-dataseed.bnbchain.org', { timeout: 10_000, retryCount: 1 }),\n http('https://bsc-dataseed-public.bnbchain.org', { timeout: 10_000, retryCount: 1 }),\n http('https://bsc.nodereal.io', { timeout: 10_000, retryCount: 1 }),\n ]),\n [polygon.id]: fallback([\n http(`https://polygon-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://polygon-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://polygon.llamarpc.com', { timeout: 10_000, retryCount: 1 }),\n http('https://polygon-rpc.com', { timeout: 10_000, retryCount: 1 }),\n http('https://polygon.drpc.org', { timeout: 10_000, retryCount: 1 }),\n ]),\n [arbitrum.id]: fallback([\n http(`https://arb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://arb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://arb1.arbitrum.io/rpc', { timeout: 10_000, retryCount: 1 }),\n http('https://arbitrum.llamarpc.com', { timeout: 10_000, retryCount: 1 }),\n ]),\n [optimism.id]: fallback([\n http(`https://opt-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://opt-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://mainnet.optimism.io', { timeout: 10_000, retryCount: 1 }),\n http('https://optimism.llamarpc.com', { timeout: 10_000, retryCount: 1 }),\n ]),\n [avalanche.id]: fallback([\n http(`https://avax-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://avax-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://api.avax.network/ext/bc/C/rpc', { timeout: 10_000, retryCount: 1 }),\n http('https://avalanche.public-rpc.com', { timeout: 10_000, retryCount: 1 }),\n ]),\n [celo.id]: fallback([\n http(`https://celo-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://celo-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://forno.celo.org', { timeout: 10_000, retryCount: 1 }),\n http('https://celo.drpc.org', { timeout: 10_000, retryCount: 1 }),\n ]),\n [base.id]: fallback([\n http(`https://base-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_PRIMARY}`, { timeout: 10_000, retryCount: 1 }),\n http(`https://base-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY_SECONDARY}`, { timeout: 10_000, retryCount: 1 }),\n http('https://mainnet.base.org', { timeout: 10_000, retryCount: 1 }),\n http('https://base.llamarpc.com', { timeout: 10_000, retryCount: 1 }),\n http('https://base.meowrpc.com', { timeout: 10_000, retryCount: 1 }),\n ]),\n },\n});\n\nexport { getConnectors };","// Payment API class for backend communication\n// Supports both new publicKey auth and legacy apiKey+apiSecret auth\n\nexport class SimplePaymentAPI {\n constructor(baseURL, publicKeyOrApiKey, apiSecret = null) {\n this.baseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;\n\n // Determine if using new publicKey auth (starts with 'pk_') or legacy auth\n if (publicKeyOrApiKey && publicKeyOrApiKey.startsWith('pk_')) {\n // New public key authentication\n this.publicKey = publicKeyOrApiKey;\n this.apiKey = null;\n this.apiSecret = null;\n } else {\n // Legacy authentication with apiKey + apiSecret\n this.publicKey = null;\n this.apiKey = publicKeyOrApiKey;\n this.apiSecret = apiSecret;\n }\n }\n\n async request(endpoint, options = {}) {\n const url = `${this.baseURL}${endpoint}`;\n\n // Build headers based on authentication method\n const headers = {\n 'Content-Type': 'application/json',\n ...options.headers\n };\n\n // Use public key if available (new method), otherwise use legacy auth\n if (this.publicKey) {\n headers['X-Public-Key'] = this.publicKey;\n } else {\n headers['X-API-Key'] = this.apiKey;\n headers['X-API-Secret'] = this.apiSecret;\n }\n\n // ✅ Add timeout to prevent infinite hanging (critical for blockchain calls)\n const timeout = options.timeout || 60000; // Default 60 seconds\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n ...options,\n headers,\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new Error(error.error || `HTTP ${response.status}`);\n }\n\n return response.json();\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error.name === 'AbortError') {\n throw new Error(`Request timeout after ${timeout / 1000}s: ${endpoint}`);\n }\n throw error;\n }\n }\n\n async getNetworks() {\n try {\n return await this.request('/api/networks');\n } catch (error) {\n return {\n networks: [\n { id: '1', name: 'Ethereum', shortName: 'ethereum', chainId: '0x1', type: 'ethereum' },\n { id: '56', name: 'BSC', shortName: 'bsc', chainId: '0x38', type: 'bsc' },\n { id: '137', name: 'Polygon', shortName: 'polygon', chainId: '0x89', type: 'polygon' },\n { id: '42161', name: 'Arbitrum', shortName: 'arbitrum', chainId: '0xa4b1', type: 'arbitrum' },\n { id: '10', name: 'Optimism', shortName: 'optimism', chainId: '0xa', type: 'optimism' },\n { id: '43114', name: 'Avalanche', shortName: 'avalanche', chainId: '0xa86a', type: 'avalanche' }\n ]\n };\n }\n }\n\n async getTokens() {\n try {\n return await this.request('/api/networks/stablecoins');\n } catch (error) {\n return {\n stablecoins: [\n // Ethereum Network\n {\n id: '1', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n decimals: 6, networkId: '1',\n Network: { shortName: 'ethereum', name: 'Ethereum' }\n },\n {\n id: '2', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n decimals: 6, networkId: '1',\n Network: { shortName: 'ethereum', name: 'Ethereum' }\n },\n\n // BSC Network\n {\n id: '3', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x55d398326f99059fF775485246999027B3197955',\n decimals: 18, networkId: '56',\n Network: { shortName: 'bsc', name: 'BSC' }\n },\n {\n id: '4', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',\n decimals: 18, networkId: '56',\n Network: { shortName: 'bsc', name: 'BSC' }\n },\n\n // Polygon Network (Native USDC)\n {\n id: '5', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xc2132D05D31c914a87c6611C10748AEb04B58e8F',\n decimals: 6, networkId: '137',\n Network: { shortName: 'polygon', name: 'Polygon' }\n },\n {\n id: '6', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',\n decimals: 6, networkId: '137',\n Network: { shortName: 'polygon', name: 'Polygon' }\n },\n\n // Arbitrum Network (Native USDC)\n {\n id: '7', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',\n decimals: 6, networkId: '42161',\n Network: { shortName: 'arbitrum', name: 'Arbitrum' }\n },\n {\n id: '8', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n decimals: 6, networkId: '42161',\n Network: { shortName: 'arbitrum', name: 'Arbitrum' }\n },\n\n // Optimism Network\n {\n id: '9', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58',\n decimals: 6, networkId: '10',\n Network: { shortName: 'optimism', name: 'Optimism' }\n },\n {\n id: '10', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n decimals: 6, networkId: '10',\n Network: { shortName: 'optimism', name: 'Optimism' }\n },\n\n // Avalanche Network\n {\n id: '11', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7',\n decimals: 6, networkId: '43114',\n Network: { shortName: 'avalanche', name: 'Avalanche' }\n },\n {\n id: '12', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',\n decimals: 6, networkId: '43114',\n Network: { shortName: 'avalanche', name: 'Avalanche' }\n },\n\n // Celo Network (Native USDC)\n {\n id: '13', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e',\n decimals: 6, networkId: '42220',\n Network: { shortName: 'celo', name: 'Celo' }\n },\n {\n id: '14', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xcebA9300f2b948710d2653dD7B07f33A8B32118C',\n decimals: 6, networkId: '42220',\n Network: { shortName: 'celo', name: 'Celo' }\n },\n\n // Base Network\n {\n id: '15', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2',\n decimals: 6, networkId: '8453',\n Network: { shortName: 'base', name: 'Base' }\n },\n {\n id: '16', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n decimals: 6, networkId: '8453',\n Network: { shortName: 'base', name: 'Base' }\n }\n ]\n };\n }\n }\n\n async createPayment(data) {\n return await this.request('/api/payments/create', {\n method: 'POST',\n body: JSON.stringify(data)\n });\n }\n\n async verifyQRPayment(paymentId) {\n return await this.request('/api/payments/verify-qr', {\n method: 'POST',\n body: JSON.stringify({ paymentId })\n });\n }\n\n async checkPaymentStatus(paymentId) {\n return await this.request(`/api/payments/status/${paymentId}`);\n }\n\n async getContractInfo(chainId) {\n try {\n const response = await this.request(`/api/payments/contract/${chainId}`);\n if (!response.success) {\n throw new Error('Contract not supported on this network');\n }\n return response.contractInfo;\n } catch (error) {\n throw new Error(error.message || 'Failed to get contract information');\n }\n }\n\n async processPayment(paymentId, transactionHash, network, senderAddress) {\n // ✅ Longer timeout for blockchain verification (90 seconds)\n console.log('📤 [API] processPayment called with:', {\n paymentId,\n transactionHash,\n network,\n senderAddress,\n baseURL: this.baseURL,\n hasPublicKey: !!this.publicKey,\n hasApiKey: !!this.apiKey,\n hasApiSecret: !!this.apiSecret\n });\n\n try {\n const result = await this.request('/api/payments/process', {\n method: 'POST',\n body: JSON.stringify({\n paymentId,\n transactionHash,\n network,\n senderAddress\n }),\n timeout: 90000 // 90 seconds - blockchain verification can be slow\n });\n return result;\n } catch (error) {\n throw error;\n }\n }\n\n async failPayment(paymentId, reason = 'Payment cancelled by user') {\n return await this.request('/api/payments/fail', {\n method: 'POST',\n body: JSON.stringify({\n paymentId,\n reason,\n status: 'failed'\n })\n });\n }\n}\n","import { useState, useEffect, useRef } from 'react';\nimport { SimplePaymentAPI } from '../api/paymentAPI';\n\nexport const usePaymentFlow = (apiUrl, apiKey, apiSecret) => {\n const [currentStep, setCurrentStep] = useState('method');\n const [networks, setNetworks] = useState([]);\n const [tokens, setTokens] = useState([]);\n const [selectedNetwork, setSelectedNetwork] = useState(null);\n const [selectedToken, setSelectedToken] = useState(null);\n const [paymentMethod, setPaymentMethod] = useState(null);\n const [paymentData, setPaymentData] = useState(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState('');\n const [processing, setProcessing] = useState(false);\n const [processingMessage, setProcessingMessage] = useState('Processing transaction...');\n const [paymentType, setPaymentType] = useState('wallet');\n const [actualTransactionHash, setActualTransactionHash] = useState(null);\n\n const api = useRef(new SimplePaymentAPI(apiUrl, apiKey, apiSecret));\n\n const loadData = async () => {\n try {\n setLoading(true);\n setError('');\n\n const [networksRes, tokensRes] = await Promise.all([\n api.current.getNetworks(),\n api.current.getTokens()\n ]);\n\n // Remove duplicate networks and filter out unsupported networks\n const uniqueNetworks = networksRes.networks?.reduce((acc, network) => {\n // Filter out Solana, Tron, and Algorand networks\n if (network.shortName === 'solana' || network.shortName === 'tron' || network.shortName === 'algorand') {\n return acc;\n }\n\n // Only include networks with valid chainId (EVM networks)\n if (!network.chainId || network.chainId === null) {\n return acc;\n }\n\n // Use chainId for deduplication (more reliable than UUID id)\n const key = `${network.chainId}-${network.shortName}`;\n if (!acc.some(n => `${n.chainId}-${n.shortName}` === key)) {\n acc.push(network);\n }\n return acc;\n }, []) || [];\n\n // Remove duplicate tokens and filter for only USDC and USDT\n const uniqueTokens = tokensRes.stablecoins?.reduce((acc, token) => {\n // Only allow USDC and USDT tokens\n if (token.symbol !== 'USDC' && token.symbol !== 'USDT') {\n return acc;\n }\n\n // Filter out tokens from unsupported networks\n if (token.Network?.shortName === 'solana' || token.Network?.shortName === 'tron' || token.Network?.shortName === 'algorand') {\n return acc;\n }\n\n // Use symbol + networkId for deduplication (not UUID id)\n const key = `${token.symbol}-${token.networkId}`;\n if (!acc.some(t => `${t.symbol}-${t.networkId}` === key)) {\n acc.push(token);\n }\n return acc;\n }, []) || [];\n\n setNetworks(uniqueNetworks);\n setTokens(uniqueTokens);\n\n\n } catch (err) {\n setError('Failed to load payment options. Using fallback data.');\n } finally {\n setLoading(false);\n }\n };\n\n const createPayment = async (config) => {\n try {\n setLoading(true);\n setError('');\n\n const paymentPayload = {\n amount: config.amount,\n currency: selectedToken.symbol,\n network: selectedNetwork.shortName,\n customerEmail: config.customerEmail,\n callbackUrl: config.callbackUrl,\n metadata: {\n ...config.metadata,\n merchantWalletAddresses: config.merchantWalletAddresses,\n paymentMethod,\n selectedNetwork: selectedNetwork.shortName,\n selectedToken: selectedToken.symbol,\n wagmiEnabled: true\n }\n };\n\n const payment = await api.current.createPayment(paymentPayload);\n setPaymentData(payment.payment);\n\n setCurrentStep('confirm');\n\n } catch (err) {\n setError(err.message);\n } finally {\n setLoading(false);\n }\n };\n\n const failPayment = async (reason = 'Payment cancelled by user') => {\n if (paymentData?.id) {\n try {\n await api.current.failPayment(paymentData.id, reason);\n } catch (error) {\n }\n }\n };\n\n const resetState = () => {\n setCurrentStep('method');\n setSelectedNetwork(null);\n setSelectedToken(null);\n setPaymentMethod(null);\n setPaymentData(null);\n setError('');\n setProcessing(false);\n setActualTransactionHash(null);\n setPaymentType('wallet');\n };\n\n const resetTransactionState = () => {\n setError('');\n setProcessing(false);\n setActualTransactionHash(null);\n setCurrentStep('confirm');\n };\n\n return {\n // State\n currentStep,\n networks,\n tokens,\n selectedNetwork,\n selectedToken,\n paymentMethod,\n paymentData,\n loading,\n error,\n processing,\n processingMessage,\n paymentType,\n actualTransactionHash,\n\n // Actions\n setCurrentStep,\n setSelectedNetwork,\n setSelectedToken,\n setPaymentMethod,\n setError,\n setProcessing,\n setProcessingMessage,\n setPaymentType,\n setActualTransactionHash,\n loadData,\n createPayment,\n failPayment,\n resetState,\n resetTransactionState,\n\n // API reference\n api: api.current\n };\n};","// Chain ID mappings for different networks\nexport const CHAIN_IDS = {\n ethereum: 1,\n bsc: 56,\n polygon: 137,\n arbitrum: 42161,\n optimism: 10,\n avalanche: 43114,\n celo: 42220,\n base: 8453\n};\n\n// Trust Wallet chain ID mapping (they use different IDs for some chains)\nexport const TRUST_CHAIN_IDS = {\n 1: 60, // Ethereum\n 56: 56, // BSC\n 137: 966, // Polygon\n 42161: 42161, // Arbitrum\n 10: 10, // Optimism\n 43114: 43114, // Avalanche\n 42220: 42220, // Celo\n 8453: 8453 // Base\n};\n\n// Network display names\nexport const NETWORK_NAMES = {\n ethereum: 'Ethereum',\n bsc: 'BSC',\n polygon: 'Polygon',\n arbitrum: 'Arbitrum',\n optimism: 'Optimism',\n avalanche: 'Avalanche',\n celo: 'Celo',\n base: 'Base'\n};\n\n/**\n * Normalize chainId to decimal number\n * Handles hex strings (\"0x1\", \"0xa86a\"), decimal strings (\"1\", \"43114\"), and numbers (1, 43114)\n * @param {string|number} chainId - Chain ID in any format\n * @returns {number} - Chain ID as decimal number\n */\nexport const normalizeChainId = (chainId) => {\n if (typeof chainId === 'number') {\n return chainId;\n }\n\n if (typeof chainId === 'string') {\n // Handle hex strings like \"0x1\" or \"0xa86a\"\n if (chainId.startsWith('0x')) {\n return parseInt(chainId, 16);\n }\n // Handle decimal strings like \"1\" or \"43114\"\n return parseInt(chainId, 10);\n }\n\n return 1; // Default to Ethereum mainnet\n};\n\n// Get numeric chain ID from network short name\nexport const getChainId = (networkShortName) => {\n return CHAIN_IDS[networkShortName] || 1;\n};\n\n// Get Trust Wallet chain ID mapping\nexport const getTrustChainId = (chainId) => {\n return TRUST_CHAIN_IDS[chainId] || 60;\n};\n\n// Get network display name\nexport const getNetworkDisplayName = (network) => {\n return NETWORK_NAMES[network] || network;\n};\n\n// Token contract addresses and decimals for different networks\nexport const TOKEN_CONTRACTS = {\n 'ethereum': {\n 'USDT': { contract: '0xdAC17F958D2ee523a2206206994597C13D831ec7', decimals: 6 },\n 'USDC': { contract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', decimals: 6 }\n },\n 'bsc': {\n 'USDT': { contract: '0x55d398326f99059fF775485246999027B3197955', decimals: 18 },\n 'USDC': { contract: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d', decimals: 18 }\n },\n 'polygon': {\n 'USDT': { contract: '0xc2132D05D31c914a87c6611C10748AEb04B58e8F', decimals: 6 },\n 'USDC': { contract: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', decimals: 6 }\n },\n 'arbitrum': {\n 'USDT': { contract: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9', decimals: 6 },\n 'USDC': { contract: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831', decimals: 6 }\n },\n 'optimism': {\n 'USDT': { contract: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58', decimals: 6 },\n 'USDC': { contract: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85', decimals: 6 }\n },\n 'avalanche': {\n 'USDT': { contract: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7', decimals: 6 },\n 'USDC': { contract: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E', decimals: 6 }\n },\n 'celo': {\n 'USDT': { contract: '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e', decimals: 6 },\n 'USDC': { contract: '0xcebA9300f2b948710d2653dD7B07f33A8B32118C', decimals: 6 }\n },\n 'base': {\n 'USDT': { contract: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2', decimals: 6 },\n 'USDC': { contract: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', decimals: 6 }\n }\n};\n\n// Get token info for a specific network and token symbol\nexport const getTokenInfo = (networkName, tokenSymbol) => {\n return TOKEN_CONTRACTS[networkName?.toLowerCase()]?.[tokenSymbol];\n};","import { useState, useEffect } from 'react';\nimport { useConnect, useAccount, useSwitchChain } from 'wagmi';\nimport { getAccount } from '@wagmi/core';\nimport { wagmiConfig } from '../config/wagmiConfig';\nimport { getChainId } from '../config/chainConfig';\n\nexport const useWalletConnection = () => {\n const [selectedWalletType, setSelectedWalletType] = useState(null);\n const [connectedWallet, setConnectedWallet] = useState(null);\n const [connectionError, setConnectionError] = useState('');\n\n const { connect, connectors } = useConnect();\n const { isConnected, address, chain } = useAccount();\n const { switchChain } = useSwitchChain();\n\n // Update connected wallet state when account changes\n useEffect(() => {\n if (isConnected && address) {\n setConnectedWallet({\n account: address,\n chainId: chain?.id,\n walletType: selectedWalletType\n });\n } else {\n setConnectedWallet(null);\n }\n }, [isConnected, address, chain, selectedWalletType]);\n\n const handleWalletSelection = (walletType) => {\n setSelectedWalletType(walletType);\n setConnectionError('');\n };\n\n const connectWallet = async (connector, selectedNetwork = null) => {\n if (!connector) {\n setConnectionError('Please select a wallet first');\n return false;\n }\n\n try {\n setConnectionError('');\n\n // Use Wagmi's connect function directly\n await connect({ connector });\n\n if (selectedNetwork) {\n // Check if we need to switch networks after connection\n const requiredChainId = getChainId(selectedNetwork.shortName);\n\n // Wait for wallet to initialize before switching networks\n // Some wallets (Zerion, Trust, Rabby) need more time on cold start\n const walletName = connector.name?.toLowerCase() || '';\n const needsLongerDelay = walletName.includes('zerion') ||\n walletName.includes('trust') ||\n walletName.includes('rabby');\n\n const delayMs = needsLongerDelay ? 5000 : 500; // 5s for slow wallets, 500ms for others\n await new Promise(resolve => setTimeout(resolve, delayMs));\n\n // Get current chain info\n const currentAccount = getAccount(wagmiConfig);\n const currentChainId = currentAccount.chainId;\n\n\n if (requiredChainId && currentChainId !== requiredChainId) {\n try {\n await switchChain({ chainId: requiredChainId });\n\n // Wait a moment for the wallet to update its state after network switch\n await new Promise(resolve => setTimeout(resolve, 1000));\n\n } catch (switchError) {\n\n // Provide user-friendly error messages\n if (switchError.code === 4001 || switchError.message?.includes('User rejected')) {\n setConnectionError('Network switch was cancelled by user');\n } else if (switchError.message?.includes('Unrecognized chain ID')) {\n setConnectionError(`${selectedNetwork.name} network is not added to your wallet. Please add it manually.`);\n } else {\n setConnectionError(`Failed to switch to ${selectedNetwork.name}. Please switch manually in your wallet.`);\n }\n return false;\n }\n }\n }\n\n return true;\n\n } catch (err) {\n\n // Provide user-friendly error messages\n if (err.code === 4001 || err.message.includes('User rejected') || err.message.includes('rejected')) {\n setConnectionError('User cancelled the connection request');\n } else {\n setConnectionError(`Failed to connect to ${connector.name}. Please try again.`);\n }\n return false;\n }\n };\n\n const disconnectWallet = () => {\n setConnectedWallet(null);\n setSelectedWalletType(null);\n setConnectionError('');\n };\n\n const clearError = () => {\n setConnectionError('');\n };\n\n const ensureCorrectNetwork = async (requiredNetwork) => {\n if (!requiredNetwork) {\n return true;\n }\n\n try {\n const requiredChainId = getChainId(requiredNetwork.shortName);\n const currentAccount = getAccount(wagmiConfig);\n const currentChainId = currentAccount.chainId;\n\n\n if (requiredChainId && currentChainId !== requiredChainId) {\n\n try {\n await switchChain({ chainId: requiredChainId });\n\n // Wait a moment for the switch to complete\n await new Promise(resolve => setTimeout(resolve, 1000));\n return true;\n\n } catch (switchError) {\n\n if (switchError.code === 4001 || switchError.message?.includes('User rejected')) {\n setConnectionError('Network switch was cancelled. Please switch to the correct network in your wallet.');\n } else if (switchError.message?.includes('Unrecognized chain ID')) {\n setConnectionError(`${requiredNetwork.name} network is not added to your wallet. Please add it manually.`);\n } else {\n setConnectionError(`Failed to switch to ${requiredNetwork.name}. Please switch manually in your wallet.`);\n }\n return false;\n }\n }\n\n return true;\n\n } catch (error) {\n setConnectionError('Failed to verify network. Please check your wallet connection.');\n return false;\n }\n };\n\n return {\n // State\n selectedWalletType,\n connectedWallet,\n connectionError,\n isConnected,\n address,\n chain,\n connectors,\n\n // Actions\n handleWalletSelection,\n connectWallet,\n disconnectWallet,\n switchChain,\n ensureCorrectNetwork,\n clearError,\n setSelectedWalletType,\n\n // Wagmi hooks\n connect\n };\n};","export function defineChain(chain) {\n return {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n };\n}\n//# sourceMappingURL=defineChain.js.map","export const version = '2.39.0';\n//# sourceMappingURL=version.js.map","import { version } from './version.js';\nlet errorConfig = {\n getDocsUrl: ({ docsBaseUrl, docsPath = '', docsSlug, }) => docsPath\n ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${docsSlug ? `#${docsSlug}` : ''}`\n : undefined,\n version: `viem@${version}`,\n};\nexport function setErrorConfig(config) {\n errorConfig = config;\n}\nexport class BaseError extends Error {\n constructor(shortMessage, args = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.details;\n if (args.cause?.message)\n return args.cause.message;\n return args.details;\n })();\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath;\n return args.docsPath;\n })();\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });\n const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),\n ].join('\\n');\n super(message, args.cause ? { cause: args.cause } : undefined);\n Object.defineProperty(this, \"details\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"docsPath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"metaMessages\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"shortMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'BaseError'\n });\n this.details = details;\n this.docsPath = docsPath;\n this.metaMessages = args.metaMessages;\n this.name = args.name ?? this.name;\n this.shortMessage = shortMessage;\n this.version = version;\n }\n walk(fn) {\n return walk(this, fn);\n }\n}\nfunction walk(err, fn) {\n if (fn?.(err))\n return err;\n if (err &&\n typeof err === 'object' &&\n 'cause' in err &&\n err.cause !== undefined)\n return walk(err.cause, fn);\n return fn ? null : err;\n}\n//# sourceMappingURL=base.js.map","import { BaseError } from './base.js';\nexport class IntegerOutOfRangeError extends BaseError {\n constructor({ max, min, signed, size, value, }) {\n super(`Number \"${value}\" is not in safe ${size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: 'IntegerOutOfRangeError' });\n }\n}\nexport class InvalidBytesBooleanError extends BaseError {\n constructor(bytes) {\n super(`Bytes value \"${bytes}\" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, {\n name: 'InvalidBytesBooleanError',\n });\n }\n}\nexport class InvalidHexBooleanError extends BaseError {\n constructor(hex) {\n super(`Hex value \"${hex}\" is not a valid boolean. The hex value must be \"0x0\" (false) or \"0x1\" (true).`, { name: 'InvalidHexBooleanError' });\n }\n}\nexport class InvalidHexValueError extends BaseError {\n constructor(value) {\n super(`Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`, { name: 'InvalidHexValueError' });\n }\n}\nexport class SizeOverflowError extends BaseError {\n constructor({ givenSize, maxSize }) {\n super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: 'SizeOverflowError' });\n }\n}\n//# sourceMappingURL=encoding.js.map","export function isHex(value, { strict = true } = {}) {\n if (!value)\n return false;\n if (typeof value !== 'string')\n return false;\n return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x');\n}\n//# sourceMappingURL=isHex.js.map","import { isHex } from './isHex.js';\n/**\n * @description Retrieves the size of the value (in bytes).\n *\n * @param value The value (hex or byte array) to retrieve the size of.\n * @returns The size of the value (in bytes).\n */\nexport function size(value) {\n if (isHex(value, { strict: false }))\n return Math.ceil((value.length - 2) / 2);\n return value.length;\n}\n//# sourceMappingURL=size.js.map","export function trim(hexOrBytes, { dir = 'left' } = {}) {\n let data = typeof hexOrBytes === 'string' ? hexOrBytes.replace('0x', '') : hexOrBytes;\n let sliceLength = 0;\n for (let i = 0; i < data.length - 1; i++) {\n if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')\n sliceLength++;\n else\n break;\n }\n data =\n dir === 'left'\n ? data.slice(sliceLength)\n : data.slice(0, data.length - sliceLength);\n if (typeof hexOrBytes === 'string') {\n if (data.length === 1 && dir === 'right')\n data = `${data}0`;\n return `0x${data.length % 2 === 1 ? `0${data}` : data}`;\n }\n return data;\n}\n//# sourceMappingURL=trim.js.map","import { BaseError } from './base.js';\nexport class SliceOffsetOutOfBoundsError extends BaseError {\n constructor({ offset, position, size, }) {\n super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset \"${offset}\" is out-of-bounds (size: ${size}).`, { name: 'SliceOffsetOutOfBoundsError' });\n }\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`, { name: 'SizeExceedsPaddingSizeError' });\n }\n}\nexport class InvalidBytesLengthError extends BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size} ${type} long.`, { name: 'InvalidBytesLengthError' });\n }\n}\n//# sourceMappingURL=data.js.map","import { SizeExceedsPaddingSizeError, } from '../../errors/data.js';\nexport function pad(hexOrBytes, { dir, size = 32 } = {}) {\n if (typeof hexOrBytes === 'string')\n return padHex(hexOrBytes, { dir, size });\n return padBytes(hexOrBytes, { dir, size });\n}\nexport function padHex(hex_, { dir, size = 32 } = {}) {\n if (size === null)\n return hex_;\n const hex = hex_.replace('0x', '');\n if (hex.length > size * 2)\n throw new SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'hex',\n });\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`;\n}\nexport function padBytes(bytes, { dir, size = 32 } = {}) {\n if (size === null)\n return bytes;\n if (bytes.length > size)\n throw new SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'bytes',\n });\n const paddedBytes = new Uint8Array(size);\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right';\n paddedBytes[padEnd ? i : size - i - 1] =\n bytes[padEnd ? i : bytes.length - i - 1];\n }\n return paddedBytes;\n}\n//# sourceMappingURL=pad.js.map","import { IntegerOutOfRangeError, } from '../../errors/encoding.js';\nimport { pad } from '../data/pad.js';\nimport { assertSize } from './fromHex.js';\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));\n/**\n * Encodes a string, number, bigint, or ByteArray into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex\n * - Example: https://viem.sh/docs/utilities/toHex#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world')\n * // '0x48656c6c6f20776f726c6421'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex(420)\n * // '0x1a4'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world', { size: 32 })\n * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'\n */\nexport function toHex(value, opts = {}) {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToHex(value, opts);\n if (typeof value === 'string') {\n return stringToHex(value, opts);\n }\n if (typeof value === 'boolean')\n return boolToHex(value, opts);\n return bytesToHex(value, opts);\n}\n/**\n * Encodes a boolean into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#booltohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true)\n * // '0x1'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(false)\n * // '0x0'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true, { size: 32 })\n * // '0x0000000000000000000000000000000000000000000000000000000000000001'\n */\nexport function boolToHex(value, opts = {}) {\n const hex = `0x${Number(value)}`;\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size });\n return pad(hex, { size: opts.size });\n }\n return hex;\n}\n/**\n * Encodes a bytes array into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#bytestohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function bytesToHex(value, opts = {}) {\n let string = '';\n for (let i = 0; i < value.length; i++) {\n string += hexes[value[i]];\n }\n const hex = `0x${string}`;\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size });\n return pad(hex, { dir: 'right', size: opts.size });\n }\n return hex;\n}\n/**\n * Encodes a number or bigint into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#numbertohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420)\n * // '0x1a4'\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420, { size: 32 })\n * // '0x00000000000000000000000000000000000000000000000000000000000001a4'\n */\nexport function numberToHex(value_, opts = {}) {\n const { signed, size } = opts;\n const value = BigInt(value_);\n let maxValue;\n if (size) {\n if (signed)\n maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n;\n else\n maxValue = 2n ** (BigInt(size) * 8n) - 1n;\n }\n else if (typeof value_ === 'number') {\n maxValue = BigInt(Number.MAX_SAFE_INTEGER);\n }\n const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0;\n if ((maxValue && value > maxValue) || value < minValue) {\n const suffix = typeof value_ === 'bigint' ? 'n' : '';\n throw new IntegerOutOfRangeError({\n max: maxValue ? `${maxValue}${suffix}` : undefined,\n min: `${minValue}${suffix}`,\n signed,\n size,\n value: `${value_}${suffix}`,\n });\n }\n const hex = `0x${(signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : value).toString(16)}`;\n if (size)\n return pad(hex, { size });\n return hex;\n}\nconst encoder = /*#__PURE__*/ new TextEncoder();\n/**\n * Encodes a UTF-8 string into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#stringtohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function stringToHex(value_, opts = {}) {\n const value = encoder.encode(value_);\n return bytesToHex(value, opts);\n}\n//# sourceMappingURL=toHex.js.map","import { BaseError } from '../../errors/base.js';\nimport { isHex } from '../data/isHex.js';\nimport { pad } from '../data/pad.js';\nimport { assertSize } from './fromHex.js';\nimport { numberToHex, } from './toHex.js';\nconst encoder = /*#__PURE__*/ new TextEncoder();\n/**\n * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes\n * - Example: https://viem.sh/docs/utilities/toBytes#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes('Hello world')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function toBytes(value, opts = {}) {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToBytes(value, opts);\n if (typeof value === 'boolean')\n return boolToBytes(value, opts);\n if (isHex(value))\n return hexToBytes(value, opts);\n return stringToBytes(value, opts);\n}\n/**\n * Encodes a boolean into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes\n *\n * @param value Boolean value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true)\n * // Uint8Array([1])\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true, { size: 32 })\n * // Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n */\nexport function boolToBytes(value, opts = {}) {\n const bytes = new Uint8Array(1);\n bytes[0] = Number(value);\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size });\n return pad(bytes, { size: opts.size });\n }\n return bytes;\n}\n// We use very optimized technique to convert hex string to byte array\nconst charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n};\nfunction charCodeToBase16(char) {\n if (char >= charCodeMap.zero && char <= charCodeMap.nine)\n return char - charCodeMap.zero;\n if (char >= charCodeMap.A && char <= charCodeMap.F)\n return char - (charCodeMap.A - 10);\n if (char >= charCodeMap.a && char <= charCodeMap.f)\n return char - (charCodeMap.a - 10);\n return undefined;\n}\n/**\n * Encodes a hex string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes\n *\n * @param hex Hex string to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function hexToBytes(hex_, opts = {}) {\n let hex = hex_;\n if (opts.size) {\n assertSize(hex, { size: opts.size });\n hex = pad(hex, { dir: 'right', size: opts.size });\n }\n let hexString = hex.slice(2);\n if (hexString.length % 2)\n hexString = `0${hexString}`;\n const length = hexString.length / 2;\n const bytes = new Uint8Array(length);\n for (let index = 0, j = 0; index < length; index++) {\n const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));\n const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new BaseError(`Invalid byte sequence (\"${hexString[j - 2]}${hexString[j - 1]}\" in \"${hexString}\").`);\n }\n bytes[index] = nibbleLeft * 16 + nibbleRight;\n }\n return bytes;\n}\n/**\n * Encodes a number into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes\n *\n * @param value Number to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function numberToBytes(value, opts) {\n const hex = numberToHex(value, opts);\n return hexToBytes(hex);\n}\n/**\n * Encodes a UTF-8 string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes\n *\n * @param value String to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function stringToBytes(value, opts = {}) {\n const bytes = encoder.encode(value);\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size });\n return pad(bytes, { dir: 'right', size: opts.size });\n }\n return bytes;\n}\n//# sourceMappingURL=toBytes.js.map","import { InvalidHexBooleanError, SizeOverflowError, } from '../../errors/encoding.js';\nimport { size as size_ } from '../data/size.js';\nimport { trim } from '../data/trim.js';\nimport { hexToBytes } from './toBytes.js';\nexport function assertSize(hexOrBytes, { size }) {\n if (size_(hexOrBytes) > size)\n throw new SizeOverflowError({\n givenSize: size_(hexOrBytes),\n maxSize: size,\n });\n}\n/**\n * Decodes a hex string into a string, number, bigint, boolean, or byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex\n * - Example: https://viem.sh/docs/utilities/fromHex#usage\n *\n * @param hex Hex string to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x1a4', 'number')\n * // 420\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c6421', 'string')\n * // 'Hello world'\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * to: 'string'\n * })\n * // 'Hello world'\n */\nexport function fromHex(hex, toOrOpts) {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts;\n const to = opts.to;\n if (to === 'number')\n return hexToNumber(hex, opts);\n if (to === 'bigint')\n return hexToBigInt(hex, opts);\n if (to === 'string')\n return hexToString(hex, opts);\n if (to === 'boolean')\n return hexToBool(hex, opts);\n return hexToBytes(hex, opts);\n}\n/**\n * Decodes a hex value into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobigint\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x1a4', { signed: true })\n * // 420n\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420n\n */\nexport function hexToBigInt(hex, opts = {}) {\n const { signed } = opts;\n if (opts.size)\n assertSize(hex, { size: opts.size });\n const value = BigInt(hex);\n if (!signed)\n return value;\n const size = (hex.length - 2) / 2;\n const max = (1n << (BigInt(size) * 8n - 1n)) - 1n;\n if (value <= max)\n return value;\n return value - BigInt(`0x${'f'.padStart(size * 2, 'f')}`) - 1n;\n}\n/**\n * Decodes a hex value into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobool\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x01')\n * // true\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // true\n */\nexport function hexToBool(hex_, opts = {}) {\n let hex = hex_;\n if (opts.size) {\n assertSize(hex, { size: opts.size });\n hex = trim(hex);\n }\n if (trim(hex) === '0x00')\n return false;\n if (trim(hex) === '0x01')\n return true;\n throw new InvalidHexBooleanError(hex);\n}\n/**\n * Decodes a hex string into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextonumber\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToNumber('0x1a4')\n * // 420\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420\n */\nexport function hexToNumber(hex, opts = {}) {\n return Number(hexToBigInt(hex, opts));\n}\n/**\n * Decodes a hex value into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextostring\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c6421')\n * // 'Hello world!'\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // 'Hello world'\n */\nexport function hexToString(hex, opts = {}) {\n let bytes = hexToBytes(hex);\n if (opts.size) {\n assertSize(bytes, { size: opts.size });\n bytes = trim(bytes, { dir: 'right' });\n }\n return new TextDecoder().decode(bytes);\n}\n//# sourceMappingURL=fromHex.js.map","export function defineFormatter(type, format) {\n return ({ exclude, format: overrides, }) => {\n return {\n exclude,\n format: (args, action) => {\n const formatted = format(args, action);\n if (exclude) {\n for (const key of exclude) {\n delete formatted[key];\n }\n }\n return {\n ...formatted,\n ...overrides(args, action),\n };\n },\n type,\n };\n };\n}\n//# sourceMappingURL=formatter.js.map","import { hexToNumber } from '../encoding/fromHex.js';\nimport { defineFormatter } from './formatter.js';\nexport const transactionType = {\n '0x0': 'legacy',\n '0x1': 'eip2930',\n '0x2': 'eip1559',\n '0x3': 'eip4844',\n '0x4': 'eip7702',\n};\nexport function formatTransaction(transaction, _) {\n const transaction_ = {\n ...transaction,\n blockHash: transaction.blockHash ? transaction.blockHash : null,\n blockNumber: transaction.blockNumber\n ? BigInt(transaction.blockNumber)\n : null,\n chainId: transaction.chainId ? hexToNumber(transaction.chainId) : undefined,\n gas: transaction.gas ? BigInt(transaction.gas) : undefined,\n gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : undefined,\n maxFeePerBlobGas: transaction.maxFeePerBlobGas\n ? BigInt(transaction.maxFeePerBlobGas)\n : undefined,\n maxFeePerGas: transaction.maxFeePerGas\n ? BigInt(transaction.maxFeePerGas)\n : undefined,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas\n ? BigInt(transaction.maxPriorityFeePerGas)\n : undefined,\n nonce: transaction.nonce ? hexToNumber(transaction.nonce) : undefined,\n to: transaction.to ? transaction.to : null,\n transactionIndex: transaction.transactionIndex\n ? Number(transaction.transactionIndex)\n : null,\n type: transaction.type\n ? transactionType[transaction.type]\n : undefined,\n typeHex: transaction.type ? transaction.type : undefined,\n value: transaction.value ? BigInt(transaction.value) : undefined,\n v: transaction.v ? BigInt(transaction.v) : undefined,\n };\n if (transaction.authorizationList)\n transaction_.authorizationList = formatAuthorizationList(transaction.authorizationList);\n transaction_.yParity = (() => {\n // If `yParity` is provided, we will use it.\n if (transaction.yParity)\n return Number(transaction.yParity);\n // If no `yParity` provided, try derive from `v`.\n if (typeof transaction_.v === 'bigint') {\n if (transaction_.v === 0n || transaction_.v === 27n)\n return 0;\n if (transaction_.v === 1n || transaction_.v === 28n)\n return 1;\n if (transaction_.v >= 35n)\n return transaction_.v % 2n === 0n ? 1 : 0;\n }\n return undefined;\n })();\n if (transaction_.type === 'legacy') {\n delete transaction_.accessList;\n delete transaction_.maxFeePerBlobGas;\n delete transaction_.maxFeePerGas;\n delete transaction_.maxPriorityFeePerGas;\n delete transaction_.yParity;\n }\n if (transaction_.type === 'eip2930') {\n delete transaction_.maxFeePerBlobGas;\n delete transaction_.maxFeePerGas;\n delete transaction_.maxPriorityFeePerGas;\n }\n if (transaction_.type === 'eip1559') {\n delete transaction_.maxFeePerBlobGas;\n }\n return transaction_;\n}\nexport const defineTransaction = /*#__PURE__*/ defineFormatter('transaction', formatTransaction);\n//////////////////////////////////////////////////////////////////////////////\nfunction formatAuthorizationList(authorizationList) {\n return authorizationList.map((authorization) => ({\n address: authorization.address,\n chainId: Number(authorization.chainId),\n nonce: Number(authorization.nonce),\n r: authorization.r,\n s: authorization.s,\n yParity: Number(authorization.yParity),\n }));\n}\n//# sourceMappingURL=transaction.js.map","import { defineFormatter } from './formatter.js';\nimport { formatTransaction } from './transaction.js';\nexport function formatBlock(block, _) {\n const transactions = (block.transactions ?? []).map((transaction) => {\n if (typeof transaction === 'string')\n return transaction;\n return formatTransaction(transaction);\n });\n return {\n ...block,\n baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,\n blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined,\n difficulty: block.difficulty ? BigInt(block.difficulty) : undefined,\n excessBlobGas: block.excessBlobGas\n ? BigInt(block.excessBlobGas)\n : undefined,\n gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined,\n gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined,\n hash: block.hash ? block.hash : null,\n logsBloom: block.logsBloom ? block.logsBloom : null,\n nonce: block.nonce ? block.nonce : null,\n number: block.number ? BigInt(block.number) : null,\n size: block.size ? BigInt(block.size) : undefined,\n timestamp: block.timestamp ? BigInt(block.timestamp) : undefined,\n transactions,\n totalDifficulty: block.totalDifficulty\n ? BigInt(block.totalDifficulty)\n : null,\n };\n}\nexport const defineBlock = /*#__PURE__*/ defineFormatter('block', formatBlock);\n//# sourceMappingURL=block.js.map","export function formatLog(log, { args, eventName, } = {}) {\n return {\n ...log,\n blockHash: log.blockHash ? log.blockHash : null,\n blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,\n logIndex: log.logIndex ? Number(log.logIndex) : null,\n transactionHash: log.transactionHash ? log.transactionHash : null,\n transactionIndex: log.transactionIndex\n ? Number(log.transactionIndex)\n : null,\n ...(eventName ? { args, eventName } : {}),\n };\n}\n//# sourceMappingURL=log.js.map","import { hexToNumber } from '../encoding/fromHex.js';\nimport { defineFormatter } from './formatter.js';\nimport { formatLog } from './log.js';\nimport { transactionType } from './transaction.js';\nexport const receiptStatuses = {\n '0x0': 'reverted',\n '0x1': 'success',\n};\nexport function formatTransactionReceipt(transactionReceipt, _) {\n const receipt = {\n ...transactionReceipt,\n blockNumber: transactionReceipt.blockNumber\n ? BigInt(transactionReceipt.blockNumber)\n : null,\n contractAddress: transactionReceipt.contractAddress\n ? transactionReceipt.contractAddress\n : null,\n cumulativeGasUsed: transactionReceipt.cumulativeGasUsed\n ? BigInt(transactionReceipt.cumulativeGasUsed)\n : null,\n effectiveGasPrice: transactionReceipt.effectiveGasPrice\n ? BigInt(transactionReceipt.effectiveGasPrice)\n : null,\n gasUsed: transactionReceipt.gasUsed\n ? BigInt(transactionReceipt.gasUsed)\n : null,\n logs: transactionReceipt.logs\n ? transactionReceipt.logs.map((log) => formatLog(log))\n : null,\n to: transactionReceipt.to ? transactionReceipt.to : null,\n transactionIndex: transactionReceipt.transactionIndex\n ? hexToNumber(transactionReceipt.transactionIndex)\n : null,\n status: transactionReceipt.status\n ? receiptStatuses[transactionReceipt.status]\n : null,\n type: transactionReceipt.type\n ? transactionType[transactionReceipt.type] || transactionReceipt.type\n : null,\n };\n if (transactionReceipt.blobGasPrice)\n receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice);\n if (transactionReceipt.blobGasUsed)\n receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed);\n return receipt;\n}\nexport const defineTransactionReceipt = /*#__PURE__*/ defineFormatter('transactionReceipt', formatTransactionReceipt);\n//# sourceMappingURL=transactionReceipt.js.map","import { bytesToHex, numberToHex } from '../encoding/toHex.js';\nimport { defineFormatter } from './formatter.js';\nexport const rpcTransactionType = {\n legacy: '0x0',\n eip2930: '0x1',\n eip1559: '0x2',\n eip4844: '0x3',\n eip7702: '0x4',\n};\nexport function formatTransactionRequest(request, _) {\n const rpcRequest = {};\n if (typeof request.authorizationList !== 'undefined')\n rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList);\n if (typeof request.accessList !== 'undefined')\n rpcRequest.accessList = request.accessList;\n if (typeof request.blobVersionedHashes !== 'undefined')\n rpcRequest.blobVersionedHashes = request.blobVersionedHashes;\n if (typeof request.blobs !== 'undefined') {\n if (typeof request.blobs[0] !== 'string')\n rpcRequest.blobs = request.blobs.map((x) => bytesToHex(x));\n else\n rpcRequest.blobs = request.blobs;\n }\n if (typeof request.data !== 'undefined')\n rpcRequest.data = request.data;\n if (request.account)\n rpcRequest.from = request.account.address;\n if (typeof request.from !== 'undefined')\n rpcRequest.from = request.from;\n if (typeof request.gas !== 'undefined')\n rpcRequest.gas = numberToHex(request.gas);\n if (typeof request.gasPrice !== 'undefined')\n rpcRequest.gasPrice = numberToHex(request.gasPrice);\n if (typeof request.maxFeePerBlobGas !== 'undefined')\n rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas);\n if (typeof request.maxFeePerGas !== 'undefined')\n rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas);\n if (typeof request.maxPriorityFeePerGas !== 'undefined')\n rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas);\n if (typeof request.nonce !== 'undefined')\n rpcRequest.nonce = numberToHex(request.nonce);\n if (typeof request.to !== 'undefined')\n rpcRequest.to = request.to;\n if (typeof request.type !== 'undefined')\n rpcRequest.type = rpcTransactionType[request.type];\n if (typeof request.value !== 'undefined')\n rpcRequest.value = numberToHex(request.value);\n return rpcRequest;\n}\nexport const defineTransactionRequest = /*#__PURE__*/ defineFormatter('transactionRequest', formatTransactionRequest);\n//////////////////////////////////////////////////////////////////////////////\nfunction formatAuthorizationList(authorizationList) {\n return authorizationList.map((authorization) => ({\n address: authorization.address,\n r: authorization.r\n ? numberToHex(BigInt(authorization.r))\n : authorization.r,\n s: authorization.s\n ? numberToHex(BigInt(authorization.s))\n : authorization.s,\n chainId: numberToHex(authorization.chainId),\n nonce: numberToHex(authorization.nonce),\n ...(typeof authorization.yParity !== 'undefined'\n ? { yParity: numberToHex(authorization.yParity) }\n : {}),\n ...(typeof authorization.v !== 'undefined' &&\n typeof authorization.yParity === 'undefined'\n ? { v: numberToHex(authorization.v) }\n : {}),\n }));\n}\n//# sourceMappingURL=transactionRequest.js.map","export const maxInt8 = 2n ** (8n - 1n) - 1n;\nexport const maxInt16 = 2n ** (16n - 1n) - 1n;\nexport const maxInt24 = 2n ** (24n - 1n) - 1n;\nexport const maxInt32 = 2n ** (32n - 1n) - 1n;\nexport const maxInt40 = 2n ** (40n - 1n) - 1n;\nexport const maxInt48 = 2n ** (48n - 1n) - 1n;\nexport const maxInt56 = 2n ** (56n - 1n) - 1n;\nexport const maxInt64 = 2n ** (64n - 1n) - 1n;\nexport const maxInt72 = 2n ** (72n - 1n) - 1n;\nexport const maxInt80 = 2n ** (80n - 1n) - 1n;\nexport const maxInt88 = 2n ** (88n - 1n) - 1n;\nexport const maxInt96 = 2n ** (96n - 1n) - 1n;\nexport const maxInt104 = 2n ** (104n - 1n) - 1n;\nexport const maxInt112 = 2n ** (112n - 1n) - 1n;\nexport const maxInt120 = 2n ** (120n - 1n) - 1n;\nexport const maxInt128 = 2n ** (128n - 1n) - 1n;\nexport const maxInt136 = 2n ** (136n - 1n) - 1n;\nexport const maxInt144 = 2n ** (144n - 1n) - 1n;\nexport const maxInt152 = 2n ** (152n - 1n) - 1n;\nexport const maxInt160 = 2n ** (160n - 1n) - 1n;\nexport const maxInt168 = 2n ** (168n - 1n) - 1n;\nexport const maxInt176 = 2n ** (176n - 1n) - 1n;\nexport const maxInt184 = 2n ** (184n - 1n) - 1n;\nexport const maxInt192 = 2n ** (192n - 1n) - 1n;\nexport const maxInt200 = 2n ** (200n - 1n) - 1n;\nexport const maxInt208 = 2n ** (208n - 1n) - 1n;\nexport const maxInt216 = 2n ** (216n - 1n) - 1n;\nexport const maxInt224 = 2n ** (224n - 1n) - 1n;\nexport const maxInt232 = 2n ** (232n - 1n) - 1n;\nexport const maxInt240 = 2n ** (240n - 1n) - 1n;\nexport const maxInt248 = 2n ** (248n - 1n) - 1n;\nexport const maxInt256 = 2n ** (256n - 1n) - 1n;\nexport const minInt8 = -(2n ** (8n - 1n));\nexport const minInt16 = -(2n ** (16n - 1n));\nexport const minInt24 = -(2n ** (24n - 1n));\nexport const minInt32 = -(2n ** (32n - 1n));\nexport const minInt40 = -(2n ** (40n - 1n));\nexport const minInt48 = -(2n ** (48n - 1n));\nexport const minInt56 = -(2n ** (56n - 1n));\nexport const minInt64 = -(2n ** (64n - 1n));\nexport const minInt72 = -(2n ** (72n - 1n));\nexport const minInt80 = -(2n ** (80n - 1n));\nexport const minInt88 = -(2n ** (88n - 1n));\nexport const minInt96 = -(2n ** (96n - 1n));\nexport const minInt104 = -(2n ** (104n - 1n));\nexport const minInt112 = -(2n ** (112n - 1n));\nexport const minInt120 = -(2n ** (120n - 1n));\nexport const minInt128 = -(2n ** (128n - 1n));\nexport const minInt136 = -(2n ** (136n - 1n));\nexport const minInt144 = -(2n ** (144n - 1n));\nexport const minInt152 = -(2n ** (152n - 1n));\nexport const minInt160 = -(2n ** (160n - 1n));\nexport const minInt168 = -(2n ** (168n - 1n));\nexport const minInt176 = -(2n ** (176n - 1n));\nexport const minInt184 = -(2n ** (184n - 1n));\nexport const minInt192 = -(2n ** (192n - 1n));\nexport const minInt200 = -(2n ** (200n - 1n));\nexport const minInt208 = -(2n ** (208n - 1n));\nexport const minInt216 = -(2n ** (216n - 1n));\nexport const minInt224 = -(2n ** (224n - 1n));\nexport const minInt232 = -(2n ** (232n - 1n));\nexport const minInt240 = -(2n ** (240n - 1n));\nexport const minInt248 = -(2n ** (248n - 1n));\nexport const minInt256 = -(2n ** (256n - 1n));\nexport const maxUint8 = 2n ** 8n - 1n;\nexport const maxUint16 = 2n ** 16n - 1n;\nexport const maxUint24 = 2n ** 24n - 1n;\nexport const maxUint32 = 2n ** 32n - 1n;\nexport const maxUint40 = 2n ** 40n - 1n;\nexport const maxUint48 = 2n ** 48n - 1n;\nexport const maxUint56 = 2n ** 56n - 1n;\nexport const maxUint64 = 2n ** 64n - 1n;\nexport const maxUint72 = 2n ** 72n - 1n;\nexport const maxUint80 = 2n ** 80n - 1n;\nexport const maxUint88 = 2n ** 88n - 1n;\nexport const maxUint96 = 2n ** 96n - 1n;\nexport const maxUint104 = 2n ** 104n - 1n;\nexport const maxUint112 = 2n ** 112n - 1n;\nexport const maxUint120 = 2n ** 120n - 1n;\nexport const maxUint128 = 2n ** 128n - 1n;\nexport const maxUint136 = 2n ** 136n - 1n;\nexport const maxUint144 = 2n ** 144n - 1n;\nexport const maxUint152 = 2n ** 152n - 1n;\nexport const maxUint160 = 2n ** 160n - 1n;\nexport const maxUint168 = 2n ** 168n - 1n;\nexport const maxUint176 = 2n ** 176n - 1n;\nexport const maxUint184 = 2n ** 184n - 1n;\nexport const maxUint192 = 2n ** 192n - 1n;\nexport const maxUint200 = 2n ** 200n - 1n;\nexport const maxUint208 = 2n ** 208n - 1n;\nexport const maxUint216 = 2n ** 216n - 1n;\nexport const maxUint224 = 2n ** 224n - 1n;\nexport const maxUint232 = 2n ** 232n - 1n;\nexport const maxUint240 = 2n ** 240n - 1n;\nexport const maxUint248 = 2n ** 248n - 1n;\nexport const maxUint256 = 2n ** 256n - 1n;\n//# sourceMappingURL=number.js.map","export function concat(values) {\n if (typeof values[0] === 'string')\n return concatHex(values);\n return concatBytes(values);\n}\nexport function concatBytes(values) {\n let length = 0;\n for (const arr of values) {\n length += arr.length;\n }\n const result = new Uint8Array(length);\n let offset = 0;\n for (const arr of values) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\nexport function concatHex(values) {\n return `0x${values.reduce((acc, x) => acc + x.replace('0x', ''), '')}`;\n}\n//# sourceMappingURL=concat.js.map","import { BaseError } from './base.js';\nexport class NegativeOffsetError extends BaseError {\n constructor({ offset }) {\n super(`Offset \\`${offset}\\` cannot be negative.`, {\n name: 'NegativeOffsetError',\n });\n }\n}\nexport class PositionOutOfBoundsError extends BaseError {\n constructor({ length, position }) {\n super(`Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`, { name: 'PositionOutOfBoundsError' });\n }\n}\nexport class RecursiveReadLimitExceededError extends BaseError {\n constructor({ count, limit }) {\n super(`Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`, { name: 'RecursiveReadLimitExceededError' });\n }\n}\n//# sourceMappingURL=cursor.js.map","import { NegativeOffsetError, PositionOutOfBoundsError, RecursiveReadLimitExceededError, } from '../errors/cursor.js';\nconst staticCursor = {\n bytes: new Uint8Array(),\n dataView: new DataView(new ArrayBuffer(0)),\n position: 0,\n positionReadCount: new Map(),\n recursiveReadCount: 0,\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n assertReadLimit() {\n if (this.recursiveReadCount >= this.recursiveReadLimit)\n throw new RecursiveReadLimitExceededError({\n count: this.recursiveReadCount + 1,\n limit: this.recursiveReadLimit,\n });\n },\n assertPosition(position) {\n if (position < 0 || position > this.bytes.length - 1)\n throw new PositionOutOfBoundsError({\n length: this.bytes.length,\n position,\n });\n },\n decrementPosition(offset) {\n if (offset < 0)\n throw new NegativeOffsetError({ offset });\n const position = this.position - offset;\n this.assertPosition(position);\n this.position = position;\n },\n getReadCount(position) {\n return this.positionReadCount.get(position || this.position) || 0;\n },\n incrementPosition(offset) {\n if (offset < 0)\n throw new NegativeOffsetError({ offset });\n const position = this.position + offset;\n this.assertPosition(position);\n this.position = position;\n },\n inspectByte(position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position);\n return this.bytes[position];\n },\n inspectBytes(length, position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position + length - 1);\n return this.bytes.subarray(position, position + length);\n },\n inspectUint8(position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position);\n return this.bytes[position];\n },\n inspectUint16(position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position + 1);\n return this.dataView.getUint16(position);\n },\n inspectUint24(position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position + 2);\n return ((this.dataView.getUint16(position) << 8) +\n this.dataView.getUint8(position + 2));\n },\n inspectUint32(position_) {\n const position = position_ ?? this.position;\n this.assertPosition(position + 3);\n return this.dataView.getUint32(position);\n },\n pushByte(byte) {\n this.assertPosition(this.position);\n this.bytes[this.position] = byte;\n this.position++;\n },\n pushBytes(bytes) {\n this.assertPosition(this.position + bytes.length - 1);\n this.bytes.set(bytes, this.position);\n this.position += bytes.length;\n },\n pushUint8(value) {\n this.assertPosition(this.position);\n this.bytes[this.position] = value;\n this.position++;\n },\n pushUint16(value) {\n this.assertPosition(this.position + 1);\n this.dataView.setUint16(this.position, value);\n this.position += 2;\n },\n pushUint24(value) {\n this.assertPosition(this.position + 2);\n this.dataView.setUint16(this.position, value >> 8);\n this.dataView.setUint8(this.position + 2, value & ~4294967040);\n this.position += 3;\n },\n pushUint32(value) {\n this.assertPosition(this.position + 3);\n this.dataView.setUint32(this.position, value);\n this.position += 4;\n },\n readByte() {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectByte();\n this.position++;\n return value;\n },\n readBytes(length, size) {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectBytes(length);\n this.position += size ?? length;\n return value;\n },\n readUint8() {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectUint8();\n this.position += 1;\n return value;\n },\n readUint16() {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectUint16();\n this.position += 2;\n return value;\n },\n readUint24() {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectUint24();\n this.position += 3;\n return value;\n },\n readUint32() {\n this.assertReadLimit();\n this._touch();\n const value = this.inspectUint32();\n this.position += 4;\n return value;\n },\n get remaining() {\n return this.bytes.length - this.position;\n },\n setPosition(position) {\n const oldPosition = this.position;\n this.assertPosition(position);\n this.position = position;\n return () => (this.position = oldPosition);\n },\n _touch() {\n if (this.recursiveReadLimit === Number.POSITIVE_INFINITY)\n return;\n const count = this.getReadCount();\n this.positionReadCount.set(this.position, count + 1);\n if (count > 0)\n this.recursiveReadCount++;\n },\n};\nexport function createCursor(bytes, { recursiveReadLimit = 8_192 } = {}) {\n const cursor = Object.create(staticCursor);\n cursor.bytes = bytes;\n cursor.dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n cursor.positionReadCount = new Map();\n cursor.recursiveReadLimit = recursiveReadLimit;\n return cursor;\n}\n//# sourceMappingURL=cursor.js.map","import { BaseError } from '../../errors/base.js';\nimport { createCursor, } from '../cursor.js';\nimport { hexToBytes } from './toBytes.js';\nimport { bytesToHex } from './toHex.js';\nexport function toRlp(bytes, to = 'hex') {\n const encodable = getEncodable(bytes);\n const cursor = createCursor(new Uint8Array(encodable.length));\n encodable.encode(cursor);\n if (to === 'hex')\n return bytesToHex(cursor.bytes);\n return cursor.bytes;\n}\nexport function bytesToRlp(bytes, to = 'bytes') {\n return toRlp(bytes, to);\n}\nexport function hexToRlp(hex, to = 'hex') {\n return toRlp(hex, to);\n}\nfunction getEncodable(bytes) {\n if (Array.isArray(bytes))\n return getEncodableList(bytes.map((x) => getEncodable(x)));\n return getEncodableBytes(bytes);\n}\nfunction getEncodableList(list) {\n const bodyLength = list.reduce((acc, x) => acc + x.length, 0);\n const sizeOfBodyLength = getSizeOfLength(bodyLength);\n const length = (() => {\n if (bodyLength <= 55)\n return 1 + bodyLength;\n return 1 + sizeOfBodyLength + bodyLength;\n })();\n return {\n length,\n encode(cursor) {\n if (bodyLength <= 55) {\n cursor.pushByte(0xc0 + bodyLength);\n }\n else {\n cursor.pushByte(0xc0 + 55 + sizeOfBodyLength);\n if (sizeOfBodyLength === 1)\n cursor.pushUint8(bodyLength);\n else if (sizeOfBodyLength === 2)\n cursor.pushUint16(bodyLength);\n else if (sizeOfBodyLength === 3)\n cursor.pushUint24(bodyLength);\n else\n cursor.pushUint32(bodyLength);\n }\n for (const { encode } of list) {\n encode(cursor);\n }\n },\n };\n}\nfunction getEncodableBytes(bytesOrHex) {\n const bytes = typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex;\n const sizeOfBytesLength = getSizeOfLength(bytes.length);\n const length = (() => {\n if (bytes.length === 1 && bytes[0] < 0x80)\n return 1;\n if (bytes.length <= 55)\n return 1 + bytes.length;\n return 1 + sizeOfBytesLength + bytes.length;\n })();\n return {\n length,\n encode(cursor) {\n if (bytes.length === 1 && bytes[0] < 0x80) {\n cursor.pushBytes(bytes);\n }\n else if (bytes.length <= 55) {\n cursor.pushByte(0x80 + bytes.length);\n cursor.pushBytes(bytes);\n }\n else {\n cursor.pushByte(0x80 + 55 + sizeOfBytesLength);\n if (sizeOfBytesLength === 1)\n cursor.pushUint8(bytes.length);\n else if (sizeOfBytesLength === 2)\n cursor.pushUint16(bytes.length);\n else if (sizeOfBytesLength === 3)\n cursor.pushUint24(bytes.length);\n else\n cursor.pushUint32(bytes.length);\n cursor.pushBytes(bytes);\n }\n },\n };\n}\nfunction getSizeOfLength(length) {\n if (length < 2 ** 8)\n return 1;\n if (length < 2 ** 16)\n return 2;\n if (length < 2 ** 24)\n return 3;\n if (length < 2 ** 32)\n return 4;\n throw new BaseError('Length is too large.');\n}\n//# sourceMappingURL=toRlp.js.map","export const etherUnits = {\n gwei: 9,\n wei: 18,\n};\nexport const gweiUnits = {\n ether: -9,\n wei: 9,\n};\nexport const weiUnits = {\n ether: -18,\n gwei: -9,\n};\n//# sourceMappingURL=unit.js.map","/**\n * Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number..\n *\n * - Docs: https://viem.sh/docs/utilities/formatUnits\n *\n * @example\n * import { formatUnits } from 'viem'\n *\n * formatUnits(420000000000n, 9)\n * // '420'\n */\nexport function formatUnits(value, decimals) {\n let display = value.toString();\n const negative = display.startsWith('-');\n if (negative)\n display = display.slice(1);\n display = display.padStart(decimals, '0');\n let [integer, fraction] = [\n display.slice(0, display.length - decimals),\n display.slice(display.length - decimals),\n ];\n fraction = fraction.replace(/(0+)$/, '');\n return `${negative ? '-' : ''}${integer || '0'}${fraction ? `.${fraction}` : ''}`;\n}\n//# sourceMappingURL=formatUnits.js.map","import { gweiUnits } from '../../constants/unit.js';\nimport { formatUnits } from './formatUnits.js';\n/**\n * Converts numerical wei to a string representation of gwei.\n *\n * - Docs: https://viem.sh/docs/utilities/formatGwei\n *\n * @example\n * import { formatGwei } from 'viem'\n *\n * formatGwei(1000000000n)\n * // '1'\n */\nexport function formatGwei(wei, unit = 'wei') {\n return formatUnits(wei, gweiUnits[unit]);\n}\n//# sourceMappingURL=formatGwei.js.map","import { formatEther } from '../utils/unit/formatEther.js';\nimport { formatGwei } from '../utils/unit/formatGwei.js';\nimport { BaseError } from './base.js';\nexport function prettyPrint(args) {\n const entries = Object.entries(args)\n .map(([key, value]) => {\n if (value === undefined || value === false)\n return null;\n return [key, value];\n })\n .filter(Boolean);\n const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0);\n return entries\n .map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`)\n .join('\\n');\n}\nexport class FeeConflictError extends BaseError {\n constructor() {\n super([\n 'Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.',\n 'Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others.',\n ].join('\\n'), { name: 'FeeConflictError' });\n }\n}\nexport class InvalidLegacyVError extends BaseError {\n constructor({ v }) {\n super(`Invalid \\`v\\` value \"${v}\". Expected 27 or 28.`, {\n name: 'InvalidLegacyVError',\n });\n }\n}\nexport class InvalidSerializableTransactionError extends BaseError {\n constructor({ transaction }) {\n super('Cannot infer a transaction type from provided transaction.', {\n metaMessages: [\n 'Provided Transaction:',\n '{',\n prettyPrint(transaction),\n '}',\n '',\n 'To infer the type, either provide:',\n '- a `type` to the Transaction, or',\n '- an EIP-1559 Transaction with `maxFeePerGas`, or',\n '- an EIP-2930 Transaction with `gasPrice` & `accessList`, or',\n '- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or',\n '- an EIP-7702 Transaction with `authorizationList`, or',\n '- a Legacy Transaction with `gasPrice`',\n ],\n name: 'InvalidSerializableTransactionError',\n });\n }\n}\nexport class InvalidSerializedTransactionTypeError extends BaseError {\n constructor({ serializedType }) {\n super(`Serialized transaction type \"${serializedType}\" is invalid.`, {\n name: 'InvalidSerializedTransactionType',\n });\n Object.defineProperty(this, \"serializedType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.serializedType = serializedType;\n }\n}\nexport class InvalidSerializedTransactionError extends BaseError {\n constructor({ attributes, serializedTransaction, type, }) {\n const missing = Object.entries(attributes)\n .map(([key, value]) => (typeof value === 'undefined' ? key : undefined))\n .filter(Boolean);\n super(`Invalid serialized transaction of type \"${type}\" was provided.`, {\n metaMessages: [\n `Serialized Transaction: \"${serializedTransaction}\"`,\n missing.length > 0 ? `Missing Attributes: ${missing.join(', ')}` : '',\n ].filter(Boolean),\n name: 'InvalidSerializedTransactionError',\n });\n Object.defineProperty(this, \"serializedTransaction\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"type\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.serializedTransaction = serializedTransaction;\n this.type = type;\n }\n}\nexport class InvalidStorageKeySizeError extends BaseError {\n constructor({ storageKey }) {\n super(`Size for storage key \"${storageKey}\" is invalid. Expected 32 bytes. Got ${Math.floor((storageKey.length - 2) / 2)} bytes.`, { name: 'InvalidStorageKeySizeError' });\n }\n}\nexport class TransactionExecutionError extends BaseError {\n constructor(cause, { account, docsPath, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, }) {\n const prettyArgs = prettyPrint({\n chain: chain && `${chain?.name} (id: ${chain?.id})`,\n from: account?.address,\n to,\n value: typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice: typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas: typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n });\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Request Arguments:',\n prettyArgs,\n ].filter(Boolean),\n name: 'TransactionExecutionError',\n });\n Object.defineProperty(this, \"cause\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.cause = cause;\n }\n}\nexport class TransactionNotFoundError extends BaseError {\n constructor({ blockHash, blockNumber, blockTag, hash, index, }) {\n let identifier = 'Transaction';\n if (blockTag && index !== undefined)\n identifier = `Transaction at block time \"${blockTag}\" at index \"${index}\"`;\n if (blockHash && index !== undefined)\n identifier = `Transaction at block hash \"${blockHash}\" at index \"${index}\"`;\n if (blockNumber && index !== undefined)\n identifier = `Transaction at block number \"${blockNumber}\" at index \"${index}\"`;\n if (hash)\n identifier = `Transaction with hash \"${hash}\"`;\n super(`${identifier} could not be found.`, {\n name: 'TransactionNotFoundError',\n });\n }\n}\nexport class TransactionReceiptNotFoundError extends BaseError {\n constructor({ hash }) {\n super(`Transaction receipt with hash \"${hash}\" could not be found. The Transaction may not be processed on a block yet.`, {\n name: 'TransactionReceiptNotFoundError',\n });\n }\n}\nexport class TransactionReceiptRevertedError extends BaseError {\n constructor({ receipt }) {\n super(`Transaction with hash \"${receipt.transactionHash}\" reverted.`, {\n metaMessages: [\n 'The receipt marked the transaction as \"reverted\". This could mean that the function on the contract you are trying to call threw an error.',\n ' ',\n 'You can attempt to extract the revert reason by:',\n '- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract',\n '- using the `call` Action with raw `data`',\n ],\n name: 'TransactionReceiptRevertedError',\n });\n Object.defineProperty(this, \"receipt\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.receipt = receipt;\n }\n}\nexport class WaitForTransactionReceiptTimeoutError extends BaseError {\n constructor({ hash }) {\n super(`Timed out while waiting for transaction with hash \"${hash}\" to be confirmed.`, { name: 'WaitForTransactionReceiptTimeoutError' });\n }\n}\n//# sourceMappingURL=transaction.js.map","import { toHex } from '../encoding/toHex.js';\nimport { toYParitySignatureArray } from '../transaction/serializeTransaction.js';\n/*\n * Serializes an EIP-7702 authorization list.\n */\nexport function serializeAuthorizationList(authorizationList) {\n if (!authorizationList || authorizationList.length === 0)\n return [];\n const serializedAuthorizationList = [];\n for (const authorization of authorizationList) {\n const { chainId, nonce, ...signature } = authorization;\n const contractAddress = authorization.address;\n serializedAuthorizationList.push([\n chainId ? toHex(chainId) : '0x',\n contractAddress,\n nonce ? toHex(nonce) : '0x',\n ...toYParitySignatureArray({}, signature),\n ]);\n }\n return serializedAuthorizationList;\n}\n//# sourceMappingURL=serializeAuthorizationList.js.map","import { hexToBytes } from '../encoding/toBytes.js';\nimport { bytesToHex } from '../encoding/toHex.js';\n/**\n * Compute commitments from a list of blobs.\n *\n * @example\n * ```ts\n * import { blobsToCommitments, toBlobs } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * ```\n */\nexport function blobsToCommitments(parameters) {\n const { kzg } = parameters;\n const to = parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes');\n const blobs = (typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x))\n : parameters.blobs);\n const commitments = [];\n for (const blob of blobs)\n commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)));\n return (to === 'bytes'\n ? commitments\n : commitments.map((x) => bytesToHex(x)));\n}\n//# sourceMappingURL=blobsToCommitments.js.map","import { hexToBytes } from '../encoding/toBytes.js';\nimport { bytesToHex } from '../encoding/toHex.js';\n/**\n * Compute the proofs for a list of blobs and their commitments.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n * ```\n */\nexport function blobsToProofs(parameters) {\n const { kzg } = parameters;\n const to = parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes');\n const blobs = (typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x))\n : parameters.blobs);\n const commitments = (typeof parameters.commitments[0] === 'string'\n ? parameters.commitments.map((x) => hexToBytes(x))\n : parameters.commitments);\n const proofs = [];\n for (let i = 0; i < blobs.length; i++) {\n const blob = blobs[i];\n const commitment = commitments[i];\n proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)));\n }\n return (to === 'bytes'\n ? proofs\n : proofs.map((x) => bytesToHex(x)));\n}\n//# sourceMappingURL=blobsToProofs.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport { SHA224 as SHA224n, sha224 as sha224n, SHA256 as SHA256n, sha256 as sha256n, } from \"./sha2.js\";\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256 = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256 = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224 = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224 = sha224n;\n//# sourceMappingURL=sha256.js.map","import { sha256 as noble_sha256 } from '@noble/hashes/sha256';\nimport { isHex } from '../data/isHex.js';\nimport { toBytes } from '../encoding/toBytes.js';\nimport { toHex } from '../encoding/toHex.js';\nexport function sha256(value, to_) {\n const to = to_ || 'hex';\n const bytes = noble_sha256(isHex(value, { strict: false }) ? toBytes(value) : value);\n if (to === 'bytes')\n return bytes;\n return toHex(bytes);\n}\n//# sourceMappingURL=sha256.js.map","import { bytesToHex } from '../encoding/toHex.js';\nimport { sha256 } from '../hash/sha256.js';\n/**\n * Transform a commitment to it's versioned hash.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentToVersionedHash,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const [commitment] = blobsToCommitments({ blobs, kzg })\n * const versionedHash = commitmentToVersionedHash({ commitment })\n * ```\n */\nexport function commitmentToVersionedHash(parameters) {\n const { commitment, version = 1 } = parameters;\n const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes');\n const versionedHash = sha256(commitment, 'bytes');\n versionedHash.set([version], 0);\n return (to === 'bytes' ? versionedHash : bytesToHex(versionedHash));\n}\n//# sourceMappingURL=commitmentToVersionedHash.js.map","import { commitmentToVersionedHash, } from './commitmentToVersionedHash.js';\n/**\n * Transform a list of commitments to their versioned hashes.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentsToVersionedHashes,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const versionedHashes = commitmentsToVersionedHashes({ commitments })\n * ```\n */\nexport function commitmentsToVersionedHashes(parameters) {\n const { commitments, version } = parameters;\n const to = parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes');\n const hashes = [];\n for (const commitment of commitments) {\n hashes.push(commitmentToVersionedHash({\n commitment,\n to,\n version,\n }));\n }\n return hashes;\n}\n//# sourceMappingURL=commitmentsToVersionedHashes.js.map","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n/** Blob limit per transaction. */\nconst blobsPerTransaction = 6;\n/** The number of bytes in a BLS scalar field element. */\nexport const bytesPerFieldElement = 32;\n/** The number of field elements in a blob. */\nexport const fieldElementsPerBlob = 4096;\n/** The number of bytes in a blob. */\nexport const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob;\n/** Blob bytes limit per transaction. */\nexport const maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction -\n // terminator byte (0x80).\n 1 -\n // zero byte (0x00) appended to each field element.\n 1 * fieldElementsPerBlob * blobsPerTransaction;\n//# sourceMappingURL=blob.js.map","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\nexport const versionedHashVersionKzg = 1;\n//# sourceMappingURL=kzg.js.map","import { versionedHashVersionKzg } from '../constants/kzg.js';\nimport { BaseError } from './base.js';\nexport class BlobSizeTooLargeError extends BaseError {\n constructor({ maxSize, size }) {\n super('Blob size is too large.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],\n name: 'BlobSizeTooLargeError',\n });\n }\n}\nexport class EmptyBlobError extends BaseError {\n constructor() {\n super('Blob data must not be empty.', { name: 'EmptyBlobError' });\n }\n}\nexport class InvalidVersionedHashSizeError extends BaseError {\n constructor({ hash, size, }) {\n super(`Versioned hash \"${hash}\" size is invalid.`, {\n metaMessages: ['Expected: 32', `Received: ${size}`],\n name: 'InvalidVersionedHashSizeError',\n });\n }\n}\nexport class InvalidVersionedHashVersionError extends BaseError {\n constructor({ hash, version, }) {\n super(`Versioned hash \"${hash}\" version is invalid.`, {\n metaMessages: [\n `Expected: ${versionedHashVersionKzg}`,\n `Received: ${version}`,\n ],\n name: 'InvalidVersionedHashVersionError',\n });\n }\n}\n//# sourceMappingURL=blob.js.map","import { bytesPerBlob, bytesPerFieldElement, fieldElementsPerBlob, maxBytesPerTransaction, } from '../../constants/blob.js';\nimport { BlobSizeTooLargeError, EmptyBlobError, } from '../../errors/blob.js';\nimport { createCursor } from '../cursor.js';\nimport { size } from '../data/size.js';\nimport { hexToBytes } from '../encoding/toBytes.js';\nimport { bytesToHex } from '../encoding/toHex.js';\n/**\n * Transforms arbitrary data to blobs.\n *\n * @example\n * ```ts\n * import { toBlobs, stringToHex } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * ```\n */\nexport function toBlobs(parameters) {\n const to = parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes');\n const data = (typeof parameters.data === 'string'\n ? hexToBytes(parameters.data)\n : parameters.data);\n const size_ = size(data);\n if (!size_)\n throw new EmptyBlobError();\n if (size_ > maxBytesPerTransaction)\n throw new BlobSizeTooLargeError({\n maxSize: maxBytesPerTransaction,\n size: size_,\n });\n const blobs = [];\n let active = true;\n let position = 0;\n while (active) {\n const blob = createCursor(new Uint8Array(bytesPerBlob));\n let size = 0;\n while (size < fieldElementsPerBlob) {\n const bytes = data.slice(position, position + (bytesPerFieldElement - 1));\n // Push a zero byte so the field element doesn't overflow the BLS modulus.\n blob.pushByte(0x00);\n // Push the current segment of data bytes.\n blob.pushBytes(bytes);\n // If we detect that the current segment of data bytes is less than 31 bytes,\n // we can stop processing and push a terminator byte to indicate the end of the blob.\n if (bytes.length < 31) {\n blob.pushByte(0x80);\n active = false;\n break;\n }\n size++;\n position += 31;\n }\n blobs.push(blob);\n }\n return (to === 'bytes'\n ? blobs.map((x) => x.bytes)\n : blobs.map((x) => bytesToHex(x.bytes)));\n}\n//# sourceMappingURL=toBlobs.js.map","import { blobsToCommitments, } from './blobsToCommitments.js';\nimport { blobsToProofs } from './blobsToProofs.js';\nimport { toBlobs } from './toBlobs.js';\n/**\n * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.\n *\n * @example\n * ```ts\n * import { toBlobSidecars, stringToHex } from 'viem'\n *\n * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })\n * ```\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs,\n * blobsToProofs,\n * toBlobSidecars,\n * stringToHex\n * } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n *\n * const sidecars = toBlobSidecars({ blobs, commitments, proofs })\n * ```\n */\nexport function toBlobSidecars(parameters) {\n const { data, kzg, to } = parameters;\n const blobs = parameters.blobs ?? toBlobs({ data: data, to });\n const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg, to });\n const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg, to });\n const sidecars = [];\n for (let i = 0; i < blobs.length; i++)\n sidecars.push({\n blob: blobs[i],\n commitment: commitments[i],\n proof: proofs[i],\n });\n return sidecars;\n}\n//# sourceMappingURL=toBlobSidecars.js.map","import { BaseError } from './base.js';\nexport class InvalidAddressError extends BaseError {\n constructor({ address }) {\n super(`Address \"${address}\" is invalid.`, {\n metaMessages: [\n '- Address must be a hex value of 20 bytes (40 hex characters).',\n '- Address must match its checksum counterpart.',\n ],\n name: 'InvalidAddressError',\n });\n }\n}\n//# sourceMappingURL=address.js.map","import { BaseError } from './base.js';\nexport class ChainDoesNotSupportContract extends BaseError {\n constructor({ blockNumber, chain, contract, }) {\n super(`Chain \"${chain.name}\" does not support contract \"${contract.name}\".`, {\n metaMessages: [\n 'This could be due to any of the following:',\n ...(blockNumber &&\n contract.blockCreated &&\n contract.blockCreated > blockNumber\n ? [\n `- The contract \"${contract.name}\" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).`,\n ]\n : [\n `- The chain does not have the contract \"${contract.name}\" configured.`,\n ]),\n ],\n name: 'ChainDoesNotSupportContract',\n });\n }\n}\nexport class ChainMismatchError extends BaseError {\n constructor({ chain, currentChainId, }) {\n super(`The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} – ${chain.name}).`, {\n metaMessages: [\n `Current Chain ID: ${currentChainId}`,\n `Expected Chain ID: ${chain.id} – ${chain.name}`,\n ],\n name: 'ChainMismatchError',\n });\n }\n}\nexport class ChainNotFoundError extends BaseError {\n constructor() {\n super([\n 'No chain was provided to the request.',\n 'Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient.',\n ].join('\\n'), {\n name: 'ChainNotFoundError',\n });\n }\n}\nexport class ClientChainNotConfiguredError extends BaseError {\n constructor() {\n super('No chain was provided to the Client.', {\n name: 'ClientChainNotConfiguredError',\n });\n }\n}\nexport class InvalidChainIdError extends BaseError {\n constructor({ chainId }) {\n super(typeof chainId === 'number'\n ? `Chain ID \"${chainId}\" is invalid.`\n : 'Chain ID is invalid.', { name: 'InvalidChainIdError' });\n }\n}\n//# sourceMappingURL=chain.js.map","import { formatGwei } from '../utils/unit/formatGwei.js';\nimport { BaseError } from './base.js';\nexport class ExecutionRevertedError extends BaseError {\n constructor({ cause, message, } = {}) {\n const reason = message\n ?.replace('execution reverted: ', '')\n ?.replace('execution reverted', '');\n super(`Execution reverted ${reason ? `with reason: ${reason}` : 'for an unknown reason'}.`, {\n cause,\n name: 'ExecutionRevertedError',\n });\n }\n}\nObject.defineProperty(ExecutionRevertedError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 3\n});\nObject.defineProperty(ExecutionRevertedError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /execution reverted/\n});\nexport class FeeCapTooHighError extends BaseError {\n constructor({ cause, maxFeePerGas, } = {}) {\n super(`The fee cap (\\`maxFeePerGas\\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''}) cannot be higher than the maximum allowed value (2^256-1).`, {\n cause,\n name: 'FeeCapTooHighError',\n });\n }\n}\nObject.defineProperty(FeeCapTooHighError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /max fee per gas higher than 2\\^256-1|fee cap higher than 2\\^256-1/\n});\nexport class FeeCapTooLowError extends BaseError {\n constructor({ cause, maxFeePerGas, } = {}) {\n super(`The fee cap (\\`maxFeePerGas\\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ''} gwei) cannot be lower than the block base fee.`, {\n cause,\n name: 'FeeCapTooLowError',\n });\n }\n}\nObject.defineProperty(FeeCapTooLowError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/\n});\nexport class NonceTooHighError extends BaseError {\n constructor({ cause, nonce, } = {}) {\n super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ''}is higher than the next one expected.`, { cause, name: 'NonceTooHighError' });\n }\n}\nObject.defineProperty(NonceTooHighError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /nonce too high/\n});\nexport class NonceTooLowError extends BaseError {\n constructor({ cause, nonce, } = {}) {\n super([\n `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ''}is lower than the current nonce of the account.`,\n 'Try increasing the nonce or find the latest nonce with `getTransactionCount`.',\n ].join('\\n'), { cause, name: 'NonceTooLowError' });\n }\n}\nObject.defineProperty(NonceTooLowError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /nonce too low|transaction already imported|already known/\n});\nexport class NonceMaxValueError extends BaseError {\n constructor({ cause, nonce, } = {}) {\n super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ''}exceeds the maximum allowed nonce.`, { cause, name: 'NonceMaxValueError' });\n }\n}\nObject.defineProperty(NonceMaxValueError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /nonce has max value/\n});\nexport class InsufficientFundsError extends BaseError {\n constructor({ cause } = {}) {\n super([\n 'The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account.',\n ].join('\\n'), {\n cause,\n metaMessages: [\n 'This error could arise when the account does not have enough funds to:',\n ' - pay for the total gas fee,',\n ' - pay for the value to send.',\n ' ',\n 'The cost of the transaction is calculated as `gas * gas fee + value`, where:',\n ' - `gas` is the amount of gas needed for transaction to execute,',\n ' - `gas fee` is the gas fee,',\n ' - `value` is the amount of ether to send to the recipient.',\n ],\n name: 'InsufficientFundsError',\n });\n }\n}\nObject.defineProperty(InsufficientFundsError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /insufficient funds|exceeds transaction sender account balance/\n});\nexport class IntrinsicGasTooHighError extends BaseError {\n constructor({ cause, gas, } = {}) {\n super(`The amount of gas ${gas ? `(${gas}) ` : ''}provided for the transaction exceeds the limit allowed for the block.`, {\n cause,\n name: 'IntrinsicGasTooHighError',\n });\n }\n}\nObject.defineProperty(IntrinsicGasTooHighError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /intrinsic gas too high|gas limit reached/\n});\nexport class IntrinsicGasTooLowError extends BaseError {\n constructor({ cause, gas, } = {}) {\n super(`The amount of gas ${gas ? `(${gas}) ` : ''}provided for the transaction is too low.`, {\n cause,\n name: 'IntrinsicGasTooLowError',\n });\n }\n}\nObject.defineProperty(IntrinsicGasTooLowError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /intrinsic gas too low/\n});\nexport class TransactionTypeNotSupportedError extends BaseError {\n constructor({ cause }) {\n super('The transaction type is not supported for this chain.', {\n cause,\n name: 'TransactionTypeNotSupportedError',\n });\n }\n}\nObject.defineProperty(TransactionTypeNotSupportedError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /transaction type not valid/\n});\nexport class TipAboveFeeCapError extends BaseError {\n constructor({ cause, maxPriorityFeePerGas, maxFeePerGas, } = {}) {\n super([\n `The provided tip (\\`maxPriorityFeePerGas\\`${maxPriorityFeePerGas\n ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei`\n : ''}) cannot be higher than the fee cap (\\`maxFeePerGas\\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''}).`,\n ].join('\\n'), {\n cause,\n name: 'TipAboveFeeCapError',\n });\n }\n}\nObject.defineProperty(TipAboveFeeCapError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/\n});\nexport class UnknownNodeError extends BaseError {\n constructor({ cause }) {\n super(`An error occurred while executing: ${cause?.shortMessage}`, {\n cause,\n name: 'UnknownNodeError',\n });\n }\n}\n//# sourceMappingURL=node.js.map","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap extends Map {\n constructor(size) {\n super();\n Object.defineProperty(this, \"maxSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.maxSize = size;\n }\n get(key) {\n const value = super.get(key);\n if (super.has(key) && value !== undefined) {\n this.delete(key);\n super.set(key, value);\n }\n return value;\n }\n set(key, value) {\n super.set(key, value);\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value;\n if (firstKey)\n this.delete(firstKey);\n }\n return this;\n }\n}\n//# sourceMappingURL=lru.js.map","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./_u64.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, clean, createHasher, createXOFer, Hash, swap32IfBE, toBytes, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/** Keccak sponge function. */\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n this.enableXOF = false;\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));\n/** SHA3-224 hash function. */\nexport const sha3_224 = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\nconst genShake = (suffix, blockLen, outputLen) => createXOFer((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();\n//# sourceMappingURL=sha3.js.map","import { keccak_256 } from '@noble/hashes/sha3';\nimport { isHex } from '../data/isHex.js';\nimport { toBytes } from '../encoding/toBytes.js';\nimport { toHex } from '../encoding/toHex.js';\nexport function keccak256(value, to_) {\n const to = to_ || 'hex';\n const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value);\n if (to === 'bytes')\n return bytes;\n return toHex(bytes);\n}\n//# sourceMappingURL=keccak256.js.map","import { InvalidAddressError } from '../../errors/address.js';\nimport { stringToBytes, } from '../encoding/toBytes.js';\nimport { keccak256 } from '../hash/keccak256.js';\nimport { LruMap } from '../lru.js';\nimport { isAddress } from './isAddress.js';\nconst checksumAddressCache = /*#__PURE__*/ new LruMap(8192);\nexport function checksumAddress(address_, \n/**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\nchainId) {\n if (checksumAddressCache.has(`${address_}.${chainId}`))\n return checksumAddressCache.get(`${address_}.${chainId}`);\n const hexAddress = chainId\n ? `${chainId}${address_.toLowerCase()}`\n : address_.substring(2).toLowerCase();\n const hash = keccak256(stringToBytes(hexAddress), 'bytes');\n const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split('');\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1] >> 4 >= 8 && address[i]) {\n address[i] = address[i].toUpperCase();\n }\n if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {\n address[i + 1] = address[i + 1].toUpperCase();\n }\n }\n const result = `0x${address.join('')}`;\n checksumAddressCache.set(`${address_}.${chainId}`, result);\n return result;\n}\nexport function getAddress(address, \n/**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\nchainId) {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address });\n return checksumAddress(address, chainId);\n}\n//# sourceMappingURL=getAddress.js.map","import { LruMap } from '../lru.js';\nimport { checksumAddress } from './getAddress.js';\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/;\n/** @internal */\nexport const isAddressCache = /*#__PURE__*/ new LruMap(8192);\nexport function isAddress(address, options) {\n const { strict = true } = options ?? {};\n const cacheKey = `${address}.${strict}`;\n if (isAddressCache.has(cacheKey))\n return isAddressCache.get(cacheKey);\n const result = (() => {\n if (!addressRegex.test(address))\n return false;\n if (address.toLowerCase() === address)\n return true;\n if (strict)\n return checksumAddress(address) === address;\n return true;\n })();\n isAddressCache.set(cacheKey, result);\n return result;\n}\n//# sourceMappingURL=isAddress.js.map","import { SliceOffsetOutOfBoundsError, } from '../../errors/data.js';\nimport { isHex } from './isHex.js';\nimport { size } from './size.js';\n/**\n * @description Returns a section of the hex or byte array given a start/end bytes offset.\n *\n * @param value The hex or byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function slice(value, start, end, { strict } = {}) {\n if (isHex(value, { strict: false }))\n return sliceHex(value, start, end, {\n strict,\n });\n return sliceBytes(value, start, end, {\n strict,\n });\n}\nfunction assertStartOffset(value, start) {\n if (typeof start === 'number' && start > 0 && start > size(value) - 1)\n throw new SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: size(value),\n });\n}\nfunction assertEndOffset(value, start, end) {\n if (typeof start === 'number' &&\n typeof end === 'number' &&\n size(value) !== end - start) {\n throw new SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: size(value),\n });\n }\n}\n/**\n * @description Returns a section of the byte array given a start/end bytes offset.\n *\n * @param value The byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceBytes(value_, start, end, { strict } = {}) {\n assertStartOffset(value_, start);\n const value = value_.slice(start, end);\n if (strict)\n assertEndOffset(value, start, end);\n return value;\n}\n/**\n * @description Returns a section of the hex value given a start/end bytes offset.\n *\n * @param value The hex value to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceHex(value_, start, end, { strict } = {}) {\n assertStartOffset(value_, start);\n const value = `0x${value_\n .replace('0x', '')\n .slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`;\n if (strict)\n assertEndOffset(value, start, end);\n return value;\n}\n//# sourceMappingURL=slice.js.map","import { versionedHashVersionKzg } from '../../constants/kzg.js';\nimport { maxUint256 } from '../../constants/number.js';\nimport { InvalidAddressError, } from '../../errors/address.js';\nimport { BaseError } from '../../errors/base.js';\nimport { EmptyBlobError, InvalidVersionedHashSizeError, InvalidVersionedHashVersionError, } from '../../errors/blob.js';\nimport { InvalidChainIdError, } from '../../errors/chain.js';\nimport { FeeCapTooHighError, TipAboveFeeCapError, } from '../../errors/node.js';\nimport { isAddress } from '../address/isAddress.js';\nimport { size } from '../data/size.js';\nimport { slice } from '../data/slice.js';\nimport { hexToNumber } from '../encoding/fromHex.js';\nexport function assertTransactionEIP7702(transaction) {\n const { authorizationList } = transaction;\n if (authorizationList) {\n for (const authorization of authorizationList) {\n const { chainId } = authorization;\n const address = authorization.address;\n if (!isAddress(address))\n throw new InvalidAddressError({ address });\n if (chainId < 0)\n throw new InvalidChainIdError({ chainId });\n }\n }\n assertTransactionEIP1559(transaction);\n}\nexport function assertTransactionEIP4844(transaction) {\n const { blobVersionedHashes } = transaction;\n if (blobVersionedHashes) {\n if (blobVersionedHashes.length === 0)\n throw new EmptyBlobError();\n for (const hash of blobVersionedHashes) {\n const size_ = size(hash);\n const version = hexToNumber(slice(hash, 0, 1));\n if (size_ !== 32)\n throw new InvalidVersionedHashSizeError({ hash, size: size_ });\n if (version !== versionedHashVersionKzg)\n throw new InvalidVersionedHashVersionError({\n hash,\n version,\n });\n }\n }\n assertTransactionEIP1559(transaction);\n}\nexport function assertTransactionEIP1559(transaction) {\n const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction;\n if (chainId <= 0)\n throw new InvalidChainIdError({ chainId });\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n if (maxFeePerGas && maxFeePerGas > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas });\n if (maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas)\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });\n}\nexport function assertTransactionEIP2930(transaction) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;\n if (chainId <= 0)\n throw new InvalidChainIdError({ chainId });\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError('`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.');\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });\n}\nexport function assertTransactionLegacy(transaction) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n if (typeof chainId !== 'undefined' && chainId <= 0)\n throw new InvalidChainIdError({ chainId });\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError('`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.');\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });\n}\n//# sourceMappingURL=assertTransaction.js.map","import { InvalidSerializableTransactionError, } from '../../errors/transaction.js';\nexport function getTransactionType(transaction) {\n if (transaction.type)\n return transaction.type;\n if (typeof transaction.authorizationList !== 'undefined')\n return 'eip7702';\n if (typeof transaction.blobs !== 'undefined' ||\n typeof transaction.blobVersionedHashes !== 'undefined' ||\n typeof transaction.maxFeePerBlobGas !== 'undefined' ||\n typeof transaction.sidecars !== 'undefined')\n return 'eip4844';\n if (typeof transaction.maxFeePerGas !== 'undefined' ||\n typeof transaction.maxPriorityFeePerGas !== 'undefined') {\n return 'eip1559';\n }\n if (typeof transaction.gasPrice !== 'undefined') {\n if (typeof transaction.accessList !== 'undefined')\n return 'eip2930';\n return 'legacy';\n }\n throw new InvalidSerializableTransactionError({ transaction });\n}\n//# sourceMappingURL=getTransactionType.js.map","import { InvalidAddressError, } from '../../errors/address.js';\nimport { InvalidStorageKeySizeError, } from '../../errors/transaction.js';\nimport { isAddress } from '../address/isAddress.js';\n/*\n * Serialize an EIP-2930 access list\n * @remarks\n * Use to create a transaction serializer with support for EIP-2930 access lists\n *\n * @param accessList - Array of objects of address and arrays of Storage Keys\n * @throws InvalidAddressError, InvalidStorageKeySizeError\n * @returns Array of hex strings\n */\nexport function serializeAccessList(accessList) {\n if (!accessList || accessList.length === 0)\n return [];\n const serializedAccessList = [];\n for (let i = 0; i < accessList.length; i++) {\n const { address, storageKeys } = accessList[i];\n for (let j = 0; j < storageKeys.length; j++) {\n if (storageKeys[j].length - 2 !== 64) {\n throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] });\n }\n }\n if (!isAddress(address, { strict: false })) {\n throw new InvalidAddressError({ address });\n }\n serializedAccessList.push([address, storageKeys]);\n }\n return serializedAccessList;\n}\n//# sourceMappingURL=serializeAccessList.js.map","import { InvalidLegacyVError, } from '../../errors/transaction.js';\nimport { serializeAuthorizationList, } from '../authorization/serializeAuthorizationList.js';\nimport { blobsToCommitments, } from '../blob/blobsToCommitments.js';\nimport { blobsToProofs, } from '../blob/blobsToProofs.js';\nimport { commitmentsToVersionedHashes, } from '../blob/commitmentsToVersionedHashes.js';\nimport { toBlobSidecars, } from '../blob/toBlobSidecars.js';\nimport { concatHex } from '../data/concat.js';\nimport { trim } from '../data/trim.js';\nimport { bytesToHex, numberToHex, } from '../encoding/toHex.js';\nimport { toRlp } from '../encoding/toRlp.js';\nimport { assertTransactionEIP1559, assertTransactionEIP2930, assertTransactionEIP4844, assertTransactionEIP7702, assertTransactionLegacy, } from './assertTransaction.js';\nimport { getTransactionType, } from './getTransactionType.js';\nimport { serializeAccessList, } from './serializeAccessList.js';\nexport function serializeTransaction(transaction, signature) {\n const type = getTransactionType(transaction);\n if (type === 'eip1559')\n return serializeTransactionEIP1559(transaction, signature);\n if (type === 'eip2930')\n return serializeTransactionEIP2930(transaction, signature);\n if (type === 'eip4844')\n return serializeTransactionEIP4844(transaction, signature);\n if (type === 'eip7702')\n return serializeTransactionEIP7702(transaction, signature);\n return serializeTransactionLegacy(transaction, signature);\n}\nfunction serializeTransactionEIP7702(transaction, signature) {\n const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data, } = transaction;\n assertTransactionEIP7702(transaction);\n const serializedAccessList = serializeAccessList(accessList);\n const serializedAuthorizationList = serializeAuthorizationList(authorizationList);\n return concatHex([\n '0x04',\n toRlp([\n numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n serializedAuthorizationList,\n ...toYParitySignatureArray(transaction, signature),\n ]),\n ]);\n}\nfunction serializeTransactionEIP4844(transaction, signature) {\n const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data, } = transaction;\n assertTransactionEIP4844(transaction);\n let blobVersionedHashes = transaction.blobVersionedHashes;\n let sidecars = transaction.sidecars;\n // If `blobs` are passed, we will need to compute the KZG commitments & proofs.\n if (transaction.blobs &&\n (typeof blobVersionedHashes === 'undefined' ||\n typeof sidecars === 'undefined')) {\n const blobs = (typeof transaction.blobs[0] === 'string'\n ? transaction.blobs\n : transaction.blobs.map((x) => bytesToHex(x)));\n const kzg = transaction.kzg;\n const commitments = blobsToCommitments({\n blobs,\n kzg,\n });\n if (typeof blobVersionedHashes === 'undefined')\n blobVersionedHashes = commitmentsToVersionedHashes({\n commitments,\n });\n if (typeof sidecars === 'undefined') {\n const proofs = blobsToProofs({ blobs, commitments, kzg });\n sidecars = toBlobSidecars({ blobs, commitments, proofs });\n }\n }\n const serializedAccessList = serializeAccessList(accessList);\n const serializedTransaction = [\n numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? numberToHex(maxFeePerBlobGas) : '0x',\n blobVersionedHashes ?? [],\n ...toYParitySignatureArray(transaction, signature),\n ];\n const blobs = [];\n const commitments = [];\n const proofs = [];\n if (sidecars)\n for (let i = 0; i < sidecars.length; i++) {\n const { blob, commitment, proof } = sidecars[i];\n blobs.push(blob);\n commitments.push(commitment);\n proofs.push(proof);\n }\n return concatHex([\n '0x03',\n sidecars\n ? // If sidecars are enabled, envelope turns into a \"wrapper\":\n toRlp([serializedTransaction, blobs, commitments, proofs])\n : // If sidecars are disabled, standard envelope is used:\n toRlp(serializedTransaction),\n ]);\n}\nfunction serializeTransactionEIP1559(transaction, signature) {\n const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data, } = transaction;\n assertTransactionEIP1559(transaction);\n const serializedAccessList = serializeAccessList(accessList);\n const serializedTransaction = [\n numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ];\n return concatHex([\n '0x02',\n toRlp(serializedTransaction),\n ]);\n}\nfunction serializeTransactionEIP2930(transaction, signature) {\n const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction;\n assertTransactionEIP2930(transaction);\n const serializedAccessList = serializeAccessList(accessList);\n const serializedTransaction = [\n numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ];\n return concatHex([\n '0x01',\n toRlp(serializedTransaction),\n ]);\n}\nfunction serializeTransactionLegacy(transaction, signature) {\n const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction;\n assertTransactionLegacy(transaction);\n let serializedTransaction = [\n nonce ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n ];\n if (signature) {\n const v = (() => {\n // EIP-155 (inferred chainId)\n if (signature.v >= 35n) {\n const inferredChainId = (signature.v - 35n) / 2n;\n if (inferredChainId > 0)\n return signature.v;\n return 27n + (signature.v === 35n ? 0n : 1n);\n }\n // EIP-155 (explicit chainId)\n if (chainId > 0)\n return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n);\n // Pre-EIP-155 (no chainId)\n const v = 27n + (signature.v === 27n ? 0n : 1n);\n if (signature.v !== v)\n throw new InvalidLegacyVError({ v: signature.v });\n return v;\n })();\n const r = trim(signature.r);\n const s = trim(signature.s);\n serializedTransaction = [\n ...serializedTransaction,\n numberToHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ];\n }\n else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n numberToHex(chainId),\n '0x',\n '0x',\n ];\n }\n return toRlp(serializedTransaction);\n}\nexport function toYParitySignatureArray(transaction, signature_) {\n const signature = signature_ ?? transaction;\n const { v, yParity } = signature;\n if (typeof signature.r === 'undefined')\n return [];\n if (typeof signature.s === 'undefined')\n return [];\n if (typeof v === 'undefined' && typeof yParity === 'undefined')\n return [];\n const r = trim(signature.r);\n const s = trim(signature.s);\n const yParity_ = (() => {\n if (typeof yParity === 'number')\n return yParity ? numberToHex(1) : '0x';\n if (v === 0n)\n return '0x';\n if (v === 1n)\n return numberToHex(1);\n return v === 27n ? '0x' : numberToHex(1);\n })();\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s];\n}\n//# sourceMappingURL=serializeTransaction.js.map","/**\n * Predeploy contracts for OP Stack.\n * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md\n */\nexport const contracts = {\n gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },\n l1Block: { address: '0x4200000000000000000000000000000000000015' },\n l2CrossDomainMessenger: {\n address: '0x4200000000000000000000000000000000000007',\n },\n l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },\n l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },\n l2ToL1MessagePasser: {\n address: '0x4200000000000000000000000000000000000016',\n },\n};\n//# sourceMappingURL=contracts.js.map","import { hexToBigInt } from '../utils/encoding/fromHex.js';\nimport { defineBlock } from '../utils/formatters/block.js';\nimport { defineTransaction, formatTransaction, } from '../utils/formatters/transaction.js';\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js';\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args) {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string')\n return transaction;\n const formatted = formatTransaction(transaction);\n if (formatted.typeHex === '0x7e') {\n formatted.isSystemTx = transaction.isSystemTx;\n formatted.mint = transaction.mint\n ? hexToBigInt(transaction.mint)\n : undefined;\n formatted.sourceHash = transaction.sourceHash;\n formatted.type = 'deposit';\n }\n return formatted;\n });\n return {\n transactions,\n stateRoot: args.stateRoot,\n };\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args) {\n const transaction = {};\n if (args.type === '0x7e') {\n transaction.isSystemTx = args.isSystemTx;\n transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined;\n transaction.sourceHash = args.sourceHash;\n transaction.type = 'deposit';\n }\n return transaction;\n },\n }),\n transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({\n format(args) {\n return {\n l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,\n l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,\n l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,\n l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,\n };\n },\n }),\n};\n//# sourceMappingURL=formatters.js.map","import { InvalidAddressError } from '../errors/address.js';\nimport { isAddress } from '../utils/address/isAddress.js';\nimport { concatHex } from '../utils/data/concat.js';\nimport { toHex } from '../utils/encoding/toHex.js';\nimport { toRlp } from '../utils/encoding/toRlp.js';\nimport { serializeTransaction as serializeTransaction_, } from '../utils/transaction/serializeTransaction.js';\nexport function serializeTransaction(transaction, signature) {\n if (isDeposit(transaction))\n return serializeTransactionDeposit(transaction);\n return serializeTransaction_(transaction, signature);\n}\nexport const serializers = {\n transaction: serializeTransaction,\n};\nfunction serializeTransactionDeposit(transaction) {\n assertTransactionDeposit(transaction);\n const { sourceHash, data, from, gas, isSystemTx, mint, to, value } = transaction;\n const serializedTransaction = [\n sourceHash,\n from,\n to ?? '0x',\n mint ? toHex(mint) : '0x',\n value ? toHex(value) : '0x',\n gas ? toHex(gas) : '0x',\n isSystemTx ? '0x1' : '0x',\n data ?? '0x',\n ];\n return concatHex([\n '0x7e',\n toRlp(serializedTransaction),\n ]);\n}\nfunction isDeposit(transaction) {\n if (transaction.type === 'deposit')\n return true;\n if (typeof transaction.sourceHash !== 'undefined')\n return true;\n return false;\n}\nexport function assertTransactionDeposit(transaction) {\n const { from, to } = transaction;\n if (from && !isAddress(from))\n throw new InvalidAddressError({ address: from });\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n}\n//# sourceMappingURL=serializers.js.map","import { contracts } from './contracts.js';\nimport { formatters } from './formatters.js';\nimport { serializers } from './serializers.js';\nexport const chainConfig = {\n blockTime: 2_000,\n contracts,\n formatters,\n serializers,\n};\n//# sourceMappingURL=chainConfig.js.map","import { defineChain } from '../../utils/chain/defineChain.js';\nexport const arbitrum = /*#__PURE__*/ defineChain({\n id: 42_161,\n name: 'Arbitrum One',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n blockTime: 250,\n rpcUrls: {\n default: {\n http: ['https://arb1.arbitrum.io/rpc'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Arbiscan',\n url: 'https://arbiscan.io',\n apiUrl: 'https://api.arbiscan.io/api',\n },\n },\n contracts: {\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 7654707,\n },\n },\n});\n//# sourceMappingURL=arbitrum.js.map","import { defineChain } from '../../utils/chain/defineChain.js';\nexport const avalanche = /*#__PURE__*/ defineChain({\n id: 43_114,\n name: 'Avalanche',\n blockTime: 1_700,\n nativeCurrency: {\n decimals: 18,\n name: 'Avalanche',\n symbol: 'AVAX',\n },\n rpcUrls: {\n default: { http: ['https://api.avax.network/ext/bc/C/rpc'] },\n },\n blockExplorers: {\n default: {\n name: 'SnowTrace',\n url: 'https://snowtrace.io',\n apiUrl: 'https://api.snowtrace.io',\n },\n },\n contracts: {\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 11907934,\n },\n },\n});\n//# sourceMappingURL=avalanche.js.map","import { chainConfig } from '../../op-stack/chainConfig.js';\nimport { defineChain } from '../../utils/chain/defineChain.js';\nconst sourceId = 1; // mainnet\nexport const base = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 8453,\n name: 'Base',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://basescan.org',\n apiUrl: 'https://api.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x56315b90c40730925ec5485cf004d835058518A0',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 5022,\n },\n portal: {\n [sourceId]: {\n address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',\n blockCreated: 17482143,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',\n blockCreated: 17482143,\n },\n },\n },\n sourceId,\n});\nexport const basePreconf = /*#__PURE__*/ defineChain({\n ...base,\n experimental_preconfirmationTime: 200,\n rpcUrls: {\n default: {\n http: ['https://mainnet-preconf.base.org'],\n },\n },\n});\n//# sourceMappingURL=base.js.map","import { defineChain } from '../../utils/chain/defineChain.js';\nexport const bsc = /*#__PURE__*/ defineChain({\n id: 56,\n name: 'BNB Smart Chain',\n blockTime: 750,\n nativeCurrency: {\n decimals: 18,\n name: 'BNB',\n symbol: 'BNB',\n },\n rpcUrls: {\n default: { http: ['https://56.rpc.thirdweb.com'] },\n },\n blockExplorers: {\n default: {\n name: 'BscScan',\n url: 'https://bscscan.com',\n apiUrl: 'https://api.bscscan.com/api',\n },\n },\n contracts: {\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 15921452,\n },\n },\n});\n//# sourceMappingURL=bsc.js.map","export const fees = {\n /*\n * Estimates the fees per gas for a transaction.\n \n * If the transaction is to be paid in a token (feeCurrency is present) then the fees\n * are estimated in the value of the token. Otherwise falls back to the default\n * estimation by returning null.\n *\n * @param params fee estimation function parameters\n */\n estimateFeesPerGas: async (params) => {\n if (!params.request?.feeCurrency)\n return null;\n const [gasPrice, maxPriorityFeePerGas] = await Promise.all([\n estimateFeePerGasInFeeCurrency(params.client, params.request.feeCurrency),\n estimateMaxPriorityFeePerGasInFeeCurrency(params.client, params.request.feeCurrency),\n ]);\n // eth_gasPrice for cel2 returns baseFeePerGas + maxPriorityFeePerGas\n const maxFeePerGas = params.multiply(gasPrice - maxPriorityFeePerGas) + maxPriorityFeePerGas;\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n };\n },\n};\n/*\n * Estimate the fee per gas in the value of the fee token\n\n *\n * @param client - Client to use\n * @param feeCurrency - Address of a whitelisted fee token\n * @returns The fee per gas in wei in the value of the fee token\n *\n */\nasync function estimateFeePerGasInFeeCurrency(client, feeCurrency) {\n const fee = await client.request({\n method: 'eth_gasPrice',\n params: [feeCurrency],\n });\n return BigInt(fee);\n}\n/*\n * Estimate the max priority fee per gas in the value of the fee token\n\n *\n * @param client - Client to use\n * @param feeCurrency - Address of a whitelisted fee token\n * @returns The fee per gas in wei in the value of the fee token\n *\n */\nasync function estimateMaxPriorityFeePerGasInFeeCurrency(client, feeCurrency) {\n const feesPerGas = await client.request({\n method: 'eth_maxPriorityFeePerGas',\n params: [feeCurrency],\n });\n return BigInt(feesPerGas);\n}\n//# sourceMappingURL=fees.js.map","import { trim } from '../utils/data/trim.js';\nexport function isEmpty(value) {\n return (value === 0 ||\n value === 0n ||\n value === undefined ||\n value === null ||\n value === '0' ||\n value === '' ||\n (typeof value === 'string' &&\n (trim(value).toLowerCase() === '0x' ||\n trim(value).toLowerCase() === '0x00')));\n}\nexport function isPresent(value) {\n return !isEmpty(value);\n}\n/** @internal */\nexport function isEIP1559(transaction) {\n return (typeof transaction.maxFeePerGas !== 'undefined' &&\n typeof transaction.maxPriorityFeePerGas !== 'undefined');\n}\nexport function isCIP64(transaction) {\n /*\n * Enable end user to force the tx to be considered as a CIP-64.\n *\n * The preliminary type will be determined as \"eip1559\" by src/utils/transaction/getTransactionType.ts\n * and so we need the logic below to check for the specific value instead of checking if just any\n * transaction type is provided. If that's anything else than \"cip64\" then we need to reevaluate the\n * type based on the transaction fields.\n *\n * Modify with caution and according to https://github.com/celo-org/celo-proposals/blob/master/CIPs/cip-0064.md\n */\n if (transaction.type === 'cip64') {\n return true;\n }\n return isEIP1559(transaction) && isPresent(transaction.feeCurrency);\n}\n//# sourceMappingURL=utils.js.map","import { hexToBigInt } from '../utils/encoding/fromHex.js';\nimport { defineBlock } from '../utils/formatters/block.js';\nimport { defineTransaction, formatTransaction, } from '../utils/formatters/transaction.js';\nimport { defineTransactionRequest } from '../utils/formatters/transactionRequest.js';\nimport { isCIP64 } from './utils.js';\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args) {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string')\n return transaction;\n const formatted = formatTransaction(transaction);\n return {\n ...formatted,\n ...(transaction.gatewayFee\n ? {\n gatewayFee: hexToBigInt(transaction.gatewayFee),\n gatewayFeeRecipient: transaction.gatewayFeeRecipient,\n }\n : {}),\n feeCurrency: transaction.feeCurrency,\n };\n });\n return {\n transactions,\n };\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args) {\n if (args.type === '0x7e')\n return {\n isSystemTx: args.isSystemTx,\n mint: args.mint ? hexToBigInt(args.mint) : undefined,\n sourceHash: args.sourceHash,\n type: 'deposit',\n };\n const transaction = { feeCurrency: args.feeCurrency };\n if (args.type === '0x7b')\n transaction.type = 'cip64';\n else {\n if (args.type === '0x7c')\n transaction.type = 'cip42';\n transaction.gatewayFee = args.gatewayFee\n ? hexToBigInt(args.gatewayFee)\n : null;\n transaction.gatewayFeeRecipient = args.gatewayFeeRecipient;\n }\n return transaction;\n },\n }),\n transactionRequest: /*#__PURE__*/ defineTransactionRequest({\n format(args) {\n const request = {};\n if (args.feeCurrency)\n request.feeCurrency = args.feeCurrency;\n if (isCIP64(args))\n request.type = '0x7b';\n return request;\n },\n }),\n};\n//# sourceMappingURL=formatters.js.map","import { maxUint256 } from '../constants/number.js';\nimport { InvalidAddressError } from '../errors/address.js';\nimport { BaseError } from '../errors/base.js';\nimport { InvalidChainIdError } from '../errors/chain.js';\nimport { FeeCapTooHighError, TipAboveFeeCapError } from '../errors/node.js';\nimport { serializeTransaction as serializeTransaction_op } from '../op-stack/serializers.js';\nimport { isAddress } from '../utils/address/isAddress.js';\nimport { concatHex } from '../utils/data/concat.js';\nimport { toHex } from '../utils/encoding/toHex.js';\nimport { toRlp } from '../utils/encoding/toRlp.js';\nimport { serializeAccessList } from '../utils/transaction/serializeAccessList.js';\nimport { toYParitySignatureArray } from '../utils/transaction/serializeTransaction.js';\nimport { isCIP64, isEmpty, isPresent } from './utils.js';\nexport function serializeTransaction(transaction, signature) {\n if (isCIP64(transaction))\n return serializeTransactionCIP64(transaction, signature);\n return serializeTransaction_op(transaction, signature);\n}\nexport const serializers = {\n transaction: serializeTransaction,\n};\nfunction serializeTransactionCIP64(transaction, signature) {\n assertTransactionCIP64(transaction);\n const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, feeCurrency, data, } = transaction;\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializeAccessList(accessList),\n feeCurrency,\n ...toYParitySignatureArray(transaction, signature),\n ];\n return concatHex([\n '0x7b',\n toRlp(serializedTransaction),\n ]);\n}\n// maxFeePerGas must be less than maxUint256\nconst MAX_MAX_FEE_PER_GAS = maxUint256;\nexport function assertTransactionCIP42(transaction) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to, feeCurrency, gatewayFee, gatewayFeeRecipient, } = transaction;\n if (chainId <= 0)\n throw new InvalidChainIdError({ chainId });\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n if (gasPrice)\n throw new BaseError('`gasPrice` is not a valid CIP-42 Transaction attribute.');\n if (isPresent(maxFeePerGas) && maxFeePerGas > MAX_MAX_FEE_PER_GAS)\n throw new FeeCapTooHighError({ maxFeePerGas });\n if (isPresent(maxPriorityFeePerGas) &&\n isPresent(maxFeePerGas) &&\n maxPriorityFeePerGas > maxFeePerGas)\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });\n if ((isPresent(gatewayFee) && isEmpty(gatewayFeeRecipient)) ||\n (isPresent(gatewayFeeRecipient) && isEmpty(gatewayFee))) {\n throw new BaseError('`gatewayFee` and `gatewayFeeRecipient` must be provided together.');\n }\n if (isPresent(feeCurrency) && !isAddress(feeCurrency)) {\n throw new BaseError('`feeCurrency` MUST be a token address for CIP-42 transactions.');\n }\n if (isPresent(gatewayFeeRecipient) && !isAddress(gatewayFeeRecipient)) {\n throw new InvalidAddressError(gatewayFeeRecipient);\n }\n if (isEmpty(feeCurrency) && isEmpty(gatewayFeeRecipient)) {\n throw new BaseError('Either `feeCurrency` or `gatewayFeeRecipient` must be provided for CIP-42 transactions.');\n }\n}\nexport function assertTransactionCIP64(transaction) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to, feeCurrency, } = transaction;\n if (chainId <= 0)\n throw new InvalidChainIdError({ chainId });\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n if (gasPrice)\n throw new BaseError('`gasPrice` is not a valid CIP-64 Transaction attribute.');\n if (isPresent(maxFeePerGas) && maxFeePerGas > MAX_MAX_FEE_PER_GAS)\n throw new FeeCapTooHighError({ maxFeePerGas });\n if (isPresent(maxPriorityFeePerGas) &&\n isPresent(maxFeePerGas) &&\n maxPriorityFeePerGas > maxFeePerGas)\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });\n if (isPresent(feeCurrency) && !isAddress(feeCurrency)) {\n throw new BaseError('`feeCurrency` MUST be a token address for CIP-64 transactions.');\n }\n if (isEmpty(feeCurrency)) {\n throw new BaseError('`feeCurrency` must be provided for CIP-64 transactions.');\n }\n}\n//# sourceMappingURL=serializers.js.map","import { contracts } from '../op-stack/contracts.js';\nimport { fees } from './fees.js';\nimport { formatters } from './formatters.js';\nimport { serializers } from './serializers.js';\nexport const chainConfig = {\n blockTime: 1_000,\n contracts,\n formatters,\n serializers,\n fees,\n};\n//# sourceMappingURL=chainConfig.js.map","import { chainConfig } from '../../celo/chainConfig.js';\nimport { defineChain } from '../../utils/chain/defineChain.js';\nexport const celo = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 42_220,\n name: 'Celo',\n nativeCurrency: {\n decimals: 18,\n name: 'CELO',\n symbol: 'CELO',\n },\n rpcUrls: {\n default: { http: ['https://forno.celo.org'] },\n },\n blockExplorers: {\n default: {\n name: 'Celo Explorer',\n url: 'https://celoscan.io',\n apiUrl: 'https://api.celoscan.io/api',\n },\n },\n contracts: {\n multicall3: {\n address: '0xcA11bde05977b3631167028862bE2a173976CA11',\n blockCreated: 13112599,\n },\n },\n testnet: false,\n});\n//# sourceMappingURL=celo.js.map","import { defineChain } from '../../utils/chain/defineChain.js';\nexport const mainnet = /*#__PURE__*/ defineChain({\n id: 1,\n name: 'Ethereum',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n blockTime: 12_000,\n rpcUrls: {\n default: {\n http: ['https://eth.merkle.io'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Etherscan',\n url: 'https://etherscan.io',\n apiUrl: 'https://api.etherscan.io/api',\n },\n },\n contracts: {\n ensUniversalResolver: {\n address: '0xeeeeeeee14d718c2b47d9923deab1335e144eeee',\n blockCreated: 23_085_558,\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 14_353_601,\n },\n },\n});\n//# sourceMappingURL=mainnet.js.map","import { chainConfig } from '../../op-stack/chainConfig.js';\nimport { defineChain } from '../../utils/chain/defineChain.js';\nconst sourceId = 1; // mainnet\nexport const optimism = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 10,\n name: 'OP Mainnet',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.optimism.io'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Optimism Explorer',\n url: 'https://optimistic.etherscan.io',\n apiUrl: 'https://api-optimistic.etherscan.io/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0xe5965Ab5962eDc7477C8520243A95517CD252fA9',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0xdfe97868233d1aa22e815a266982f2cf17685a27',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 4286263,\n },\n portal: {\n [sourceId]: {\n address: '0xbEb5Fc579115071764c7423A4f12eDde41f106Ed',\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x99C9fc46f92E8a1c0deC1b1747d010903E884bE1',\n },\n },\n },\n sourceId,\n});\n//# sourceMappingURL=optimism.js.map","import { defineChain } from '../../utils/chain/defineChain.js';\nexport const polygon = /*#__PURE__*/ defineChain({\n id: 137,\n name: 'Polygon',\n blockTime: 2000,\n nativeCurrency: { name: 'POL', symbol: 'POL', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://polygon-rpc.com'],\n },\n },\n blockExplorers: {\n default: {\n name: 'PolygonScan',\n url: 'https://polygonscan.com',\n apiUrl: 'https://api.polygonscan.com/api',\n },\n },\n contracts: {\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 25770160,\n },\n },\n});\n//# sourceMappingURL=polygon.js.map","// Contract utility functions for payment processing\n\n// Validate contract ABI structure\nexport const validateABI = (abi, functionName) => {\n if (!Array.isArray(abi)) {\n throw new Error('ABI must be an array');\n }\n\n const func = abi.find(item =>\n item.type === 'function' &&\n item.name === functionName\n );\n\n if (!func) {\n throw new Error(`Function ${functionName} not found in ABI`);\n }\n\n return func;\n};\n\n// Create structured parameters for tuple-based contract calls\nexport const createTupleParams = (paramDefinition, values) => {\n const tupleInputs = paramDefinition.inputs[0];\n\n if (tupleInputs.type !== 'tuple') {\n throw new Error('Expected tuple parameter definition');\n }\n\n const structuredParams = {};\n tupleInputs.components.forEach((component, index) => {\n if (values[component.name] !== undefined) {\n structuredParams[component.name] = values[component.name];\n }\n });\n\n return structuredParams;\n};\n\n// Validate BigInt conversion\nexport const validateBigInt = (value, name) => {\n try {\n const bigIntValue = BigInt(value || 0);\n if (bigIntValue < 0n) {\n throw new Error(`${name} cannot be negative`);\n }\n return bigIntValue;\n } catch (error) {\n throw new Error(`Invalid ${name}: ${error.message}`);\n }\n};\n\n// Check if contract function expects tuple parameters\nexport const usesTupleParameters = (abi, functionName) => {\n const func = validateABI(abi, functionName);\n return func.inputs.length === 1 && func.inputs[0].type === 'tuple';\n};\n\n// Validate Ethereum address format\nexport const validateAddress = (addr, name, allowZero = false) => {\n if (!addr || typeof addr !== 'string') {\n throw new Error(`Missing ${name} address`);\n }\n if (!addr.startsWith('0x')) {\n throw new Error(`Invalid ${name} address format: must start with 0x`);\n }\n if (addr.length !== 42) {\n throw new Error(`Invalid ${name} address length: expected 42 characters, got ${addr.length}`);\n }\n if (addr === '0x0000000000000000000000000000000000000000' && !allowZero) {\n throw new Error(`Invalid ${name} address: cannot be zero address`);\n }\n};\n\n// Validate contract call parameters for PaymentSplitter\nexport const validateSplitPaymentParams = (params) => {\n // Validate addresses\n validateAddress(params.token, 'token');\n validateAddress(params.recipient1, 'recipient1');\n validateAddress(params.recipient2, 'recipient2');\n\n // Allow recipient3 to be zero address if percentage is 0 (optional recipient)\n const recipient3Percentage = BigInt(params.recipient3Percentage || 0);\n const allowZeroRecipient3 = recipient3Percentage === 0n;\n validateAddress(params.recipient3, 'recipient3', allowZeroRecipient3);\n\n // Validate payment ID\n if (!params.paymentId || typeof params.paymentId !== 'string' || params.paymentId.length === 0) {\n throw new Error('Invalid payment ID: must be a non-empty string');\n }\n\n // Ensure all numeric values are valid BigInts\n let amount, percentage1, percentage2, percentage3;\n\n try {\n amount = BigInt(params.amount || 0);\n percentage1 = BigInt(params.recipient1Percentage || 0);\n percentage2 = BigInt(params.recipient2Percentage || 0);\n percentage3 = BigInt(params.recipient3Percentage || 0);\n } catch (bigIntError) {\n throw new Error('Invalid numeric values: cannot convert to BigInt');\n }\n\n if (amount <= 0n) {\n throw new Error(`Invalid amount: ${params.amount} (must be greater than 0)`);\n }\n\n const totalPercentage = percentage1 + percentage2 + percentage3;\n if (totalPercentage !== 10000n) {\n throw new Error(`Invalid percentages: total is ${totalPercentage} but must equal 10000 basis points (100%). Individual: ${percentage1}, ${percentage2}, ${percentage3}`);\n }\n\n return {\n amount,\n percentage1,\n percentage2,\n percentage3\n };\n};\n\n// Create structured parameters for PaymentSplitter contract\nexport const createSplitPaymentParams = (params) => {\n const validated = validateSplitPaymentParams(params);\n\n return {\n token: params.token,\n amount: validated.amount,\n paymentId: params.paymentId,\n recipient1: params.recipient1,\n recipient2: params.recipient2,\n recipient3: params.recipient3,\n recipient1Percentage: validated.percentage1,\n recipient2Percentage: validated.percentage2,\n recipient3Percentage: validated.percentage3\n };\n};\n\n// Helper function to categorize contract simulation errors\nexport const categorizeSimulationError = (error) => {\n if (!error.message) {\n return {\n revertReason: 'Transaction will revert',\n userFriendlyMessage: 'Transaction simulation failed'\n };\n }\n\n const errorMsg = error.message.toLowerCase();\n\n if (errorMsg.includes('abi encoding params/values length mismatch')) {\n return {\n revertReason: 'Smart contract parameter mismatch. This is likely a technical issue.',\n userFriendlyMessage: 'Technical error: Contract parameters mismatch. Please try again or contact support.'\n };\n }\n\n if (errorMsg.includes('payment id already used')) {\n return {\n revertReason: 'This payment ID has already been used.',\n userFriendlyMessage: 'This payment has already been processed. Please check your transaction history.'\n };\n }\n\n if (errorMsg.includes('percentages must equal 100')) {\n return {\n revertReason: 'Payment split percentages are incorrect.',\n userFriendlyMessage: 'Internal error: Payment split configuration is invalid. Please contact support.'\n };\n }\n\n if (errorMsg.includes('token transfer failed') || errorMsg.includes('transfer amount exceeds')) {\n return {\n revertReason: 'Insufficient token balance or approval.',\n userFriendlyMessage: 'Insufficient balance or token approval. Please check your wallet balance.'\n };\n }\n\n if (errorMsg.includes('amount must be greater than 0')) {\n return {\n revertReason: 'Payment amount is invalid.',\n userFriendlyMessage: 'Invalid payment amount. Please try again.'\n };\n }\n\n if (errorMsg.includes('invalid recipient') || errorMsg.includes('zero address')) {\n return {\n revertReason: 'One of the payment recipients has an invalid address.',\n userFriendlyMessage: 'Payment configuration error: Invalid recipient address. Please contact support.'\n };\n }\n\n if (errorMsg.includes('insufficient gas') || errorMsg.includes('out of gas')) {\n return {\n revertReason: 'Insufficient gas for transaction.',\n userFriendlyMessage: 'Not enough gas to process transaction. Please increase gas limit or check ETH balance.'\n };\n }\n\n if (errorMsg.includes('nonce')) {\n return {\n revertReason: 'Transaction nonce conflict.',\n userFriendlyMessage: 'Transaction ordering conflict. Please try again in a moment.'\n };\n }\n\n return {\n revertReason: error.message,\n userFriendlyMessage: `Transaction simulation failed: ${error.message.substring(0, 100)}${error.message.length > 100 ? '...' : ''}`\n };\n};\n\n// Standard ERC20 ABI for approve function\nexport const ERC20_APPROVE_ABI = [\n {\n constant: false,\n inputs: [\n { name: \"_spender\", type: \"address\" },\n { name: \"_value\", type: \"uint256\" }\n ],\n name: \"approve\",\n outputs: [],\n payable: false,\n stateMutability: \"nonpayable\",\n type: \"function\"\n }\n];\n\n// USDT has a different approve function signature\nexport const USDT_APPROVE_ABI = [\n {\n constant: false,\n inputs: [\n { name: \"_spender\", type: \"address\" },\n { name: \"_value\", type: \"uint256\" }\n ],\n name: \"approve\",\n outputs: [],\n payable: false,\n stateMutability: \"nonpayable\",\n type: \"function\"\n }\n];\n\n// ERC20 balance check ABI\nexport const ERC20_BALANCE_ABI = [\n {\n constant: true,\n inputs: [\n {\n name: \"_owner\",\n type: \"address\"\n }\n ],\n name: \"balanceOf\",\n outputs: [\n {\n name: \"balance\",\n type: \"uint256\"\n }\n ],\n payable: false,\n stateMutability: \"view\",\n type: \"function\"\n }\n];","// User-friendly error message utilities\n\n/**\n * Parse wallet/transaction errors into user-friendly messages\n */\nexport const parseUserFriendlyError = (error) => {\n const errorMessage = error?.message?.toLowerCase() || error?.toString()?.toLowerCase() || '';\n const errorCode = error?.code || error?.reason || '';\n\n\n // User rejected transaction\n if (errorMessage.includes('user rejected') ||\n errorMessage.includes('user denied') ||\n errorMessage.includes('user cancelled') ||\n errorMessage.includes('rejected by user') ||\n errorCode === 4001 ||\n errorCode === 'ACTION_REJECTED') {\n return {\n type: 'user_rejected',\n title: 'Transaction Cancelled',\n message: 'You cancelled the transaction. No charges were made.',\n suggestion: 'Click \"Pay Now\" to try again when you\\'re ready.'\n };\n }\n\n // Insufficient funds\n if (errorMessage.includes('insufficient funds') ||\n errorMessage.includes('insufficient balance') ||\n errorMessage.includes('insufficient eth') ||\n errorMessage.includes('insufficient matic') ||\n errorMessage.includes('insufficient bnb') ||\n errorCode === -32000) {\n return {\n type: 'insufficient_funds',\n title: 'Insufficient Funds',\n message: 'You don\\'t have enough tokens or gas fees in your wallet.',\n suggestion: 'Add more funds to your wallet and try again.'\n };\n }\n\n // Network/RPC errors\n if (errorMessage.includes('network error') ||\n errorMessage.includes('rpc error') ||\n errorMessage.includes('connection failed') ||\n errorMessage.includes('timeout') ||\n errorMessage.includes('request failed')) {\n return {\n type: 'network_error',\n title: 'Network Error',\n message: 'Unable to connect to the blockchain network.',\n suggestion: 'Check your internet connection and try again.'\n };\n }\n\n // Wrong network\n if (errorMessage.includes('wrong network') ||\n errorMessage.includes('unsupported network') ||\n errorMessage.includes('chain mismatch') ||\n errorCode === 4902) {\n return {\n type: 'wrong_network',\n title: 'Wrong Network',\n message: 'Please switch to the correct network in your wallet.',\n suggestion: 'Your wallet should prompt you to switch networks.'\n };\n }\n\n // Wallet not connected\n if (errorMessage.includes('wallet not connected') ||\n errorMessage.includes('no provider') ||\n errorMessage.includes('wallet disconnected') ||\n errorCode === 4900) {\n return {\n type: 'wallet_disconnected',\n title: 'Wallet Disconnected',\n message: 'Your wallet is not connected.',\n suggestion: 'Please reconnect your wallet and try again.'\n };\n }\n\n // Gas estimation failed\n if (errorMessage.includes('gas estimation failed') ||\n errorMessage.includes('execution reverted') ||\n errorMessage.includes('out of gas')) {\n return {\n type: 'gas_error',\n title: 'Transaction Failed',\n message: 'The transaction couldn\\'t be processed.',\n suggestion: 'This might be a temporary issue. Please try again.'\n };\n }\n\n // Token approval specific errors\n if (errorMessage.includes('approve') && errorMessage.includes('failed')) {\n return {\n type: 'approval_failed',\n title: 'Token Approval Failed',\n message: 'Failed to approve token spending.',\n suggestion: 'Please try the approval step again.'\n };\n }\n\n // Generic contract/transaction errors\n if (errorMessage.includes('transaction failed') ||\n errorMessage.includes('revert') ||\n errorMessage.includes('contract call failed')) {\n return {\n type: 'transaction_failed',\n title: 'Transaction Failed',\n message: 'The blockchain transaction was unsuccessful.',\n suggestion: 'Please check your wallet and try again.'\n };\n }\n\n // Wallet popup blocked\n if (errorMessage.includes('popup') ||\n errorMessage.includes('blocked')) {\n return {\n type: 'popup_blocked',\n title: 'Wallet Popup Blocked',\n message: 'Your browser blocked the wallet popup.',\n suggestion: 'Please allow popups for this site and try again.'\n };\n }\n\n // Rate limiting\n if (errorMessage.includes('rate limit') ||\n errorMessage.includes('too many requests')) {\n return {\n type: 'rate_limited',\n title: 'Too Many Requests',\n message: 'Please wait a moment before trying again.',\n suggestion: 'Wait 30 seconds and retry your transaction.'\n };\n }\n\n // Payment verification pending (not yet confirmed on blockchain)\n if (errorMessage.includes('payment not yet confirmed') ||\n errorMessage.includes('not yet confirmed on-chain') ||\n errorMessage.includes('payment not found on-chain') ||\n errorMessage.includes('please complete the payment')) {\n return {\n type: 'payment_pending',\n title: 'Payment Pending',\n message: 'Your payment is still being confirmed on the blockchain.',\n suggestion: 'Please wait a moment and try again, or check if your transaction completed successfully.'\n };\n }\n\n // Mobile wallet specific errors\n if (errorMessage.includes('deep link') ||\n errorMessage.includes('app not installed') ||\n errorMessage.includes('wallet app')) {\n return {\n type: 'mobile_wallet_error',\n title: 'Wallet App Issue',\n message: 'Unable to open or connect to your wallet app.',\n suggestion: 'Make sure your wallet app is installed and try again.'\n };\n }\n\n // Default fallback for unknown errors\n return {\n type: 'unknown_error',\n title: 'Something Went Wrong',\n message: 'An unexpected error occurred.',\n suggestion: 'Please try again or contact support if the problem persists.'\n };\n};\n\n/**\n * Get error severity level for UI styling\n */\nexport const getErrorSeverity = (errorType) => {\n switch (errorType) {\n case 'user_rejected':\n return 'info'; // Not really an error, just user choice\n\n case 'insufficient_funds':\n case 'wrong_network':\n case 'wallet_disconnected':\n case 'payment_pending':\n return 'warning'; // User can fix these\n\n case 'network_error':\n case 'gas_error':\n case 'rate_limited':\n return 'error'; // Temporary issues\n\n case 'transaction_failed':\n case 'approval_failed':\n case 'unknown_error':\n default:\n return 'critical'; // Serious issues\n }\n};\n\n/**\n * Get appropriate action button text based on error type\n */\nexport const getErrorActionText = (errorType) => {\n switch (errorType) {\n case 'user_rejected':\n return 'Try Again';\n\n case 'insufficient_funds':\n return 'Add Funds & Retry';\n\n case 'wrong_network':\n return 'Switch Network & Retry';\n\n case 'wallet_disconnected':\n return 'Reconnect Wallet';\n\n case 'payment_pending':\n return 'Check Again';\n\n case 'network_error':\n case 'rate_limited':\n return 'Retry';\n\n case 'popup_blocked':\n return 'Allow Popups & Retry';\n\n case 'mobile_wallet_error':\n return 'Open Wallet App';\n\n default:\n return 'Try Again';\n }\n};\n\n/**\n * Format error for console logging (keeps technical details for debugging)\n */\nexport const formatErrorForLogging = (error, context = '') => {\n const timestamp = new Date().toISOString();\n const userFriendly = parseUserFriendlyError(error);\n\n return {\n timestamp,\n context,\n userFriendly,\n technical: {\n message: error?.message || 'Unknown error',\n code: error?.code,\n reason: error?.reason,\n stack: error?.stack,\n name: error?.name\n }\n };\n};\n\nexport default {\n parseUserFriendlyError,\n getErrorSeverity,\n getErrorActionText,\n formatErrorForLogging\n};","import { useState, useEffect } from 'react';\nimport { useSendTransaction, useWaitForTransactionReceipt, useWriteContract, useSimulateContract } from 'wagmi';\nimport { readContract, writeContract, simulateContract, waitForTransactionReceipt, estimateFeesPerGas } from '@wagmi/core';\nimport { erc20Abi, createPublicClient, http, fallback } from 'viem';\nimport { mainnet, bsc, polygon, arbitrum, optimism, avalanche, celo, base } from 'viem/chains';\nimport { wagmiConfig } from '../config/wagmiConfig';\nimport { normalizeChainId } from '../config/chainConfig';\nimport {\n validateSplitPaymentParams,\n createSplitPaymentParams,\n categorizeSimulationError,\n ERC20_BALANCE_ABI,\n USDT_APPROVE_ABI\n} from '../utils/contractUtils';\nimport { parseUserFriendlyError, formatErrorForLogging } from '../utils/errorUtils';\n\n// 🔖 SDK VERSION TRACKING\nconst TRANSACTION_HANDLER_VERSION = '2.6.0-base-network';\nconst FIX_DATE = '2025-10-24';\nconst FIXES_APPLIED = [\n '✅ 3s RPC propagation delay after approval (Coinbase Wallet fix)',\n '✅ Allowance verification loop (3 attempts, 2s intervals)',\n '✅ Avalanche simulation bypass (JSON-RPC error workaround)',\n '✅ Ethereum simulation bypass (stale RPC state workaround)',\n '✅ 120s transaction timeout (was 60s)',\n '✅ 20% gas price buffer (FIXED: proper estimateFeesPerGas import)',\n '✅ Balance check fallback RPC (Alchemy primary, 3+ public fallbacks)',\n '✅ USDT reset handling',\n '⚡ Alchemy RPCs: ALL 8 CHAINS (ETH, BSC, MATIC, ARB, OP, AVAX, CELO, BASE) - 99.9% uptime',\n '✅ 8s backend sync delay (prevents \"payment not found\" RPC indexing lag)',\n '🆕 Base network support (Chain ID 8453, Contract: 0x6D827e60d0dC279cAa09f026d1641ECDb5704753)'\n];\n\n// ⛽ Helper function to calculate gas fees with buffer for volatile networks\n// Adds 20% buffer to prevent \"max fee per gas less than block base fee\" errors\nconst getGasFeesWithBuffer = async (wagmiConfig, chainId) => {\n try {\n // Use Wagmi's estimateFeesPerGas action\n const gasPrice = await estimateFeesPerGas(wagmiConfig, { chainId });\n\n // Add 20% buffer to both maxFeePerGas and maxPriorityFeePerGas\n const GAS_BUFFER_MULTIPLIER = 120n; // 120% = 1.20x\n const MULTIPLIER_BASE = 100n;\n\n const bufferedFees = {\n maxFeePerGas: gasPrice.maxFeePerGas ? (gasPrice.maxFeePerGas * GAS_BUFFER_MULTIPLIER) / MULTIPLIER_BASE : undefined,\n maxPriorityFeePerGas: gasPrice.maxPriorityFeePerGas ? (gasPrice.maxPriorityFeePerGas * GAS_BUFFER_MULTIPLIER) / MULTIPLIER_BASE : undefined\n };\n\n\n return bufferedFees;\n } catch (error) {\n return {}; // Return empty object to let wagmi use defaults\n }\n};\n\n// Alchemy API configuration (same as wagmiConfig)\nconst ALCHEMY_API_KEY = 'YWG990wOlIikc1tU7-WWTepfU8d1f4dp';\n\n// Helper function to get fallback RPC client for a given chain\n// Uses app's own RPC configuration instead of wallet's RPC\n// Priority: Alchemy (primary) → Public RPCs (fallback)\nconst getFallbackRpcClient = (chainId) => {\n const chainMap = {\n 1: mainnet,\n 56: bsc,\n 137: polygon,\n 42161: arbitrum,\n 10: optimism,\n 43114: avalanche,\n 42220: celo,\n 8453: base\n };\n\n const rpcEndpoints = {\n 1: [\n `https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://cloudflare-eth.com',\n 'https://eth.llamarpc.com',\n 'https://ethereum.publicnode.com'\n ],\n 56: [\n `https://bnb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://bsc-dataseed.bnbchain.org',\n 'https://bsc-dataseed-public.bnbchain.org',\n 'https://bsc.nodereal.io'\n ],\n 137: [\n `https://polygon-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://polygon.llamarpc.com',\n 'https://polygon-rpc.com',\n 'https://polygon.drpc.org'\n ],\n 42161: [\n `https://arb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://arb1.arbitrum.io/rpc',\n 'https://arbitrum.llamarpc.com'\n ],\n 10: [\n `https://opt-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://mainnet.optimism.io',\n 'https://optimism.llamarpc.com'\n ],\n 43114: [\n `https://avax-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://api.avax.network/ext/bc/C/rpc',\n 'https://avalanche.public-rpc.com'\n ],\n 42220: [\n `https://celo-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://forno.celo.org',\n 'https://celo.drpc.org'\n ],\n 8453: [\n `https://base-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,\n 'https://mainnet.base.org',\n 'https://base.llamarpc.com',\n 'https://base.meowrpc.com'\n ]\n };\n\n const chain = chainMap[chainId];\n const endpoints = rpcEndpoints[chainId];\n\n if (!chain || !endpoints) {\n return null;\n }\n\n // Create fallback transport with multiple RPC endpoints (Alchemy first, then public)\n const transports = endpoints.map(url => http(url, { timeout: 10_000, retryCount: 1 }));\n\n return createPublicClient({\n chain,\n transport: fallback(transports)\n });\n};\n\nexport const useTransactionHandling = (paymentData, selectedToken, selectedNetwork, address, api, walletConnection) => {\n const [transactionStep, setTransactionStep] = useState('idle'); // idle, approve, splitPayment, processing, success, error\n const [transactionError, setTransactionError] = useState('');\n const [currentTransactionHash, setCurrentTransactionHash] = useState(null);\n\n const { data: txHash, isPending: txPending, error: txError, sendTransaction } = useSendTransaction();\n const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({\n hash: txHash,\n });\n\n // Handle two-step PaymentSplitter flow\n const executePaymentTransaction = async () => {\n if (!address || !paymentData?.contractCall) {\n throw new Error('Missing wallet connection or payment data');\n }\n\n const contractCall = paymentData.contractCall;\n\n if (!contractCall.contractAddress) {\n throw new Error('PaymentSplitter contract data missing from payment response');\n }\n\n\n // ⭐ CRITICAL: Verify and switch to correct network before starting transaction\n if (walletConnection?.ensureCorrectNetwork && selectedNetwork) {\n const networkOk = await walletConnection.ensureCorrectNetwork(selectedNetwork);\n\n if (!networkOk) {\n throw new Error('Network verification failed. Please ensure you are on the correct network.');\n }\n\n }\n\n // Step 1: Check balance and approve PaymentSplitter contract\n if (selectedToken.contractAddress) {\n\n const decimals = selectedToken.decimals || 6;\n const amount = contractCall.approvalAmount || Math.floor(paymentData.totalAmount * Math.pow(10, decimals));\n\n\n // Enhanced balance check with fallback RPC\n try {\n let userBalance;\n let balanceCheckMethod = 'unknown';\n\n // Try wallet's RPC first (preferred - uses user's wallet infrastructure)\n try {\n userBalance = await readContract(wagmiConfig, {\n address: contractCall.tokenAddress,\n abi: ERC20_BALANCE_ABI,\n functionName: 'balanceOf',\n args: [address]\n });\n balanceCheckMethod = 'wallet-rpc';\n } catch (walletRpcError) {\n\n // Try fallback RPC (app's own multi-endpoint RPC configuration)\n const chainId = selectedNetwork?.chainId || selectedNetwork?.id;\n if (chainId) {\n // Normalize chainId to decimal (handles hex \"0xa86a\" → 43114, decimal \"43114\" → 43114, number 43114 → 43114)\n const chainIdNumber = normalizeChainId(chainId);\n\n const fallbackClient = getFallbackRpcClient(chainIdNumber);\n\n if (fallbackClient) {\n try {\n userBalance = await fallbackClient.readContract({\n address: contractCall.tokenAddress,\n abi: ERC20_BALANCE_ABI,\n functionName: 'balanceOf',\n args: [address]\n });\n balanceCheckMethod = 'fallback-rpc';\n } catch (fallbackRpcError) {\n throw walletRpcError; // Throw original error\n }\n } else {\n throw walletRpcError; // Throw original error\n }\n } else {\n throw walletRpcError; // Throw original error\n }\n }\n\n const requiredAmount = BigInt(amount);\n\n\n if (userBalance < requiredAmount) {\n const errorMsg = `Insufficient ${selectedToken.symbol} balance. You have ${(Number(userBalance) / Math.pow(10, decimals)).toFixed(6)} ${selectedToken.symbol} but need ${(Number(requiredAmount) / Math.pow(10, decimals)).toFixed(6)} ${selectedToken.symbol}`;\n throw new Error(errorMsg);\n }\n } catch (balanceError) {\n if (balanceError.message.includes('Insufficient')) {\n throw balanceError;\n }\n // Continue if balance check fails due to network issues\n }\n\n setTransactionStep('approve');\n\n // Store contract call data for step 2\n window.coinleyPendingSplitPayment = {\n contractCall,\n selectedToken,\n paymentData,\n selectedNetwork\n };\n\n // Use WAGMI writeContract for ERC20 approve\n try {\n // Special handling for USDT (non-standard ERC20)\n const isUSDT = contractCall.tokenAddress.toLowerCase() === '0xdac17f958d2ee523a2206206994597c13d831ec7' ||\n selectedToken.symbol.toUpperCase() === 'USDT';\n\n let abi = erc20Abi;\n if (isUSDT) {\n abi = USDT_APPROVE_ABI;\n }\n\n // ⭐ SMART ALLOWANCE CHECK: Skip approval if allowance is already sufficient\n // Ensure amount is a valid number or string before converting to BigInt\n let requiredAmount;\n try {\n requiredAmount = BigInt(amount);\n } catch (conversionError) {\n throw new Error(`Invalid amount value: ${amount}`);\n }\n\n // Check current allowance for ALL tokens with retry logic (fixes fresh wallet connection issue)\n let currentAllowance = 0n;\n let allowanceCheckAttempts = 0;\n const maxAllowanceCheckAttempts = 3;\n\n while (allowanceCheckAttempts < maxAllowanceCheckAttempts) {\n try {\n currentAllowance = await readContract(wagmiConfig, {\n address: contractCall.tokenAddress,\n abi: erc20Abi,\n functionName: 'allowance',\n args: [address, contractCall.contractAddress]\n });\n\n\n // Success! Exit retry loop\n break;\n\n } catch (allowanceError) {\n allowanceCheckAttempts++;\n\n if (allowanceCheckAttempts < maxAllowanceCheckAttempts) {\n await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds before retry\n } else {\n currentAllowance = 0n; // Assume no allowance, will proceed with approval\n }\n }\n }\n\n // If allowance is already sufficient, skip approval entirely\n if (currentAllowance >= requiredAmount) {\n setTransactionStep('splitPayment');\n\n // Execute Step 2: Call splitPayment function directly\n const splitPaymentHash = await executeSplitPayment();\n\n // 🔒 CRITICAL FIX: Notify backend after successful transaction\n if (splitPaymentHash) {\n await processFinalPayment(splitPaymentHash);\n }\n\n return splitPaymentHash;\n }\n\n // ⭐ USDT FIX: If changing allowance, reset to 0 first (USDT security requirement)\n if (isUSDT && currentAllowance > 0n) {\n\n // Get gas fees with 20% buffer\n const gasFees = await getGasFeesWithBuffer(wagmiConfig, selectedNetwork.chainId);\n\n // Step 1: Reset allowance to 0\n const resetHash = await writeContract(wagmiConfig, {\n address: contractCall.tokenAddress,\n abi: erc20Abi,\n functionName: 'approve',\n args: [contractCall.contractAddress, 0n],\n ...gasFees // ✅ FIX #2: Add 20% gas price buffer\n });\n\n\n // Wait for reset confirmation\n await waitForTransactionReceipt(wagmiConfig, {\n hash: resetHash,\n confirmations: 1,\n timeout: 120_000 // 120 seconds (same as approve transaction)\n });\n\n }\n\n // Get gas fees with 20% buffer to prevent rejection\n const gasFees = await getGasFeesWithBuffer(wagmiConfig, selectedNetwork.chainId);\n\n // Approve the required amount\n\n const approveHash = await writeContract(wagmiConfig, {\n address: contractCall.tokenAddress,\n abi: erc20Abi,\n functionName: 'approve',\n args: [contractCall.contractAddress, requiredAmount],\n ...gasFees // ✅ FIX #2: Add 20% gas price buffer to prevent \"max fee < base fee\" errors\n });\n\n setCurrentTransactionHash(approveHash);\n\n // ⭐ CRITICAL FIX: Wait for actual transaction confirmation\n // ✅ FIX #1: Increased timeout from 60s (default) to 120s\n // Reason: Wallet RPC caching can delay receipt availability by 5-15s\n // - Coinbase Wallet: Infura RPC cache (5-10s)\n // - Trust Wallet: Requires 3+ confirmations (6-15s)\n // - Avalanche: RPC indexing delay (10-15s)\n const receipt = await waitForTransactionReceipt(wagmiConfig, {\n hash: approveHash,\n confirmations: 1,\n timeout: 120_000 // 120 seconds (2 minutes)\n });\n\n\n // ⭐ CRITICAL FIX: Wait for RPC state propagation after approval\n // Some RPCs (especially Optimism with Coinbase Wallet) need 2-5 seconds\n // for the allowance update to propagate through their caching layer\n await new Promise(resolve => setTimeout(resolve, 3000));\n\n // ⭐ VERIFY ALLOWANCE: Double-check that approval actually propagated\n let verificationAttempts = 0;\n const maxVerificationAttempts = 3;\n let allowanceVerified = false;\n\n while (verificationAttempts < maxVerificationAttempts && !allowanceVerified) {\n try {\n const updatedAllowance = await readContract(wagmiConfig, {\n address: contractCall.tokenAddress,\n abi: erc20Abi,\n functionName: 'allowance',\n args: [address, contractCall.contractAddress]\n });\n\n\n if (updatedAllowance >= requiredAmount) {\n allowanceVerified = true;\n break;\n }\n\n // If not verified, wait 2 more seconds and try again\n if (verificationAttempts < maxVerificationAttempts - 1) {\n await new Promise(resolve => setTimeout(resolve, 2000));\n }\n } catch (verifyError) {\n if (verificationAttempts < maxVerificationAttempts - 1) {\n await new Promise(resolve => setTimeout(resolve, 2000));\n }\n }\n\n verificationAttempts++;\n }\n\n if (!allowanceVerified) {\n }\n\n // Execute Step 2: Call splitPayment function\n const splitPaymentHash = await executeSplitPayment();\n\n // 🔒 CRITICAL FIX: Notify backend after successful transaction\n if (splitPaymentHash) {\n await processFinalPayment(splitPaymentHash);\n }\n\n // Return the transaction hash so component can show success screen\n return splitPaymentHash;\n\n } catch (error) {\n\n // Log full error for debugging\n const errorLog = formatErrorForLogging(error, 'approve_transaction');\n\n // Parse user-friendly error\n const friendlyError = parseUserFriendlyError(error);\n setTransactionError(friendlyError);\n setTransactionStep('idle');\n\n // Check if user rejected (keep original logic)\n if (error.message?.includes('User rejected') ||\n error.message?.includes('User denied') ||\n error.code === 4001) {\n throw new Error('Transaction was cancelled by user');\n }\n\n throw new Error(`Approve failed: ${error.message}`);\n }\n } else {\n throw new Error('Native token transactions not yet supported with PaymentSplitter. Please use ERC-20 tokens.');\n }\n };\n\n // Execute Step 2: Call splitPayment function on contract\n const executeSplitPayment = async () => {\n try {\n setTransactionStep('splitPayment');\n\n const pendingSplitPayment = window.coinleyPendingSplitPayment;\n if (!pendingSplitPayment) {\n throw new Error('Missing split payment data');\n }\n\n const { contractCall, selectedToken, paymentData, selectedNetwork } = pendingSplitPayment;\n\n\n const chainId = selectedNetwork.chainId || 10; // Default to Optimism\n\n // Get contract ABI from backend\n const contractInfo = await api.getContractInfo(chainId);\n const { abi } = contractInfo;\n\n // Create and validate parameters\n const splitPaymentParams = createSplitPaymentParams(contractCall.params);\n\n // Simulate the transaction first\n const chainIdNormalized = normalizeChainId(chainId);\n const isEthereum = chainIdNormalized === 1; // Ethereum has stale RPC state issues\n const isAvalanche = chainIdNormalized === 43114; // Avalanche has JSON-RPC errors during simulation\n const shouldBypassSimulationErrors = isEthereum || isAvalanche;\n\n try {\n const { request } = await simulateContract(wagmiConfig, {\n address: contractCall.contractAddress,\n abi: abi,\n functionName: 'splitPayment',\n args: [splitPaymentParams]\n });\n } catch (simulationError) {\n\n // Log detailed error information\n\n // ⭐ ADVANCED: Try to extract revert data (hex error signature)\n const errorData = simulationError.data || simulationError.cause?.data;\n if (errorData) {\n // Common error signatures:\n // 0x08c379a0 = Error(string)\n // 0x4e487b71 = Panic(uint256)\n if (typeof errorData === 'string' && errorData.startsWith('0x08c379a0')) {\n } else if (typeof errorData === 'string' && errorData.startsWith('0x4e487b71')) {\n } else if (errorData) {\n }\n }\n\n // Try to extract revert reason\n const revertReason = simulationError.reason ||\n simulationError.cause?.reason ||\n simulationError.cause?.shortMessage ||\n simulationError.data?.message ||\n 'Unknown revert reason (contract may use require() without message)';\n\n\n // Log contract call details for debugging\n\n // ⚠️ BYPASS SIMULATION ERRORS: For chains with known RPC simulation issues\n // Other networks: Throw error immediately\n if (shouldBypassSimulationErrors) {\n const networkName = isEthereum ? 'ETHEREUM' : 'AVALANCHE';\n const reason = isEthereum\n ? 'Stale RPC state, gas estimation quirks, contract has 100% Etherscan success rate'\n : 'JSON-RPC errors during simulation (common with Avalanche RPCs), but transactions succeed on-chain';\n\n } else {\n const { userFriendlyMessage } = categorizeSimulationError(simulationError);\n throw new Error(userFriendlyMessage);\n }\n }\n\n // Execute the splitPayment transaction\n\n // Get gas fees with 20% buffer to prevent rejection\n const gasFees = await getGasFeesWithBuffer(wagmiConfig, chainId);\n\n // Special handling for Arbitrum + MetaMask JSON-RPC issues\n const isArbitrum = selectedNetwork.shortName === 'arbitrum';\n const maxRetries = isArbitrum ? 2 : 0;\n\n let splitPaymentHash;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n if (attempt > 0) {\n const waitTime = 2000 * attempt;\n await new Promise(resolve => setTimeout(resolve, waitTime));\n }\n\n splitPaymentHash = await writeContract(wagmiConfig, {\n address: contractCall.contractAddress,\n abi: abi,\n functionName: 'splitPayment',\n args: [splitPaymentParams],\n ...gasFees // ✅ FIX #2: Add 20% gas price buffer to prevent \"max fee < base fee\" errors\n });\n break; // Success, exit retry loop\n } catch (writeError) {\n\n const isKnownArbitrumError = writeError.message?.includes('Internal JSON-RPC error') ||\n writeError.message?.includes('-32603') ||\n writeError.message?.includes('nonce');\n\n if (attempt === maxRetries || (!isKnownArbitrumError && !isArbitrum)) {\n throw writeError; // Final attempt or not a retriable error\n }\n }\n }\n\n setCurrentTransactionHash(splitPaymentHash);\n setTransactionStep('processing');\n\n // Clear pending data\n window.coinleyPendingSplitPayment = null;\n\n return splitPaymentHash;\n\n } catch (error) {\n\n // Log full error for debugging\n const errorLog = formatErrorForLogging(error, 'split_payment_transaction');\n\n // Parse user-friendly error\n const friendlyError = parseUserFriendlyError(error);\n setTransactionError(friendlyError);\n setTransactionStep('error');\n throw error;\n }\n };\n\n // Process final payment completion\n const processFinalPayment = async (transactionHash) => {\n try {\n setTransactionStep('processing');\n\n\n if (!api || !api.processPayment) {\n throw new Error('API instance not available or missing processPayment method');\n }\n\n // Wait for blockchain indexers to sync the transaction\n // This prevents \"Payment not found on-chain\" errors caused by RPC lag\n await new Promise(resolve => setTimeout(resolve, 8000));\n\n const processResult = await api.processPayment(\n paymentData.id,\n transactionHash,\n selectedNetwork.shortName,\n address\n );\n\n setTransactionStep('success');\n\n return processResult;\n\n } catch (error) {\n\n // Log full error for debugging\n const errorLog = formatErrorForLogging(error, 'final_payment_processing');\n\n // Parse user-friendly error\n const friendlyError = parseUserFriendlyError(error);\n setTransactionError(friendlyError);\n setTransactionStep('error');\n throw error;\n }\n };\n\n const resetTransaction = () => {\n setTransactionStep('idle');\n setTransactionError('');\n setCurrentTransactionHash(null);\n window.coinleyPendingSplitPayment = null;\n };\n\n return {\n // State\n transactionStep,\n transactionError,\n currentTransactionHash,\n txPending,\n isConfirming,\n isConfirmed,\n\n // Actions\n executePaymentTransaction,\n executeSplitPayment,\n processFinalPayment,\n resetTransaction,\n setTransactionError,\n setTransactionStep\n };\n};","import React, { useState, useEffect, useRef } from 'react';\nimport ReactDOM from 'react-dom';\n\nconst ModernDropdown = ({\n options = [],\n value,\n onChange,\n placeholder,\n renderOption,\n getOptionKey,\n getOptionValue,\n getSearchableText,\n disabled = false\n}) => {\n const [isOpen, setIsOpen] = useState(false);\n const [searchTerm, setSearchTerm] = useState('');\n const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 400, maxHeight: 450 });\n const dropdownRef = useRef(null);\n const buttonRef = useRef(null);\n\n const filteredOptions = options.filter(option => {\n const searchableText = getSearchableText ? getSearchableText(option) : '';\n return searchableText.toLowerCase().includes(searchTerm.toLowerCase());\n });\n\n const selectedOption = options.find(option => getOptionValue(option) === value);\n\n const updateDropdownPosition = () => {\n if (buttonRef.current) {\n const viewportWidth = window.innerWidth;\n const viewportHeight = window.innerHeight;\n\n const dropdownWidth = Math.min(400, viewportWidth - 40);\n const dropdownHeight = Math.min(450, viewportHeight - 100);\n\n const centerX = viewportWidth / 2;\n const centerY = viewportHeight / 2;\n\n const left = centerX - (dropdownWidth / 2);\n const top = centerY - (dropdownHeight / 2);\n\n setDropdownPosition({\n top: top,\n left: left,\n width: dropdownWidth,\n maxHeight: dropdownHeight\n });\n }\n };\n\n useEffect(() => {\n const handleClickOutside = (event) => {\n if (dropdownRef.current && !dropdownRef.current.contains(event.target) &&\n buttonRef.current && !buttonRef.current.contains(event.target)) {\n setIsOpen(false);\n setSearchTerm('');\n }\n };\n\n const handleResize = () => {\n if (isOpen) {\n updateDropdownPosition();\n }\n };\n\n if (isOpen) {\n updateDropdownPosition();\n\n // Lock body scroll when dropdown is open\n const scrollY = window.scrollY;\n document.body.style.position = 'fixed';\n document.body.style.top = `-${scrollY}px`;\n document.body.style.width = '100%';\n\n document.addEventListener('mousedown', handleClickOutside);\n window.addEventListener('resize', handleResize);\n }\n\n return () => {\n // Unlock body scroll when dropdown closes\n if (isOpen) {\n const scrollY = document.body.style.top;\n document.body.style.position = '';\n document.body.style.top = '';\n document.body.style.width = '';\n window.scrollTo(0, parseInt(scrollY || '0') * -1);\n }\n\n document.removeEventListener('mousedown', handleClickOutside);\n window.removeEventListener('resize', handleResize);\n };\n }, [isOpen]);\n\n const handleToggle = () => {\n if (!disabled) {\n if (!isOpen) {\n updateDropdownPosition();\n }\n setIsOpen(!isOpen);\n }\n };\n\n const dropdownContent = isOpen && (\n <>\n <div\n className=\"fixed inset-0 bg-black bg-opacity-30 transition-opacity\"\n style={{ zIndex: 999998 }}\n onClick={() => {\n setIsOpen(false);\n setSearchTerm('');\n }}\n />\n\n <div\n ref={dropdownRef}\n className=\"fixed bg-white border-2 border-gray-200 rounded-3xl shadow-2xl overflow-hidden\"\n style={{\n top: dropdownPosition.top,\n left: dropdownPosition.left,\n width: dropdownPosition.width,\n maxHeight: dropdownPosition.maxHeight,\n zIndex: 999999,\n transform: 'translateZ(0)',\n boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(0, 0, 0, 0.05)'\n }}\n >\n <div className=\"flex items-center justify-between p-4 border-b border-gray-200 bg-gradient-to-r from-[#7042D2]/10 to-purple-50\">\n <h3 className=\"text-lg font-semibold text-[#7042D2]\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n {placeholder || 'Select Option'}\n </h3>\n <button\n onClick={() => {\n setIsOpen(false);\n setSearchTerm('');\n }}\n className=\"text-gray-500 hover:text-gray-700 transition-colors p-1 rounded-full hover:bg-gray-100\"\n >\n <svg xmlns=\"http://www.w3.org/2000/svg\" className=\"h-5 w-5\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M6 18L18 6M6 6l12 12\" />\n </svg>\n </button>\n </div>\n\n <div className=\"p-4 border-b border-gray-200 bg-gray-50\">\n <input\n type=\"text\"\n placeholder=\"Search networks and tokens...\"\n value={searchTerm}\n onChange={(e) => setSearchTerm(e.target.value)}\n 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\"\n style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}\n autoFocus\n />\n </div>\n\n <div\n className=\"overflow-y-auto custom-scrollbar\"\n style={{\n maxHeight: `${(dropdownPosition.maxHeight || 450) - 180}px`,\n minHeight: '200px'\n }}\n >\n {filteredOptions.length === 0 ? (\n <div className=\"p-8 text-gray-500 text-center\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n <div className=\"text-4xl mb-3\">🔍</div>\n <div className=\"text-lg mb-2\">No options found</div>\n <div className=\"text-sm text-gray-400\">Try a different search term</div>\n </div>\n ) : (\n <>\n <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' }}>\n <span className=\"font-semibold\">{filteredOptions.length}</span> option{filteredOptions.length !== 1 ? 's' : ''} available\n </div>\n\n <div className=\"p-2\">\n {filteredOptions.map((option) => (\n <button\n key={getOptionKey(option)}\n type=\"button\"\n onClick={() => {\n onChange(getOptionValue(option));\n setIsOpen(false);\n setSearchTerm('');\n }}\n className={`w-full p-4 text-left hover:bg-[#7042D2]/10 transition-all duration-200 rounded-xl mb-2 last:mb-0 ${getOptionValue(option) === value\n ? 'bg-[#7042D2]/20 text-[#7042D2] border-2 border-[#7042D2]/30'\n : 'text-gray-800 border-2 border-transparent hover:border-[#7042D2]/20'\n }`}\n style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}\n >\n {renderOption(option)}\n </button>\n ))}\n </div>\n </>\n )}\n </div>\n\n <div className=\"p-3 bg-gradient-to-r from-gray-50 to-gray-100 border-t border-gray-200 text-center\">\n <div className=\"text-xs text-gray-500\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n {filteredOptions.length > 5 ? '↕️ Scroll to see more options' : '✨ Select your preferred option'}\n </div>\n </div>\n </div>\n </>\n );\n\n return (\n <>\n <div className=\"relative\">\n <button\n ref={buttonRef}\n type=\"button\"\n onClick={handleToggle}\n disabled={disabled}\n 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 ${disabled ? 'opacity-50 cursor-not-allowed' : 'hover:border-[#7042D2]/50 cursor-pointer'\n } ${isOpen ? 'border-[#7042D2] ring-3 ring-[#7042D2]/20' : 'border-gray-200'}`}\n style={{\n minHeight: '60px',\n fontFamily: 'Bricolage Grotesque, sans-serif',\n fontSize: '16px',\n fontWeight: '500'\n }}\n >\n <div className=\"flex items-center justify-between\">\n <div className=\"flex items-center space-x-3\">\n {selectedOption ? renderOption(selectedOption) : (\n <span className=\"text-gray-500\">{placeholder}</span>\n )}\n </div>\n <div className={`transform transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}>\n <svg xmlns=\"http://www.w3.org/2000/svg\" className=\"h-5 w-5 text-[#7042D2]\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M19 9l-7 7-7-7\" />\n </svg>\n </div>\n </div>\n </button>\n </div>\n\n {typeof document !== 'undefined' && document.body &&\n ReactDOM.createPortal(dropdownContent, document.body)\n }\n\n <style jsx>{`\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 `}</style>\n </>\n );\n};\n\nexport default ModernDropdown;","import React, { useState, useEffect } from 'react';\n\n// Screen transition wrapper for smooth animations between payment steps\nconst ScreenTransition = ({\n currentStep,\n targetStep,\n children,\n className = \"\",\n duration = 300\n}) => {\n const [isVisible, setIsVisible] = useState(currentStep === targetStep);\n const [shouldRender, setShouldRender] = useState(currentStep === targetStep);\n\n useEffect(() => {\n if (currentStep === targetStep) {\n setShouldRender(true);\n setTimeout(() => setIsVisible(true), 10);\n } else {\n setIsVisible(false);\n setTimeout(() => setShouldRender(false), duration);\n }\n }, [currentStep, targetStep, duration]);\n\n if (!shouldRender) return null;\n\n return (\n <div\n className={`\n transition-all duration-300 ease-out\n ${isVisible\n ? 'transform translate-y-0 opacity-100'\n : 'transform translate-y-full opacity-0'\n }\n ${className}\n `}\n style={{\n transitionDuration: `${duration}ms`\n }}\n >\n {children}\n </div>\n );\n};\n\nexport default ScreenTransition;","// Formatting utilities for the payment system\n\n// Format amount to display with proper decimal places\nexport const formatAmount = (amount) => {\n return parseFloat(amount).toFixed(2);\n};\n\n// Format wallet address with ellipsis in the middle\nexport const formatWalletAddress = (address) => {\n if (!address || address.length <= 16) return address;\n return `${address.slice(0, 6)}...${address.slice(-4)}`;\n};\n\n// Format transaction hash with ellipsis in the middle\nexport const formatTransactionHash = (hash) => {\n if (!hash) return '';\n if (hash.length <= 16) return hash;\n return `${hash.slice(0, 8)}...${hash.slice(-8)}`;\n};\n\n// Format large numbers with proper separators\nexport const formatNumber = (num, decimals = 2) => {\n if (typeof num !== 'number') {\n num = parseFloat(num) || 0;\n }\n return num.toLocaleString('en-US', {\n minimumFractionDigits: decimals,\n maximumFractionDigits: decimals\n });\n};\n\n// Format percentage values\nexport const formatPercentage = (percentage, decimals = 2) => {\n return `${formatNumber(percentage, decimals)}%`;\n};\n\n// Format currency amounts with symbol\nexport const formatCurrency = (amount, symbol = 'USD', decimals = 2) => {\n const formattedAmount = formatNumber(amount, decimals);\n return symbol === 'USD' ? `$${formattedAmount}` : `${formattedAmount} ${symbol}`;\n};\n\n// Format token amounts with proper decimals based on token type\nexport const formatTokenAmount = (amount, decimals = 6, symbol = '') => {\n const divisor = Math.pow(10, decimals);\n const formattedAmount = (Number(amount) / divisor).toFixed(decimals);\n return symbol ? `${formattedAmount} ${symbol}` : formattedAmount;\n};\n\n// Format time duration (for transaction waiting times)\nexport const formatDuration = (seconds) => {\n if (seconds < 60) {\n return `${seconds} second${seconds !== 1 ? 's' : ''}`;\n }\n const minutes = Math.floor(seconds / 60);\n const remainingSeconds = seconds % 60;\n\n if (remainingSeconds === 0) {\n return `${minutes} minute${minutes !== 1 ? 's' : ''}`;\n }\n return `${minutes}m ${remainingSeconds}s`;\n};\n\n// Format gas amounts and fees\nexport const formatGas = (gasAmount, gasPrice = null) => {\n if (gasPrice) {\n const fee = (Number(gasAmount) * Number(gasPrice)) / 1e18; // Convert from wei\n return `${formatNumber(fee, 6)} ETH`;\n }\n return formatNumber(gasAmount, 0);\n};\n\n// Convert wei to ether and format\nexport const formatWeiToEther = (wei, decimals = 6) => {\n const ether = Number(wei) / 1e18;\n return formatNumber(ether, decimals);\n};\n\n// Format network names consistently\nexport const formatNetworkName = (networkName) => {\n const nameMap = {\n 'ethereum': 'Ethereum',\n 'bsc': 'BSC',\n 'polygon': 'Polygon',\n 'arbitrum': 'Arbitrum',\n 'optimism': 'Optimism',\n 'avalanche': 'Avalanche',\n 'celo': 'Celo',\n 'base': 'Base'\n };\n return nameMap[networkName?.toLowerCase()] || networkName;\n};\n\n// Format status messages for user display\nexport const formatStatusMessage = (status, details = {}) => {\n const messages = {\n pending: 'Transaction pending confirmation...',\n processing: 'Processing your payment...',\n confirming: 'Confirming on blockchain...',\n success: 'Payment completed successfully!',\n failed: 'Payment failed. Please try again.',\n cancelled: 'Payment was cancelled.',\n timeout: 'Transaction timed out. Please check your wallet.',\n insufficient_funds: 'Insufficient funds for this transaction.',\n network_error: 'Network error. Please check your connection.',\n user_rejected: 'Transaction was rejected by user.'\n };\n\n let message = messages[status] || `Status: ${status}`;\n\n // Add additional context if provided\n if (details.transactionHash) {\n message += ` (${formatTransactionHash(details.transactionHash)})`;\n }\n\n if (details.amount && details.currency) {\n message += ` Amount: ${formatCurrency(details.amount, details.currency)}`;\n }\n\n return message;\n};\n\n// Format error messages for user display\nexport const formatErrorMessage = (error) => {\n if (!error) return 'An unknown error occurred';\n\n const message = error.message || error.toString();\n\n // Clean up common error messages\n const cleanedMessage = message\n .replace(/^Error:\\s*/, '') // Remove \"Error: \" prefix\n .replace(/execution reverted:?\\s*/i, '') // Remove execution reverted\n .replace(/VM Exception while processing transaction:?\\s*/i, '') // Remove VM exception\n .trim();\n\n // Capitalize first letter\n return cleanedMessage.charAt(0).toUpperCase() + cleanedMessage.slice(1);\n};\n\n// Format validation error messages\nexport const formatValidationError = (field, value, requirement) => {\n const fieldName = field.charAt(0).toUpperCase() + field.slice(1);\n\n switch (requirement) {\n case 'required':\n return `${fieldName} is required`;\n case 'invalid_format':\n return `${fieldName} format is invalid`;\n case 'too_short':\n return `${fieldName} is too short`;\n case 'too_long':\n return `${fieldName} is too long`;\n case 'invalid_address':\n return `${fieldName} must be a valid Ethereum address`;\n case 'insufficient_balance':\n return `Insufficient ${fieldName} balance`;\n default:\n return `${fieldName} validation failed: ${requirement}`;\n }\n};\n\n// Format loading states with progress\nexport const formatLoadingMessage = (step, total = null, currentAction = null) => {\n let message = currentAction || 'Loading...';\n\n if (total && step <= total) {\n message += ` (${step}/${total})`;\n }\n\n return message;\n};\n\n// Format file sizes\nexport const formatFileSize = (bytes) => {\n if (bytes === 0) return '0 Bytes';\n\n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n};\n\n// Truncate text with ellipsis\nexport const truncateText = (text, maxLength = 50) => {\n if (!text || text.length <= maxLength) return text;\n return text.substring(0, maxLength) + '...';\n};\n\n// Format API responses for display\nexport const formatApiResponse = (response) => {\n if (!response) return 'No response';\n\n if (typeof response === 'string') return response;\n\n if (response.message) return response.message;\n if (response.error) return formatErrorMessage(response.error);\n\n return JSON.stringify(response, null, 2);\n};\n\n// Get blockchain explorer URL for transaction\nexport const getExplorerUrl = (transactionHash, network) => {\n if (!transactionHash || !network) return null;\n\n const networkName = typeof network === 'string' ? network : network.shortName || network.name;\n const normalizedNetwork = networkName?.toLowerCase();\n\n const explorerUrls = {\n 'ethereum': `https://etherscan.io/tx/${transactionHash}`,\n 'bsc': `https://bscscan.com/tx/${transactionHash}`,\n 'polygon': `https://polygonscan.com/tx/${transactionHash}`,\n 'arbitrum': `https://arbiscan.io/tx/${transactionHash}`,\n 'optimism': `https://optimistic.etherscan.io/tx/${transactionHash}`,\n 'avalanche': `https://snowtrace.io/tx/${transactionHash}`,\n 'celo': `https://celoscan.io/tx/${transactionHash}`,\n 'base': `https://basescan.org/tx/${transactionHash}`\n };\n\n return explorerUrls[normalizedNetwork] || null;\n};\n\n// Get blockchain explorer name\nexport const getExplorerName = (network) => {\n if (!network) return 'Explorer';\n\n const networkName = typeof network === 'string' ? network : network.shortName || network.name;\n const normalizedNetwork = networkName?.toLowerCase();\n\n const explorerNames = {\n 'ethereum': 'Etherscan',\n 'bsc': 'BscScan',\n 'polygon': 'PolygonScan',\n 'arbitrum': 'Arbiscan',\n 'optimism': 'Optimistic Etherscan',\n 'avalanche': 'SnowTrace',\n 'celo': 'CeloScan',\n 'base': 'BaseScan'\n };\n\n return explorerNames[normalizedNetwork] || 'Explorer';\n};","import React, { useState, useEffect } from 'react';\nimport { formatTransactionHash, getExplorerUrl, getExplorerName } from '../utils/formatUtils';\n\n// Enhanced Payment Status Component with processing step\nconst PaymentStatus = ({\n status,\n message,\n theme = 'light',\n payment = null,\n transactionHash = null,\n selectedPaymentMethod = null,\n selectedNetwork = null,\n merchantName = 'Merchant',\n onClose = null\n}) => {\n const [copiedHash, setCopiedHash] = useState(false);\n const [processingProgress, setProcessingProgress] = useState(0);\n\n // Handle processing progress animation\n useEffect(() => {\n if (status === 'processing') {\n const interval = setInterval(() => {\n setProcessingProgress(prev => {\n if (prev >= 90) return prev; // Don't go to 100% until success\n return prev + Math.random() * 15;\n });\n }, 500);\n\n return () => clearInterval(interval);\n }\n }, [status]);\n\n const copyTransactionHash = async () => {\n if (transactionHash) {\n try {\n await navigator.clipboard.writeText(transactionHash);\n setCopiedHash(true);\n setTimeout(() => setCopiedHash(false), 2000);\n } catch (err) {\n }\n }\n };\n\n const renderIcon = () => {\n switch (status) {\n case 'processing':\n return (\n <div className=\"relative\">\n <div className=\"animate-spin rounded-full h-12 w-12 border-4 border-t-[#7042D2] border-blue-500/20\"></div>\n <div className=\"absolute inset-0 flex items-center justify-center\">\n <div className=\"w-6 h-6 bg-[#7042D2] rounded-full animate-pulse\"></div>\n </div>\n </div>\n );\n case 'success':\n return (\n <div className=\"rounded-full h-16 w-16 bg-green-500 flex items-center justify-center animate-bounce\">\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n className=\"h-10 w-10 text-white\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n strokeWidth={3}\n >\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M5 13l4 4L19 7\" />\n </svg>\n </div>\n );\n case 'error':\n return (\n <div className=\"rounded-full h-12 w-12 bg-red-100 flex items-center justify-center\">\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n className=\"h-8 w-8 text-red-500\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n strokeWidth={2}\n >\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" d=\"M6 18L18 6M6 6l12 12\" />\n </svg>\n </div>\n );\n default:\n return null;\n }\n };\n\n // Enhanced processing screen\n if (status === 'processing') {\n return (\n <div className=\"flex flex-col items-center justify-center py-6 px-4\">\n <div className=\"mb-6\">{renderIcon()}</div>\n\n <h3 className=\"text-xl font-bold mb-3 text-gray-900\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Processing Payment\n </h3>\n\n <p className=\"text-center text-gray-600 mb-6\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Your transaction has been sent to the blockchain and is being processed...\n </p>\n\n {/* Progress Bar */}\n <div className=\"w-full max-w-xs mb-4\">\n <div className=\"bg-gray-200 rounded-full h-3\">\n <div\n className=\"bg-[#7042D2] h-3 rounded-full transition-all duration-500 ease-out\"\n style={{ width: `${processingProgress}%` }}\n ></div>\n </div>\n <div className=\"text-center mt-2 text-sm text-gray-500\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Processing... {Math.round(processingProgress)}%\n </div>\n </div>\n\n {/* Processing Steps */}\n <div className=\"text-center space-y-2\">\n <div className=\"flex items-center justify-center space-x-2\">\n <div className=\"w-2 h-2 bg-green-500 rounded-full animate-pulse\"></div>\n <span className=\"text-sm text-gray-600\">Transaction submitted</span>\n </div>\n <div className=\"flex items-center justify-center space-x-2\">\n <div className=\"w-2 h-2 bg-yellow-500 rounded-full animate-pulse\"></div>\n <span className=\"text-sm text-gray-600\">Confirming on blockchain...</span>\n </div>\n <div className=\"flex items-center justify-center space-x-2\">\n <div className=\"w-2 h-2 bg-gray-300 rounded-full\"></div>\n <span className=\"text-sm text-gray-400\">Finalizing payment...</span>\n </div>\n </div>\n\n <div className=\"mt-6 p-3 bg-blue-50 rounded-lg border border-blue-200\">\n <p className=\"text-xs text-blue-800 text-center\">\n Please don't close this window. This usually takes 10-30 seconds.\n </p>\n </div>\n </div>\n );\n }\n\n if (status === 'success') {\n return (\n <div className=\"flex flex-col items-center justify-center py-6 px-4\">\n <div className=\"mb-6\">{renderIcon()}</div>\n\n <h3 className=\"text-2xl font-bold mb-3 text-gray-900\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Payment Successful!\n </h3>\n\n {payment && selectedPaymentMethod && (\n <p className=\"text-center max-w-[235px] mb-6 text-gray-600\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Your payment of <span className='text-[#7042D2] font-semibold'>{payment.totalAmount || payment.amount} {selectedPaymentMethod.currency}</span> has been completed.\n </p>\n )}\n\n {transactionHash && (\n <div className=\"w-full mb-6 px-4\">\n <p className=\"text-sm font-medium mb-2 text-gray-700\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Transaction Details\n </p>\n\n {/* Transaction Hash with Copy Button */}\n <div\n 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\"\n onClick={copyTransactionHash}\n >\n <span className=\"font-mono text-sm text-gray-700\">\n {formatTransactionHash(transactionHash)}\n </span>\n <div className=\"flex items-center\">\n {copiedHash ? (\n <span className=\"text-green-500 text-xs font-medium mr-2\">Copied!</span>\n ) : null}\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n className=\"h-4 w-4 text-gray-500\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <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\" />\n </svg>\n </div>\n </div>\n\n {/* View on Explorer Button */}\n {(() => {\n const explorerUrl = getExplorerUrl(transactionHash, selectedNetwork);\n const explorerName = getExplorerName(selectedNetwork);\n\n\n return selectedNetwork && explorerUrl && (\n <a\n href={explorerUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n 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\"\n >\n <span className=\"text-sm font-medium text-[#7042D2]\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n View on {explorerName}\n </span>\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n className=\"h-4 w-4 text-[#7042D2] group-hover:translate-x-1 transition-transform\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n strokeWidth={2}\n >\n <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\" />\n </svg>\n </a>\n );\n })()}\n </div>\n )}\n\n {onClose && (\n <button\n onClick={onClose}\n className=\"w-full py-3 px-4 bg-[#7042D2] text-white font-semibold rounded-2xl text-lg shadow-md hover:bg-[#5b34b1] transition-colors\"\n style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}\n >\n Close\n </button>\n )}\n </div>\n );\n }\n\n return (\n <div className=\"flex flex-col items-center justify-center py-6\">\n <div className=\"mb-4\">{renderIcon()}</div>\n <h3 className=\"text-xl font-bold mb-2 text-gray-900\">\n {status === 'processing' ? 'Processing Payment' : status === 'error' ? 'Payment Failed' : 'Unknown Status'}\n </h3>\n <p className=\"text-center text-gray-600\">{message}</p>\n </div>\n );\n};\n\nexport default PaymentStatus;","// CoinMarketCap logo base URL\nexport const CMC_LOGO_BASE_URL = 'https://s2.coinmarketcap.com/static/img/coins/64x64';\n\n// CoinMarketCap ID mappings for cryptocurrencies\nexport const CMC_IDS = {\n bitcoin: 1,\n ethereum: 1027,\n bsc: 1839,\n polygon: 3890,\n cardano: 2010,\n avalanche: 5805,\n fantom: 3513,\n arbitrum: 11841,\n optimism: 11840,\n USDT: 825,\n USDC: 3408,\n BUSD: 4687,\n DAI: 4943,\n FRAX: 6952,\n TUSD: 2563,\n USDP: 5992,\n USDD: 5994,\n FDUSD: 26081,\n PYUSD: 28295,\n WBTC: 3717,\n LINK: 1975,\n UNI: 7083,\n AAVE: 7278,\n COMP: 5692,\n YFI: 5864,\n MKR: 1518,\n SUSHI: 6758,\n CRV: 6538,\n SNX: 2586,\n UMA: 5617,\n BAL: 5728,\n MANA: 1966,\n SAND: 6210,\n APE: 18876,\n LDO: 8000,\n GRT: 6719,\n ENS: 13855,\n RPL: 2943,\n SHIB: 5994,\n MATIC: 3890,\n BNB: 1839,\n ADA: 2010,\n SOL: 5426,\n DOT: 6636,\n AVAX: 5805,\n TRX: 1958,\n ALGO: 4030,\n FTM: 3513,\n ARB: 11841,\n OP: 11840,\n \"1INCH\": 8104,\n DYDX: 11156,\n ICP: 8916,\n FIL: 2280,\n CAKE: 7186,\n RUNE: 4157,\n ALPHA: 7232,\n BNT: 1727,\n KNC: 1982,\n ZRX: 1896,\n REN: 2539,\n LRC: 1934,\n WETH: 2396,\n WMATIC: 3890,\n WBNB: 1839,\n UST: 7129,\n USTC: 7129,\n LUSD: 8115,\n MIM: 9681,\n FEI: 8642,\n TRIBE: 8741,\n RAI: 8525,\n SUSD: 2927,\n};\n\n// Network logo URLs\nexport const NETWORK_LOGOS = {\n ethereum: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png',\n bsc: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png',\n polygon: 'https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png',\n arbitrum: 'https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png',\n avalanche: 'https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png',\n celo: 'https://s2.coinmarketcap.com/static/img/coins/64x64/5567.png',\n optimism: 'https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png',\n base: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png', // Base uses ETH logo\n eth: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png',\n bnb: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png',\n trx: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1958.png',\n algo: 'https://s2.coinmarketcap.com/static/img/coins/64x64/4030.png',\n sol: 'https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png',\n matic: 'https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png',\n arb: 'https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png',\n avax: 'https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png',\n op: 'https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png'\n};\n\n// Wallet icon mappings\nexport const WALLET_ICONS = {\n metamask: 'https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg',\n coinbase: 'https://avatars.githubusercontent.com/u/18060234?s=280&v=4',\n rabby: 'https://rabby.io/logo-128.png',\n zerion: 'https://app.zerion.io/favicon-32x32.png',\n phantom: 'https://phantom.app/favicons/apple-touch-icon.png',\n trust: 'https://trustwallet.com/favicon-196x196.png',\n okx: 'https://static.okx.com/cdn/assets/imgs/248/58E63FEA47A2B7D7.png',\n binance: 'https://bin.bnbstatic.com/static/images/common/favicon.ico',\n cryptocom: 'https://crypto.com/favicon.ico',\n hot: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiNGRjZBNkEiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmg0djhoLTR2LTJoMnYtNGgtMnYtMnptNiAwaDJ2MmgtdjdoLTJ2LTIiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg==',\n backpack: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiMwMEQ0QUEiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMGg4djJoLTJ2NmgtdjhoLTZWMTB6bTIgMnY0aDJWMTJ6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4=',\n '1inch': 'https://1inch.io/favicon.svg',\n default: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiM2MzY2RjEiIHN0cm9rZT0iI0Y5RkFGQiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmgxMnY4SDEweiIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIxLjUiIHJ4PSIxIi8+CjxjaXJjbGUgY3g9IjE4IiBjeT0iMTYiIHI9IjEiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg=='\n};\n\n// Get CMC logo URL for a symbol\nexport const getCmcLogoUrl = (symbol) => {\n if (!symbol) return null;\n\n const directId = CMC_IDS[symbol.toUpperCase()];\n if (directId) {\n return `${CMC_LOGO_BASE_URL}/${directId}.png`;\n }\n\n return null;\n};\n\n// Get token logo URL\nexport const getTokenLogoUrl = (symbol) => {\n return getCmcLogoUrl(symbol);\n};\n\n// Get network logo URL - Prioritize API logo over hardcoded fallback\nexport const getNetworkLogoUrl = (networkOrShortName) => {\n // If passed a full network object with logo field from API, use it\n if (typeof networkOrShortName === 'object' && networkOrShortName?.logo) {\n return networkOrShortName.logo;\n }\n\n // If passed a network object with shortName, try hardcoded fallback\n if (typeof networkOrShortName === 'object' && networkOrShortName?.shortName) {\n return NETWORK_LOGOS[networkOrShortName.shortName.toLowerCase()];\n }\n\n // If passed a string (shortName), use hardcoded fallback\n if (typeof networkOrShortName === 'string') {\n return NETWORK_LOGOS[networkOrShortName.toLowerCase()];\n }\n\n return null;\n};\n\n// Get wallet icon URL\nexport const getWalletIcon = (connectorName, connectorId) => {\n const name = connectorName.toLowerCase();\n const id = connectorId.toLowerCase();\n\n // Check for specific wallet matches\n for (const [key, icon] of Object.entries(WALLET_ICONS)) {\n if (name.includes(key) || id.includes(key)) {\n return icon;\n }\n }\n\n return WALLET_ICONS.default;\n};","import { getWalletIcon } from '../config/logoConfig';\nimport { getTrustChainId } from '../config/chainConfig';\n\n// Mobile detection utility\nexport const detectMobile = () => {\n return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);\n};\n\n// Helper function to check if a wallet is detected in the browser\nexport const isWalletDetected = (walletType) => {\n switch (walletType) {\n case 'trust':\n return window.ethereum && window.ethereum.isTrust === true;\n case 'metaMask':\n return window.ethereum && window.ethereum.isMetaMask === true;\n case 'injected':\n return window.ethereum && !window.ethereum.isMetaMask && !window.ethereum.isCoinbaseWallet;\n default:\n return false;\n }\n};\n\n// Convert Wagmi connectors to our wallet format\nexport const createWalletFromConnector = (connector, selectedNetwork) => {\n return {\n type: connector.id,\n name: connector.name,\n icon: getWalletIcon(connector.name, connector.id),\n description: `Connect using ${connector.name}`,\n isInstalled: true,\n connector: connector,\n isWagmi: true\n };\n};\n\n// Create custom mobile wallets that aren't covered by wagmi\nexport const getCustomMobileWallets = () => {\n return [\n {\n type: 'trust',\n name: 'Trust Wallet',\n icon: '🛡️',\n description: 'Multi-chain wallet with transaction deep links',\n isInstalled: false,\n connector: null,\n isWagmi: false,\n mobileOnly: true,\n hasTransactionDeepLinks: true\n }\n ];\n};\n\n// Get available wallets based on device and network\nexport const getAvailableWallets = (connectors, selectedNetwork) => {\n\n if (!selectedNetwork) {\n return [];\n }\n\n // Check if network is EVM-compatible\n const evmNetworks = ['ethereum', 'bsc', 'polygon', 'arbitrum', 'optimism', 'avalanche', 'celo', 'base'];\n if (!evmNetworks.includes(selectedNetwork.shortName)) {\n return [];\n }\n\n // Map all connectors (they all support EVM chains)\n const wagmiWallets = (connectors || []).map(connector =>\n createWalletFromConnector(connector, selectedNetwork)\n );\n\n\n const isMobile = detectMobile();\n const customMobileWallets = isMobile ? getCustomMobileWallets() : [];\n\n const allWallets = [...wagmiWallets, ...customMobileWallets];\n\n return allWallets;\n};\n\n// Get wallet store URLs for mobile app downloads\nexport const getWalletStoreUrl = (walletType, platform) => {\n const storeUrls = {\n trust: {\n ios: 'https://apps.apple.com/app/trust-crypto-bitcoin-wallet/id1288339409',\n android: 'https://play.google.com/store/apps/details?id=com.wallet.crypto.trustapp'\n }\n };\n\n return storeUrls[walletType]?.[platform] || storeUrls.trust[platform];\n};\n\n// Helper function to attempt app opening with proper fallback detection\nexport const attemptAppOpen = (deepLink, storeUrls) => {\n return new Promise((resolve) => {\n let appOpened = false;\n let fallbackTimeout;\n\n // Detect if the user navigates away from the page (app opened)\n const handleVisibilityChange = () => {\n if (document.hidden) {\n appOpened = true;\n clearTimeout(fallbackTimeout);\n cleanup();\n resolve(true);\n }\n };\n\n // Detect if the user focuses back after some time (might indicate app was opened)\n const handleFocus = () => {\n // Give a small delay to see if app actually opened\n setTimeout(() => {\n if (!appOpened) {\n appOpened = true;\n clearTimeout(fallbackTimeout);\n cleanup();\n resolve(true);\n }\n }, 100);\n };\n\n const cleanup = () => {\n document.removeEventListener('visibilitychange', handleVisibilityChange);\n window.removeEventListener('focus', handleFocus);\n };\n\n // Set up listeners\n document.addEventListener('visibilitychange', handleVisibilityChange);\n window.addEventListener('focus', handleFocus);\n\n // Try to open the app\n window.location.href = deepLink;\n\n // Fallback to app store if app doesn't open within 3 seconds\n fallbackTimeout = setTimeout(() => {\n if (!appOpened) {\n cleanup();\n\n // Only redirect to store if we're confident the app didn't open\n const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);\n const storeUrl = isIOS ? storeUrls.ios : storeUrls.android;\n\n window.location.href = storeUrl;\n resolve(false);\n }\n }, 3000); // Increased to 3 seconds\n });\n};\n\n// Generate session ID for transaction tracking\nexport const generateSessionId = () => {\n return Math.random().toString(36).substring(2, 15) + Date.now().toString(36);\n};\n\n// Store session data for mobile transaction tracking\nexport const storeTransactionSession = (sessionId, sessionData) => {\n localStorage.setItem(`tx_session_${sessionId}`, JSON.stringify(sessionData));\n};\n\n// Retrieve session data for mobile transaction tracking\nexport const getTransactionSession = (sessionId) => {\n const sessionData = localStorage.getItem(`tx_session_${sessionId}`);\n return sessionData ? JSON.parse(sessionData) : null;\n};\n\n// Clear session data for mobile transaction tracking\nexport const clearTransactionSession = (sessionId) => {\n localStorage.removeItem(`tx_session_${sessionId}`);\n};\n\n// Handle transaction callback when user returns from wallet\nexport const handleTransactionCallback = () => {\n const urlParams = new URLSearchParams(window.location.search);\n const txCallback = urlParams.get('tx_callback');\n const sessionId = urlParams.get('sessionId');\n const txHash = urlParams.get('hash');\n const txError = urlParams.get('error');\n\n if (txCallback && sessionId) {\n const sessionData = getTransactionSession(sessionId);\n if (sessionData) {\n clearTransactionSession(sessionId);\n\n // Clean up URL parameters\n const cleanUrl = window.location.origin + window.location.pathname;\n window.history.replaceState({}, document.title, cleanUrl);\n\n return {\n sessionData,\n txHash,\n txError,\n success: !!(txHash && !txError)\n };\n }\n }\n\n return null;\n};","import { getTrustChainId, getChainId } from '../config/chainConfig';\nimport { generateSessionId, storeTransactionSession, clearTransactionSession, getTransactionSession } from './walletUtils';\n\n// Helper function to map chain IDs to Trust Wallet coin IDs\n// IMPORTANT: Trust Wallet's DApp browser (open_url) uses coin_id=60 for ALL EVM chains\n// because they all use the same Ethereum-compatible Web3 provider.\n// Network switching happens AFTER the DApp browser opens via the injected provider.\nconst getCoinIdForChain = (chainId) => {\n // Handle hex chainId (e.g., \"0x89\" for Polygon)\n const normalizedChainId = typeof chainId === 'string' && chainId.startsWith('0x')\n ? parseInt(chainId, 16)\n : parseInt(chainId);\n\n // For Trust Wallet DApp browser, ALL EVM chains use coin_id=60\n // This ensures the DApp browser opens correctly\n const evmChains = [1, 56, 137, 42161, 10, 43114, 42220, 8453]; // Ethereum, BSC, Polygon, Arbitrum, Optimism, Avalanche, Celo, Base\n\n if (evmChains.includes(normalizedChainId)) {\n return 60;\n }\n\n // For non-EVM chains, use specific coin_ids (future use)\n const chainToCoinId = {\n // Non-EVM chains would go here\n };\n\n const coinId = chainToCoinId[normalizedChainId] || 60;\n return coinId;\n};\n\n// Simple QR Payment URI generation - NO COMPLEX VALIDATION\nexport const generateQRPaymentURI = (paymentData, selectedToken, selectedNetwork, config, preferredWallet = 'metamask', apiConfig = null) => {\n if (!paymentData) return null;\n\n try {\n const baseUrl = 'https://paymentscreen.vercel.app';\n\n\n // ⭐ OPTIMIZED: Minimal params - payment screen fetches rest from backend\n const params = new URLSearchParams();\n\n // ⭐ ONLY ESSENTIAL PARAMETERS (rest fetched from backend using paymentId)\n const paymentId = paymentData?.id || paymentData?.splitterPaymentId;\n if (!paymentId) {\n return null;\n }\n params.set('paymentId', paymentId);\n\n // Preferred wallet for deep link (essential for UX)\n params.set('preferredWallet', preferredWallet);\n\n // Mobile flag (helps payment screen optimize UI)\n params.set('isMobile', 'true');\n\n const paymentScreenUrl = `${baseUrl}?${params.toString()}`;\n\n\n // Generate wallet-specific deep link that opens the payment screen in wallet browser\n let deepLinkUrl;\n\n switch (preferredWallet) {\n case 'metamask':\n const metaMaskUrl = paymentScreenUrl.replace('https://', '');\n deepLinkUrl = `https://metamask.app.link/dapp/${metaMaskUrl}`;\n break;\n\n case 'trust':\n // ⭐ CRITICAL FIX: Trust Wallet requires 'coin_id' parameter for proper DApp browser mode\n // Format: https://link.trustwallet.com/open_url?coin_id=60&url=ENCODED_URL\n // coin_id=60 is Ethereum (standard for all EVM chains in Trust Wallet)\n const chainIdForCoin = selectedNetwork?.chainId || 1;\n const coinId = getCoinIdForChain(chainIdForCoin); // Default to 60 (Ethereum) for EVM chains\n deepLinkUrl = `https://link.trustwallet.com/open_url?coin_id=${coinId}&url=${encodeURIComponent(paymentScreenUrl)}`;\n break;\n\n case 'coinbase':\n deepLinkUrl = `https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(paymentScreenUrl)}`;\n break;\n\n default:\n // Direct payment screen URL for other wallets\n deepLinkUrl = paymentScreenUrl;\n }\n\n return deepLinkUrl;\n\n } catch (error) {\n return null;\n }\n};\n\n// Helper function to get display name for networks\nconst getNetworkDisplayName = (shortName) => {\n const networkNames = {\n 'ethereum': 'Ethereum Mainnet',\n 'bsc': 'BSC',\n 'polygon': 'Polygon',\n 'arbitrum': 'Arbitrum One',\n 'optimism': 'Optimism',\n 'avalanche': 'Avalanche',\n 'celo': 'Celo',\n 'base': 'Base'\n };\n return networkNames[shortName] || shortName;\n};\n\n// Keep other necessary functions from original file\nexport const generateMobilePaymentDeepLink = (walletType, paymentUri) => {\n if (!paymentUri) return null;\n\n try {\n\n switch (walletType) {\n case 'metamask':\n const metaMaskUrl = paymentUri.includes('metamask.app.link')\n ? paymentUri\n : `https://metamask.app.link/dapp/${paymentUri.replace('https://', '')}`;\n return metaMaskUrl;\n\n case 'trust':\n // ⭐ CRITICAL: Add coin_id parameter for proper DApp browser activation\n const trustUrl = paymentUri.includes('link.trustwallet.com')\n ? paymentUri\n : `https://link.trustwallet.com/open_url?coin_id=60&url=${encodeURIComponent(paymentUri)}`;\n return trustUrl;\n\n case 'coinbase':\n const coinbaseUrl = paymentUri.includes('go.cb-w.com')\n ? paymentUri\n : `https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(paymentUri)}`;\n return coinbaseUrl;\n\n default:\n return paymentUri;\n }\n } catch (error) {\n return paymentUri;\n }\n};","import React, { useState, useEffect, useRef } from 'react';\nimport QRCode from 'qrcode';\nimport { detectMobile } from '../utils/walletUtils';\nimport { getTokenInfo, getChainId } from '../config/chainConfig';\nimport { formatWalletAddress } from '../utils/formatUtils';\nimport { generateQRPaymentURI } from '../utils/deepLinkUtils';\n\nconst QRCodeDisplay = ({\n walletAddress,\n amount,\n currency,\n network,\n theme = 'light',\n paymentData = null,\n onPaymentDetected = null,\n config = null,\n selectedToken = null,\n selectedNetwork = null,\n preferredWallet = 'metamask', // Default to MetaMask for best compatibility\n compact = false\n}) => {\n const [qrData, setQrData] = useState('');\n const [qrCodeImage, setQrCodeImage] = useState('');\n const [isGenerating, setIsGenerating] = useState(true);\n const [monitoringPayment, setMonitoringPayment] = useState(false);\n const [transactionDetected, setTransactionDetected] = useState(false);\n\n const monitoringInterval = useRef(null);\n\n useEffect(() => {\n const generateQRCode = async () => {\n if (!paymentData?.id) {\n setIsGenerating(false);\n return;\n }\n\n setIsGenerating(true);\n\n try {\n // 🔧 CRITICAL FIX: Use complete objects instead of fallbacks\n // Ensure we have complete selectedToken and selectedNetwork objects\n if (!selectedToken || !selectedToken.contractAddress) {\n throw new Error('Cannot generate QR code: Token contract address required');\n }\n\n if (!selectedNetwork || !selectedNetwork.chainId) {\n throw new Error('Cannot generate QR code: Network chain ID required');\n }\n\n // Generate Coinley payment URL with wallet deep link for smart QR system\n const paymentUri = generateQRPaymentURI(\n paymentData,\n selectedToken, // ✅ Use complete token object\n selectedNetwork, // ✅ Use complete network object\n config, // ✅ Use complete config object\n preferredWallet // Pass the preferred wallet for deep link generation\n );\n\n\n // Check if the deep link actually contains the wallet-specific URL\n if (paymentUri.includes('metamask.app.link')) {\n } else if (paymentUri.includes('link.trustwallet.com')) {\n } else if (paymentUri.includes('go.cb-w.com')) {\n } else {\n }\n\n if (!paymentUri) {\n throw new Error('Failed to generate Coinley payment URL');\n }\n\n setQrData(paymentUri);\n\n // Generate actual QR code image - OPTIMIZED FOR COMPACT DISPLAY\n const isMobile = detectMobile();\n const qrImage = await QRCode.toDataURL(paymentUri, {\n width: compact ? 140 : (isMobile ? 350 : 280), // ⭐ COMPACT: 140px for side-by-side layout\n margin: 2, // ⭐ Minimal margin for compact display\n errorCorrectionLevel: 'M', // ⭐ MEDIUM (15%) - good balance for reliability\n color: {\n dark: theme === 'dark' ? '#FFFFFF' : '#000000',\n light: theme === 'dark' ? '#000000' : '#FFFFFF'\n }\n });\n\n setQrCodeImage(qrImage);\n setIsGenerating(false);\n\n\n } catch (error) {\n setIsGenerating(false);\n }\n };\n\n generateQRCode();\n\n // ❌ MONITORING DISABLED - Requires backend blockchain monitoring implementation\n // if (paymentData && !monitoringPayment) {\n // startTransactionMonitoring();\n // }\n }, [paymentData, amount, currency, network, theme, selectedToken, selectedNetwork, config, preferredWallet]);\n\n // Cleanup monitoring on unmount\n useEffect(() => {\n return () => {\n if (monitoringInterval.current) {\n clearInterval(monitoringInterval.current);\n }\n };\n }, []);\n\n const startTransactionMonitoring = async () => {\n if (!paymentData || monitoringPayment) return;\n\n setMonitoringPayment(true);\n\n // Monitor transactions every 10 seconds\n monitoringInterval.current = setInterval(async () => {\n try {\n await checkForTransaction();\n } catch (error) {\n }\n }, 10000);\n\n // Also check immediately\n setTimeout(checkForTransaction, 2000);\n };\n\n const checkForTransaction = async () => {\n if (!paymentData || transactionDetected) return;\n\n try {\n\n // ❌ REMOVE THIS - POLLING NOT IMPLEMENTED YET\n // This would require backend blockchain monitoring\n return;\n\n } catch (error) {\n }\n };\n\n return (\n <div className=\"flex flex-col items-center\">\n {/* ✅ ULTRA-COMPACT: Side-by-side QR + Info layout to save vertical space */}\n <div className=\"flex gap-3 items-start w-full mb-2\">\n {/* QR Code - Smaller size */}\n <div className=\"p-1.5 rounded-lg bg-white shadow-sm border flex-shrink-0\">\n {isGenerating ? (\n <div className=\"flex items-center justify-center\" style={{ width: 140, height: 140 }}>\n <div className=\"text-center\">\n <div className=\"animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600 mx-auto mb-1\"></div>\n <div className=\"text-xs text-gray-600\">Generating...</div>\n </div>\n </div>\n ) : (\n qrCodeImage ? (\n <img\n src={qrCodeImage}\n alt=\"Payment QR Code\"\n className=\"rounded-lg\"\n style={{ width: 140, height: 140 }}\n />\n ) : (\n <div className=\"flex items-center justify-center bg-gray-100 rounded-lg\" style={{ width: 140, height: 140 }}>\n <div className=\"text-center p-2\">\n <div className=\"text-lg mb-1\">⚠️</div>\n <div className=\"text-xs text-gray-600\">\n {!paymentData?.id ? 'Payment not created' : 'QR Failed'}\n </div>\n </div>\n </div>\n )\n )}\n </div>\n\n {/* Payment Info - Beside QR code */}\n <div className=\"flex-1 flex flex-col justify-center\">\n <div className=\"p-2 bg-gray-50 rounded-lg mb-2\">\n <div className=\"flex justify-between items-center mb-1\">\n <span className=\"text-xs font-medium text-gray-600\">Amount:</span>\n <span className=\"text-sm font-bold text-[#7042D2]\">{amount} {currency}</span>\n </div>\n <div className=\"flex justify-between items-center\">\n <span className=\"text-xs text-gray-500\">Network:</span>\n <span className=\"text-xs font-medium text-gray-700\">{network}</span>\n </div>\n </div>\n\n {/* Status/Instruction */}\n {transactionDetected ? (\n <div className=\"flex items-center justify-center text-xs font-semibold text-green-600 p-1.5 bg-green-50 rounded-lg\">\n <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\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M5 13l4 4L19 7\" />\n </svg>\n Payment Received!\n </div>\n ) : (\n <div className=\"p-1.5 rounded-lg bg-blue-50 border border-blue-200\">\n <p className=\"text-xs text-blue-700 text-center leading-tight\">\n 📱 Scan with phone camera\n </p>\n </div>\n )}\n </div>\n </div>\n </div>\n );\n};\n\nexport default QRCodeDisplay;","import React, { useState } from 'react';\nimport { useConnect, useAccount } from 'wagmi';\nimport ModernDropdown from './ModernDropdown';\nimport { detectMobile } from '../utils/walletUtils';\nimport {\n getAvailableWallets,\n isWalletDetected,\n handleTransactionCallback\n} from '../utils/walletUtils';\nimport { getWalletIcon } from '../config/logoConfig';\n\nconst WalletSelector = ({\n selectedNetwork,\n onWalletSelect,\n onConnect,\n connectedWallet,\n loading,\n paymentData = null,\n selectedToken = null,\n api = null\n}) => {\n const [selectedWalletType, setSelectedWalletType] = useState(null);\n\n // Use Wagmi's built-in connector detection\n const { connectors } = useConnect();\n const { isConnected, address } = useAccount();\n\n // Get available wallets based on device and network\n const availableWallets = getAvailableWallets(connectors, selectedNetwork);\n\n\n const handleWalletSelection = async (walletType) => {\n setSelectedWalletType(walletType);\n const wallet = availableWallets.find(w => w.type === walletType);\n\n if (wallet) {\n onWalletSelect(walletType);\n\n if (wallet.isWagmi && wallet.connector) {\n // Standard wagmi connector\n await onConnect(wallet.connector);\n } else if (!wallet.isWagmi) {\n // Custom mobile wallet - handle with deep linking\n await handleCustomWalletConnection(wallet, walletType);\n }\n }\n };\n\n const handleCustomWalletConnection = async (wallet, walletType) => {\n const isMobile = detectMobile();\n\n if (!isMobile) {\n // Desktop: Show download instructions\n alert(`Please install ${wallet.name} mobile app or use the browser extension if available.`);\n return;\n }\n\n // For mobile wallets, we need payment data to create deep links\n if (!paymentData) {\n alert('Please create a payment first before selecting a mobile wallet.');\n return;\n }\n\n try {\n\n // Import deep link utilities\n const { generateQRPaymentURI, generateMobilePaymentDeepLink } = await import('../utils/deepLinkUtils');\n\n // Generate payment URL\n const paymentUri = generateQRPaymentURI(\n paymentData,\n selectedToken,\n selectedNetwork,\n api?.config || {},\n walletType\n );\n\n if (!paymentUri) {\n throw new Error('Failed to generate payment URL');\n }\n\n // Generate mobile deep link\n const mobileDeepLink = generateMobilePaymentDeepLink(walletType, paymentUri);\n\n if (!mobileDeepLink) {\n throw new Error(`Failed to generate ${wallet.name} deep link`);\n }\n\n\n // Open wallet app\n window.location.href = mobileDeepLink;\n\n } catch (error) {\n alert(`Failed to open ${wallet.name}: ${error.message}`);\n }\n };\n\n // Render wallet option for dropdown\n const renderWalletOption = (wallet) => {\n return (\n <div className=\"flex items-center space-x-3\">\n <div className=\"w-8 h-8 flex items-center justify-center\">\n {wallet.icon.startsWith('http') || wallet.icon.startsWith('data:') ? (\n <img\n src={wallet.icon}\n alt={wallet.name}\n className=\"w-6 h-6 rounded-full object-contain\"\n onError={(e) => {\n e.target.style.display = 'none';\n e.target.nextSibling.style.display = 'block';\n }}\n />\n ) : (\n <div className=\"text-2xl\">{wallet.icon}</div>\n )}\n <div className=\"text-xl\" style={{display: 'none'}}>🔗</div>\n </div>\n <div className=\"flex-1\">\n <div className=\"font-semibold text-gray-800 flex items-center\">\n {wallet.name}\n {isWalletDetected(wallet.type) && (\n <span className=\"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full\">\n DETECTED\n </span>\n )}\n {connectedWallet?.walletType === wallet.type && (\n <span className=\"ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full\">\n CONNECTED\n </span>\n )}\n </div>\n <div className=\"text-sm text-gray-500\">\n {connectedWallet?.walletType === wallet.type\n ? `Connected • ${connectedWallet.account?.slice(0, 6)}...${connectedWallet.account?.slice(-4)}`\n : wallet.description\n }\n </div>\n </div>\n {loading && selectedWalletType === wallet.type && (\n <div className=\"animate-spin rounded-full h-5 w-5 border-b-2 border-[#7042D2]\"></div>\n )}\n </div>\n );\n };\n\n if (!selectedNetwork) {\n return (\n <div className=\"text-center p-4\">\n <p className=\"text-gray-500\">Please select a network first</p>\n </div>\n );\n }\n\n if (availableWallets.length === 0) {\n return (\n <div className=\"text-center p-4\">\n <p className=\"text-gray-500 mb-4\">No compatible wallets found for {selectedNetwork.name}</p>\n <div className=\"p-3 bg-amber-50 rounded-lg border border-amber-200\">\n <div className=\"text-sm text-amber-800\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n <div className=\"font-medium mb-2\">Install a compatible wallet:</div>\n <div className=\"space-y-1 text-xs\">\n <div>• <a href=\"https://metamask.io/download/\" target=\"_blank\" rel=\"noopener noreferrer\" className=\"text-amber-700 underline hover:text-amber-900\">Install MetaMask Wallet</a></div>\n <div>• <a href=\"https://www.coinbase.com/wallet\" target=\"_blank\" rel=\"noopener noreferrer\" className=\"text-amber-700 underline hover:text-amber-900\">Install Coinbase Wallet</a></div>\n </div>\n </div>\n </div>\n </div>\n );\n }\n\n return (\n <div className=\"space-y-4\">\n <label className=\"block text-sm font-medium text-gray-700\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Select Wallet for {selectedNetwork.name}\n </label>\n\n {/* Beautiful Wallet Dropdown */}\n <ModernDropdown\n options={availableWallets}\n value={connectedWallet?.walletType || selectedWalletType || ''}\n onChange={handleWalletSelection}\n placeholder=\"Choose your wallet...\"\n renderOption={renderWalletOption}\n getOptionKey={(wallet) => wallet.type}\n getOptionValue={(wallet) => wallet.type}\n getSearchableText={(wallet) => `${wallet.name} ${wallet.description}`}\n disabled={loading}\n />\n </div>\n );\n};\n\nexport default WalletSelector;","/**\n * Debug Utilities for Production-Safe Logging\n *\n * Controls whether debug logs are shown based on environment\n * In production, only errors are logged\n */\n\n// Check if we're in development mode\nconst isDevelopment = () => {\n // Check multiple conditions\n if (typeof process !== 'undefined' && process.env) {\n return process.env.NODE_ENV === 'development';\n }\n\n // Fallback: check hostname for localhost\n if (typeof window !== 'undefined') {\n const hostname = window.location.hostname;\n return hostname === 'localhost' || hostname === '127.0.0.1' || hostname.includes('192.168.');\n }\n\n return false;\n};\n\n// Check if debug mode is explicitly enabled via URL param\nconst isDebugEnabled = () => {\n if (typeof window !== 'undefined') {\n const urlParams = new URLSearchParams(window.location.search);\n return urlParams.get('debug') === 'true' || urlParams.get('debugMode') === 'true';\n }\n return false;\n};\n\n// Master debug flag\nexport const DEBUG_MODE = isDevelopment() || isDebugEnabled();\n\n/**\n * Safe console.log that only logs in development or when debug=true\n */\nexport const debugLog = (...args) => {\n if (DEBUG_MODE) {\n }\n};\n\n/**\n * Safe console.warn that only logs in development or when debug=true\n */\nexport const debugWarn = (...args) => {\n if (DEBUG_MODE) {\n }\n};\n\n/**\n * Safe console.error - ALWAYS logs (errors should always be visible)\n */\nexport const debugError = (...args) => {\n};\n\n/**\n * Safe console.info that only logs in development or when debug=true\n */\nexport const debugInfo = (...args) => {\n if (DEBUG_MODE) {\n }\n};\n\n/**\n * Sanitize object for logging (remove sensitive data)\n */\nexport const sanitizeForLog = (obj) => {\n if (!obj || typeof obj !== 'object') return obj;\n\n const sanitized = { ...obj };\n const sensitiveKeys = [\n 'apiKey',\n 'apiSecret',\n 'api_key',\n 'api_secret',\n 'x-api-key',\n 'x-api-secret',\n 'authorization',\n 'password',\n 'privateKey',\n 'private_key',\n 'mnemonic',\n 'seed'\n ];\n\n // Remove sensitive keys\n sensitiveKeys.forEach(key => {\n if (sanitized[key]) {\n sanitized[key] = '[REDACTED]';\n }\n // Also check lowercase\n const lowerKey = key.toLowerCase();\n if (sanitized[lowerKey]) {\n sanitized[lowerKey] = '[REDACTED]';\n }\n });\n\n return sanitized;\n};\n\n/**\n * Log object safely (sanitizes sensitive data)\n */\nexport const debugLogObject = (label, obj) => {\n if (DEBUG_MODE) {\n }\n};\n\nexport default {\n DEBUG_MODE,\n debugLog,\n debugWarn,\n debugError,\n debugInfo,\n debugLogObject,\n sanitizeForLog\n};\n","import React, { useState, useEffect } from 'react';\nimport ModernDropdown from './ModernDropdown';\nimport { generateQRPaymentURI, generateMobilePaymentDeepLink } from '../utils/deepLinkUtils';\nimport { DEBUG_MODE, debugLog } from '../../../utils/debugUtils';\n\nconst MobileWalletDropdown = ({\n paymentData,\n selectedToken,\n selectedNetwork,\n config,\n onPaymentStarted = () => {},\n onError = () => {}\n}) => {\n const [selectedWallet, setSelectedWallet] = useState(null);\n const [loading, setLoading] = useState(false);\n const [debugLogs, setDebugLogs] = useState([]);\n const [showDebugPanel, setShowDebugPanel] = useState(false);\n const [dataCheckCount, setDataCheckCount] = useState(0);\n\n // Auto-check data completeness periodically\n useEffect(() => {\n const isComplete = paymentData?.id &&\n selectedToken?.contractAddress &&\n selectedNetwork?.chainId &&\n (paymentData?.contractCall?.contractAddress || paymentData?.contractAddress);\n\n if (!isComplete) {\n // Log what's missing for debugging\n addDebugLog('debug', '⏳ Waiting for complete payment data', {\n hasPaymentId: !!paymentData?.id,\n hasTokenContract: !!selectedToken?.contractAddress,\n hasChainId: !!selectedNetwork?.chainId,\n hasPaymentContract: !!(paymentData?.contractCall?.contractAddress || paymentData?.contractAddress),\n checkCount: dataCheckCount\n });\n\n // Increment check count\n setDataCheckCount(prev => prev + 1);\n } else {\n addDebugLog('success', '✅ Payment data complete', {\n paymentId: paymentData.id,\n tokenContract: selectedToken.contractAddress,\n chainId: selectedNetwork.chainId,\n paymentContract: paymentData?.contractCall?.contractAddress || paymentData?.contractAddress\n });\n }\n }, [paymentData, selectedToken, selectedNetwork, dataCheckCount]);\n\n // Helper function to add debug logs to UI\n const addDebugLog = (type, message, data = null) => {\n const timestamp = new Date().toLocaleTimeString();\n const logEntry = {\n id: Date.now() + Math.random(),\n type,\n message,\n data,\n timestamp\n };\n // Only store logs if debug mode is enabled\n if (DEBUG_MODE) {\n setDebugLogs(prev => [...prev, logEntry].slice(-20)); // Keep last 20 logs\n debugLog(`[${type.toUpperCase()}] ${message}`, data || '');\n }\n };\n\n // Mobile wallet options for dropdown - Only trusted wallets\n const mobileWallets = [\n {\n id: 'metamask',\n name: 'MetaMask',\n icon: '🦊',\n description: 'Connect with MetaMask mobile'\n },\n {\n id: 'trust',\n name: 'Trust Wallet',\n icon: '🛡️',\n description: 'Connect with Trust Wallet'\n },\n {\n id: 'coinbase',\n name: 'Coinbase Wallet',\n icon: '💙',\n description: 'Connect with Coinbase Wallet'\n }\n ];\n\n const handleWalletSelection = async (walletId) => {\n const wallet = mobileWallets.find(w => w.id === walletId);\n if (!wallet) return;\n\n setSelectedWallet(walletId);\n setLoading(true);\n\n try {\n addDebugLog('info', `🚀 Mobile wallet selected: ${wallet.name}`);\n\n if (!paymentData) {\n throw new Error('Payment data not available. Please create payment first.');\n }\n\n // 🔍 SIMPLE DATA CHECK - just log what we have\n addDebugLog('debug', '🔍 Payment Data Check', {\n hasPaymentData: !!paymentData,\n hasSelectedToken: !!selectedToken,\n hasSelectedNetwork: !!selectedNetwork,\n hasConfig: !!config,\n paymentId: paymentData?.id || paymentData?.splitterPaymentId,\n tokenAddress: selectedToken?.contractAddress,\n networkChainId: selectedNetwork?.chainId,\n amount: paymentData?.totalAmount || paymentData?.amount || config?.amount\n });\n\n // Generate payment URL - let the URL generation function handle all the logic\n const paymentUri = generateQRPaymentURI(\n paymentData,\n selectedToken,\n selectedNetwork,\n config,\n walletId\n );\n\n if (!paymentUri) {\n throw new Error('Failed to generate payment URL');\n }\n\n addDebugLog('success', '📱 Generated payment URL', {\n url: paymentUri,\n length: paymentUri.length\n });\n\n // Generate wallet-specific deep link\n const mobileDeepLink = generateMobilePaymentDeepLink(walletId, paymentUri);\n\n if (!mobileDeepLink) {\n throw new Error(`Failed to generate ${wallet.name} deep link`);\n }\n\n addDebugLog('success', `🔗 Deep link generated for ${wallet.name}`, {\n deepLink: mobileDeepLink\n });\n\n // Notify parent that payment was started\n onPaymentStarted({\n walletType: walletId,\n walletName: wallet.name,\n paymentUrl: paymentUri,\n deepLink: mobileDeepLink\n });\n\n // Simple redirect with minimal feedback\n setTimeout(() => {\n addDebugLog('info', `📱 Opening ${wallet.name}...`);\n window.location.href = mobileDeepLink;\n }, 500);\n\n } catch (error) {\n addDebugLog('error', `❌ Mobile wallet connection failed`, {\n error: error.message,\n walletId,\n hasPaymentData: !!paymentData,\n hasSelectedToken: !!selectedToken,\n hasSelectedNetwork: !!selectedNetwork\n });\n onError(error.message);\n setLoading(false);\n setSelectedWallet(null);\n }\n };\n\n // Render wallet option for dropdown\n const renderWalletOption = (wallet) => {\n return (\n <div className=\"flex items-center space-x-3\">\n <div className=\"w-8 h-8 flex items-center justify-center\">\n <div className=\"text-2xl\">{wallet.icon}</div>\n </div>\n <div className=\"flex-1\">\n <div className=\"font-semibold text-gray-800\">\n {wallet.name}\n {selectedWallet === wallet.id && loading && (\n <span className=\"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full animate-pulse\">\n Opening...\n </span>\n )}\n </div>\n <div className=\"text-sm text-gray-500\">\n {wallet.description}\n </div>\n </div>\n </div>\n );\n };\n\n if (!paymentData) {\n return (\n <div className=\"p-4 bg-amber-50 rounded-lg border border-amber-200\">\n <div className=\"text-center\">\n <div className=\"text-amber-800 font-medium mb-2\">⚠️ Payment Required</div>\n <div className=\"text-sm text-amber-700\">\n Please create a payment before selecting a wallet\n </div>\n </div>\n </div>\n );\n }\n\n // Check if payment data is fully loaded with all required fields\n const isPaymentDataComplete = paymentData?.id &&\n selectedToken?.contractAddress &&\n selectedNetwork?.chainId &&\n (paymentData?.contractCall?.contractAddress || paymentData?.contractAddress);\n\n return (\n <div className=\"space-y-4\">\n {/* Show loading state if payment data is incomplete */}\n {!isPaymentDataComplete ? (\n <div className=\"p-4 bg-amber-50 rounded-lg border border-amber-200\">\n <div className=\"text-center\">\n <div className=\"text-amber-800 font-medium mb-2\">⏳ Preparing Payment...</div>\n <div className=\"text-sm text-amber-700\">\n Payment is being prepared. Please wait a moment...\n </div>\n <div className=\"mt-3\">\n <div className=\"animate-spin rounded-full h-6 w-6 border-2 border-amber-600 border-t-transparent mx-auto\"></div>\n </div>\n </div>\n </div>\n ) : (\n <>\n {/* Wallet Selection Dropdown */}\n <div className=\"space-y-2\">\n <label className=\"block text-sm font-medium text-gray-700\" style={{ fontFamily: 'Bricolage Grotesque, sans-serif' }}>\n Select Mobile Wallet\n </label>\n\n <ModernDropdown\n options={mobileWallets}\n value={selectedWallet || ''}\n onChange={handleWalletSelection}\n placeholder=\"Choose your wallet...\"\n renderOption={renderWalletOption}\n getOptionKey={(wallet) => wallet.id}\n getOptionValue={(wallet) => wallet.id}\n getSearchableText={(wallet) => `${wallet.name} ${wallet.description}`}\n disabled={loading}\n />\n\n {/* Help text */}\n <div className=\"text-xs text-gray-500 mt-2\">\n Select a wallet to open it with your payment details\n </div>\n </div>\n\n {/* Status message when loading */}\n {loading && selectedWallet && (\n <div className=\"p-3 bg-blue-50 border border-blue-200 rounded-lg animate-pulse\">\n <div className=\"flex items-center space-x-2\">\n <div className=\"animate-spin rounded-full h-4 w-4 border-2 border-blue-600 border-t-transparent\"></div>\n <div className=\"text-sm text-blue-700\">\n Opening {mobileWallets.find(w => w.id === selectedWallet)?.name}...\n </div>\n </div>\n </div>\n )}\n\n {/* Payment Details Summary */}\n <div className=\"p-3 bg-gray-50 rounded-lg\">\n <div className=\"flex justify-between items-center text-sm\">\n <span className=\"text-gray-600\">Amount:</span>\n <span className=\"font-semibold text-gray-800\">\n {paymentData.totalAmount} {selectedToken?.symbol || 'USDC'}\n </span>\n </div>\n <div className=\"flex justify-between items-center text-sm mt-1\">\n <span className=\"text-gray-600\">Network:</span>\n <span className=\"text-gray-800\">{selectedNetwork?.name || 'Ethereum'}</span>\n </div>\n </div>\n\n {/* Mobile Info */}\n <div className=\"p-3 bg-purple-50 border border-purple-200 rounded-lg\">\n <div className=\"text-xs text-purple-700\">\n <div className=\"font-medium mb-1\">📱 Mobile Payment</div>\n <div>Your selected wallet app will open with payment details pre-filled</div>\n </div>\n </div>\n\n {/* Mobile Debug Panel - Only show in development mode */}\n {DEBUG_MODE && (\n <div className=\"mt-4\">\n <button\n onClick={() => setShowDebugPanel(!showDebugPanel)}\n className=\"w-full text-xs py-2 px-3 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition-colors\"\n >\n {showDebugPanel ? '🔽 Hide Debug Info' : '🔧 Show Debug Info'} ({debugLogs.length} logs)\n </button>\n\n {showDebugPanel && (\n <div className=\"mt-2 p-3 bg-gray-900 text-green-400 rounded-lg text-xs font-mono max-h-80 overflow-y-auto\">\n <div className=\"text-white mb-2 font-bold\">📱 Mobile Debug Panel</div>\n {debugLogs.length === 0 ? (\n <div className=\"text-gray-400\">No debug logs yet. Try selecting a wallet...</div>\n ) : (\n debugLogs.map(log => (\n <div key={log.id} className=\"mb-3 pb-2 border-b border-gray-700\">\n <div className=\"flex items-center justify-between mb-1\">\n <span className={`px-2 py-1 rounded text-xs font-bold ${\n log.type === 'error' ? 'bg-red-600 text-white' :\n log.type === 'success' ? 'bg-green-600 text-white' :\n log.type === 'debug' ? 'bg-blue-600 text-white' :\n 'bg-gray-600 text-white'\n }`}>\n {log.type.toUpperCase()}\n </span>\n <span className=\"text-gray-400\">{log.timestamp}</span>\n </div>\n <div className=\"text-yellow-300 mb-1\">{log.message}</div>\n {log.data && (\n <div className=\"text-gray-300 text-xs\">\n <details>\n <summary className=\"cursor-pointer text-blue-300 hover:text-blue-200\">\n 📊 Data\n </summary>\n <pre className=\"mt-1 p-2 bg-gray-800 rounded overflow-x-auto whitespace-pre-wrap\">\n {JSON.stringify(log.data, null, 2)}\n </pre>\n </details>\n </div>\n )}\n </div>\n ))\n )}\n <button\n onClick={() => setDebugLogs([])}\n className=\"mt-2 px-3 py-1 bg-red-600 text-white rounded text-xs hover:bg-red-700\"\n >\n Clear Logs\n </button>\n </div>\n )}\n </div>\n )}\n </>\n )}\n </div>\n );\n};\n\nexport default MobileWalletDropdown;","import React from 'react';\nimport { parseUserFriendlyError, getErrorSeverity, getErrorActionText } from '../utils/errorUtils';\n\nconst ErrorDisplay = ({\n error,\n onRetry,\n onDismiss,\n context = 'payment',\n className = ''\n}) => {\n if (!error) return null;\n\n const friendlyError = parseUserFriendlyError(error);\n const severity = getErrorSeverity(friendlyError.type);\n const actionText = getErrorActionText(friendlyError.type);\n\n // Color schemes based on severity\n const severityStyles = {\n info: {\n container: 'bg-blue-50 border-blue-200',\n title: 'text-blue-800',\n message: 'text-blue-700',\n icon: 'ℹ️',\n button: 'bg-blue-600 hover:bg-blue-700'\n },\n warning: {\n container: 'bg-amber-50 border-amber-200',\n title: 'text-amber-800',\n message: 'text-amber-700',\n icon: '⚠️',\n button: 'bg-amber-600 hover:bg-amber-700'\n },\n error: {\n container: 'bg-red-50 border-red-200',\n title: 'text-red-800',\n message: 'text-red-700',\n icon: '❌',\n button: 'bg-red-600 hover:bg-red-700'\n },\n critical: {\n container: 'bg-red-50 border-red-300',\n title: 'text-red-900',\n message: 'text-red-800',\n icon: '🚨',\n button: 'bg-red-700 hover:bg-red-800'\n }\n };\n\n const styles = severityStyles[severity] || severityStyles.error;\n\n return (\n <div className={`p-4 border rounded-lg ${styles.container} ${className}`}>\n <div className=\"flex items-start space-x-3\">\n {/* Icon */}\n <div className=\"flex-shrink-0 text-xl\">\n {styles.icon}\n </div>\n\n {/* Content */}\n <div className=\"flex-1 min-w-0\">\n <div className={`font-semibold ${styles.title} mb-1`}>\n {friendlyError.title}\n </div>\n <div className={`text-sm ${styles.message} mb-2`}>\n {friendlyError.message}\n </div>\n {friendlyError.suggestion && (\n <div className={`text-xs ${styles.message} opacity-90`}>\n 💡 {friendlyError.suggestion}\n </div>\n )}\n </div>\n\n {/* Dismiss button */}\n {onDismiss && (\n <button\n onClick={onDismiss}\n className={`flex-shrink-0 text-gray-400 hover:text-gray-600 transition-colors`}\n aria-label=\"Dismiss error\"\n >\n <svg className=\"w-4 h-4\" fill=\"currentColor\" viewBox=\"0 0 20 20\">\n <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 </svg>\n </button>\n )}\n </div>\n\n {/* Action buttons */}\n {onRetry && (\n <div className=\"mt-3 flex justify-end space-x-2\">\n {onDismiss && severity === 'info' && (\n <button\n onClick={onDismiss}\n className=\"px-3 py-1.5 text-xs text-gray-600 hover:text-gray-800 transition-colors\"\n >\n Cancel\n </button>\n )}\n <button\n onClick={onRetry}\n className={`px-4 py-2 text-sm font-medium text-white rounded-md transition-colors ${styles.button}`}\n >\n {actionText}\n </button>\n </div>\n )}\n\n {/* Debug info in development */}\n {process.env.NODE_ENV === 'development' && (\n <details className=\"mt-3 text-xs opacity-50\">\n <summary className=\"cursor-pointer\">Debug Info</summary>\n <pre className=\"mt-1 p-2 bg-gray-100 rounded text-xs overflow-x-auto\">\n {JSON.stringify({\n type: friendlyError.type,\n originalError: error?.message || error?.toString(),\n code: error?.code,\n severity\n }, null, 2)}\n </pre>\n </details>\n )}\n </div>\n );\n};\n\nexport default ErrorDisplay;","// Payment flow steps\nexport const PAYMENT_STEPS = {\n METHOD: 'method',\n CONFIRM: 'confirm',\n PROCESSING: 'processing',\n SUCCESS: 'success',\n ERROR: 'error'\n};\n\n// Payment types\nexport const PAYMENT_TYPES = {\n WALLET: 'wallet',\n QR: 'qr'\n};\n\n// Transaction steps for PaymentSplitter flow\nexport const TRANSACTION_STEPS = {\n IDLE: 'idle',\n APPROVE: 'approve',\n SPLIT_PAYMENT: 'splitPayment',\n PROCESSING: 'processing',\n SUCCESS: 'success',\n ERROR: 'error'\n};\n\n// Payment statuses\nexport const PAYMENT_STATUS = {\n PENDING: 'pending',\n PROCESSING: 'processing',\n CONFIRMING: 'confirming',\n SUCCESS: 'success',\n FAILED: 'failed',\n CANCELLED: 'cancelled',\n TIMEOUT: 'timeout',\n INSUFFICIENT_FUNDS: 'insufficient_funds',\n NETWORK_ERROR: 'network_error',\n USER_REJECTED: 'user_rejected'\n};\n\n// Supported networks for EVM compatibility\nexport const SUPPORTED_NETWORKS = [\n 'ethereum',\n 'bsc',\n 'polygon',\n 'arbitrum',\n 'optimism',\n 'avalanche',\n 'celo',\n 'base'\n];\n\n// Supported stablecoins\nexport const SUPPORTED_TOKENS = ['USDC', 'USDT'];\n\n// Error codes for better error handling\nexport const ERROR_CODES = {\n USER_REJECTED: 4001,\n UNAUTHORIZED: 4100,\n UNSUPPORTED_METHOD: 4200,\n DISCONNECTED: 4900,\n CHAIN_DISCONNECTED: 4901,\n INSUFFICIENT_FUNDS: -32000,\n INVALID_PARAMS: -32602,\n INTERNAL_ERROR: -32603\n};\n\n// Timeouts and delays\nexport const TIMEOUTS = {\n TRANSACTION_TIMEOUT: 30000, // 30 seconds\n NETWORK_SWITCH_DELAY: 1000, // 1 second\n APPROVE_DELAY: 3000, // 3 seconds\n RETRY_DELAY: 2000, // 2 seconds\n APP_OPEN_TIMEOUT: 3000 // 3 seconds\n};\n\n// QR Code configuration\nexport const QR_CONFIG = {\n WIDTH_MOBILE: 300,\n WIDTH_DESKTOP: 200,\n MARGIN: 2,\n ERROR_CORRECTION_LEVEL: 'M' // 15% error correction\n};\n\n// Font family for consistent styling\nexport const FONT_FAMILY = 'Bricolage Grotesque, sans-serif';\n\n// Color scheme\nexport const COLORS = {\n PRIMARY: '#7042D2',\n PRIMARY_HOVER: '#5b34b1',\n PRIMARY_LIGHT: '#7042D2',\n SUCCESS: '#10B981',\n ERROR: '#EF4444',\n WARNING: '#F59E0B',\n INFO: '#3B82F6',\n GRAY: {\n 50: '#F9FAFB',\n 100: '#F3F4F6',\n 200: '#E5E7EB',\n 300: '#D1D5DB',\n 400: '#9CA3AF',\n 500: '#6B7280',\n 600: '#4B5563',\n 700: '#374151',\n 800: '#1F2937',\n 900: '#111827'\n }\n};\n\n// Validation patterns\nexport const VALIDATION = {\n EMAIL_REGEX: /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/,\n ETHEREUM_ADDRESS_REGEX: /^0x[a-fA-F0-9]{40}$/,\n TRANSACTION_HASH_REGEX: /^0x[a-fA-F0-9]{64}$/,\n MIN_AMOUNT: 0.01,\n MAX_AMOUNT: 1000000\n};\n\n// API endpoints\nexport const API_ENDPOINTS = {\n NETWORKS: '/api/networks',\n TOKENS: '/api/networks/stablecoins',\n CREATE_PAYMENT: '/api/payments/create',\n VERIFY_QR: '/api/payments/verify-qr',\n PROCESS_PAYMENT: '/api/payments/process',\n FAIL_PAYMENT: '/api/payments/fail',\n CONTRACT_INFO: '/api/payments/contract'\n};\n\n// Mobile user agent patterns\nexport const MOBILE_PATTERNS = [\n /Android/i,\n /webOS/i,\n /iPhone/i,\n /iPad/i,\n /iPod/i,\n /BlackBerry/i,\n /Windows Phone/i\n];\n\n// Default fallback data for when API fails\nexport const FALLBACK_NETWORKS = [\n { id: '1', name: 'Ethereum', shortName: 'ethereum', chainId: '0x1', type: 'ethereum' },\n { id: '56', name: 'BSC', shortName: 'bsc', chainId: '0x38', type: 'bsc' },\n { id: '137', name: 'Polygon', shortName: 'polygon', chainId: '0x89', type: 'polygon' },\n { id: '42161', name: 'Arbitrum', shortName: 'arbitrum', chainId: '0xa4b1', type: 'arbitrum' },\n { id: '10', name: 'Optimism', shortName: 'optimism', chainId: '0xa', type: 'optimism' },\n { id: '43114', name: 'Avalanche', shortName: 'avalanche', chainId: '0xa86a', type: 'avalanche' },\n { id: '42220', name: 'Celo', shortName: 'celo', chainId: '0xa4ec', type: 'celo' },\n { id: '8453', name: 'Base', shortName: 'base', chainId: '0x2105', type: 'base' }\n];\n\n// Browser extension detection\nexport const WALLET_DETECTION = {\n metamask: () => window.ethereum && window.ethereum.isMetaMask === true,\n trust: () => window.ethereum && window.ethereum.isTrust === true,\n coinbase: () => window.ethereum && window.ethereum.isCoinbaseWallet === true,\n injected: () => window.ethereum && !window.ethereum.isMetaMask && !window.ethereum.isCoinbaseWallet\n};\n\n// Deep link schemes\nexport const DEEP_LINK_SCHEMES = {\n EIP681: 'ethereum:',\n TRUST_WALLET: 'https://link.trustwallet.com/send',\n METAMASK: 'https://metamask.app.link/send'\n};\n\n// Payment processing retry configuration\nexport const RETRY_CONFIG = {\n MAX_RETRIES: 3,\n RETRY_DELAY: 8000, // 8 seconds\n EXPONENTIAL_BACKOFF: true\n};\n\n// Network specific configurations\nexport const NETWORK_CONFIG = {\n ethereum: {\n gasMultiplier: 1.2,\n confirmationBlocks: 3\n },\n arbitrum: {\n gasMultiplier: 1.0,\n confirmationBlocks: 1,\n hasJsonRpcIssues: true,\n maxRetries: 2\n },\n polygon: {\n gasMultiplier: 1.5,\n confirmationBlocks: 10\n },\n bsc: {\n gasMultiplier: 1.1,\n confirmationBlocks: 3\n },\n optimism: {\n gasMultiplier: 1.0,\n confirmationBlocks: 1\n },\n avalanche: {\n gasMultiplier: 1.3,\n confirmationBlocks: 3,\n syncDelay: 2500\n },\n celo: {\n gasMultiplier: 1.0,\n confirmationBlocks: 1\n },\n base: {\n gasMultiplier: 1.0,\n confirmationBlocks: 1\n }\n};","import React, { useEffect, useState } from 'react';\nimport { WagmiProvider } from 'wagmi';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\n\n// Modular imports\nimport { wagmiConfig } from './enhanced-payment/config/wagmiConfig';\nimport { usePaymentFlow } from './enhanced-payment/hooks/usePaymentFlow';\nimport { useWalletConnection } from './enhanced-payment/hooks/useWalletConnection';\nimport { useTransactionHandling } from './enhanced-payment/hooks/useTransactionHandling';\nimport ModernDropdown from './enhanced-payment/components/ModernDropdown';\nimport ScreenTransition from './enhanced-payment/components/ScreenTransition';\nimport PaymentStatus from './enhanced-payment/components/PaymentStatus';\nimport QRCodeDisplay from './enhanced-payment/components/QRCodeDisplay';\nimport WalletSelector from './enhanced-payment/components/WalletSelector';\nimport MobilePaymentButtons from './enhanced-payment/components/MobilePaymentButtons';\nimport MobileWalletDropdown from './enhanced-payment/components/MobileWalletDropdown';\nimport ErrorDisplay from './enhanced-payment/components/ErrorDisplay';\nimport { detectMobile } from './enhanced-payment/utils/walletUtils';\nimport {\n getNetworkLogoUrl,\n getTokenLogoUrl\n} from './enhanced-payment/config/logoConfig';\nimport { formatAmount } from './enhanced-payment/utils/formatUtils';\nimport { PAYMENT_STEPS, PAYMENT_TYPES, FONT_FAMILY } from './enhanced-payment/constants';\nimport logo from \"../assets/Logomark.png\";\n\n// Create Query Client for Wagmi\nconst queryClient = new QueryClient();\n\n// Internal component that uses Wagmi hooks\nconst EnhancedSimpleCoinleyPaymentInternal = ({\n publicKey, // New: Single public key for authentication (recommended)\n apiKey, // Legacy: API key (used with apiSecret)\n apiSecret, // Legacy: API secret (used with apiKey)\n apiUrl,\n config,\n onSuccess,\n onError,\n onClose,\n isOpen,\n theme = 'light'\n}) => {\n // Use our custom hooks for state management\n // Pass publicKey if available, otherwise fall back to legacy apiKey+apiSecret\n const paymentFlow = usePaymentFlow(apiUrl, publicKey || apiKey, publicKey ? null : apiSecret);\n const walletConnection = useWalletConnection();\n\n // State for QR code wallet preference\n const [qrWalletPreference, setQrWalletPreference] = useState('metamask');\n\n // Auto-detect mobile device\n const [isMobile, setIsMobile] = useState(false);\n\n // State for mobile payment verification - persist across page reloads\n const [mobilePaymentStarted, setMobilePaymentStarted] = useState(() => {\n // Check if user already started a mobile payment\n if (typeof window !== 'undefined' && window.sessionStorage) {\n return sessionStorage.getItem('coinley_mobile_payment_started') === 'true';\n }\n return false;\n });\n const [verifyingPayment, setVerifyingPayment] = useState(false);\n\n useEffect(() => {\n setIsMobile(detectMobile());\n }, []);\n\n const {\n currentStep,\n networks,\n tokens,\n selectedNetwork,\n selectedToken,\n paymentData,\n loading,\n error,\n paymentType,\n loadData,\n createPayment,\n failPayment,\n resetState,\n setSelectedNetwork,\n setSelectedToken,\n setPaymentType,\n setCurrentStep,\n setError\n } = paymentFlow;\n\n const {\n connectedWallet,\n address,\n connectWallet,\n handleWalletSelection\n } = walletConnection;\n\n // Use transaction handling hook\n const transactionHandling = useTransactionHandling(\n paymentData,\n selectedToken,\n selectedNetwork,\n address,\n paymentFlow.api,\n walletConnection\n );\n\n const {\n executePaymentTransaction,\n processFinalPayment,\n transactionStep,\n transactionError,\n currentTransactionHash\n } = transactionHandling;\n\n // Clear mobile payment started flag on success\n useEffect(() => {\n if (currentStep === PAYMENT_STEPS.SUCCESS && typeof window !== 'undefined' && window.sessionStorage) {\n sessionStorage.removeItem('coinley_mobile_payment_started');\n }\n }, [currentStep]);\n\n useEffect(() => {\n if (isOpen) {\n loadData();\n resetState();\n\n // Lock body scroll when modal is open\n const scrollY = window.scrollY;\n document.body.style.position = 'fixed';\n document.body.style.top = `-${scrollY}px`;\n document.body.style.width = '100%';\n document.body.style.overflow = 'hidden';\n } else {\n // Unlock body scroll when modal closes\n const scrollY = document.body.style.top;\n document.body.style.position = '';\n document.body.style.top = '';\n document.body.style.width = '';\n document.body.style.overflow = '';\n window.scrollTo(0, parseInt(scrollY || '0') * -1);\n }\n\n return () => {\n // Cleanup on unmount\n if (isOpen) {\n const scrollY = document.body.style.top;\n document.body.style.position = '';\n document.body.style.top = '';\n document.body.style.width = '';\n document.body.style.overflow = '';\n window.scrollTo(0, parseInt(scrollY || '0') * -1);\n }\n };\n }, [isOpen]);\n\n // Monitor transaction steps and handle timeouts\n useEffect(() => {\n if (transactionStep === 'processing' || transactionStep === 'approve' || transactionStep === 'splitPayment') {\n // Set a timeout to reset if transaction takes too long\n const timeout = setTimeout(() => {\n setError('Transaction timed out. Please try again.');\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n transactionHandling.resetTransaction();\n }, 120000); // 2 minutes timeout\n\n return () => clearTimeout(timeout);\n }\n }, [transactionStep]);\n\n // Handle payment cancellation\n const handleCancel = async () => {\n await failPayment();\n onClose();\n };\n\n // Handle wallet connection\n const handleConnect = async (connector) => {\n const success = await connectWallet(connector, selectedNetwork);\n if (success && onSuccess) {\n }\n };\n\n // Get wallet address for the selected network\n const getWalletAddressForNetwork = () => {\n if (!selectedNetwork) return null;\n\n // First check config for merchant wallet addresses\n const networkAddress = config?.merchantWalletAddresses?.[selectedNetwork.shortName];\n if (networkAddress) return networkAddress;\n\n // Then check paymentData\n if (paymentData?.recipientWallet) return paymentData.recipientWallet;\n if (paymentData?.merchantWalletAddress) return paymentData.merchantWalletAddress;\n\n return null;\n };\n\n // Render network option for dropdown\n const renderNetworkOption = (network) => {\n // Pass full network object to get logo from API data\n const networkLogoUrl = getNetworkLogoUrl(network);\n\n return (\n <div className=\"flex items-center space-x-3\">\n {networkLogoUrl ? (\n <img\n src={networkLogoUrl}\n alt={network.name}\n className=\"w-8 h-8 rounded-full\"\n onError={(e) => {\n e.target.style.display = 'none';\n e.target.nextSibling.style.display = 'flex';\n }}\n />\n ) : null}\n <div\n className=\"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center\"\n style={{ display: networkLogoUrl ? 'none' : 'flex' }}\n >\n <span className=\"text-xs font-bold text-gray-600\">{network.shortName?.slice(0, 2).toUpperCase()}</span>\n </div>\n <div>\n <div className=\"font-semibold text-gray-800\">{network.name}</div>\n <div className=\"text-sm text-gray-500\">{network.shortName?.toUpperCase()}</div>\n </div>\n </div>\n );\n };\n\n // Render token option for dropdown\n const renderTokenOption = (token) => {\n const tokenLogoUrl = getTokenLogoUrl(token.symbol);\n\n return (\n <div className=\"flex items-center space-x-3\">\n {tokenLogoUrl ? (\n <img\n src={tokenLogoUrl}\n alt={token.symbol}\n className=\"w-8 h-8 rounded-full\"\n onError={(e) => {\n e.target.style.display = 'none';\n e.target.nextSibling.style.display = 'flex';\n }}\n />\n ) : null}\n <div\n className=\"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center\"\n style={{ display: tokenLogoUrl ? 'none' : 'flex' }}\n >\n <span className=\"text-xs font-bold text-gray-600\">{token.symbol?.slice(0, 2)}</span>\n </div>\n <div>\n <div className=\"font-semibold text-gray-800\">{token.name} ({token.symbol})</div>\n <div className=\"text-sm text-gray-500\">\n {token.Network?.name || 'Unknown Network'}\n {token.isStablecoin && <span className=\"ml-2 text-green-600\">• Stablecoin</span>}\n </div>\n </div>\n </div>\n );\n };\n\n if (!isOpen) return null;\n\n return (\n <div className=\"fixed inset-0 z-50\">\n <div className=\"fixed inset-0 bg-black bg-opacity-50 transition-opacity\" onClick={handleCancel} aria-hidden=\"true\" />\n <div className=\"fixed inset-0 flex items-center justify-center p-4\" style={{ zIndex: 51 }}>\n <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 }}>\n\n {/* Modern Header with Logo - FIXED HEIGHT */}\n <div className=\"flex-shrink-0 bg-white flex justify-between items-center mb-3 mr-3 ml-3 py-3 px-2 rounded-full\">\n <div className=\"flex-1 flex items-center gap-2 px-4\">\n <div className=\"w-7 h-7 rounded-full flex items-center justify-center\">\n <img src={logo} alt=\"Coinley\" />\n </div>\n <span className=\"text-base font-semibold text-gray-800\" style={{ fontFamily: FONT_FAMILY }}>Payment Details</span>\n </div>\n {currentStep !== PAYMENT_STEPS.SUCCESS && currentStep !== PAYMENT_STEPS.PROCESSING && (\n <button\n onClick={handleCancel}\n className=\"text-gray-500 hover:text-gray-700 focus:outline-none\"\n >\n <svg xmlns=\"http://www.w3.org/2000/svg\" className=\"h-5 w-5 mr-2\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M6 18L18 6M6 6l12 12\" />\n </svg>\n </button>\n )}\n </div>\n\n {/* Payment Summary - COMPACT */}\n {config && currentStep !== PAYMENT_STEPS.SUCCESS && (\n <div className=\"flex-shrink-0 mb-3 px-4\">\n <div className=\"text-center\">\n <div className=\"text-xs text-gray-600\">Total Amount</div>\n <div className=\"text-3xl font-bold text-[#7042D2] mt-1 leading-tight tracking-tight\" style={{ fontFamily: FONT_FAMILY }}>\n ${formatAmount(config.amount)}\n </div>\n <div className=\"mt-1 text-xs text-gray-500\">No additional fees</div>\n <div className=\"text-xs text-gray-600 mt-2\">Payment to:</div>\n <div className=\"text-sm font-semibold mt-0.5 flex gap-1.5 items-center justify-center\" style={{ fontFamily: FONT_FAMILY }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <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\" />\n </svg>\n {config.merchantName || 'Merchant'}\n </div>\n </div>\n </div>\n )}\n\n {/* Main Content Area - SCROLLABLE */}\n <div className=\"flex-1 overflow-y-auto overscroll-contain\">\n\n {/* Step 1: Select Network & Token */}\n <ScreenTransition currentStep={currentStep} targetStep={PAYMENT_STEPS.METHOD}>\n <div className=\"pb-4 pt-3 px-5 bg-white rounded-t-2xl\">\n <h3 className=\"font-semibold text-center mb-3 text-sm\" style={{ fontFamily: FONT_FAMILY }}>Choose Payment Method</h3>\n\n {/* Network Selection */}\n <div className=\"space-y-3 mb-4\">\n <label className=\"block text-sm font-medium text-gray-700\" style={{ fontFamily: FONT_FAMILY }}>Select Network</label>\n <ModernDropdown\n options={networks}\n value={selectedNetwork?.id || ''}\n onChange={(networkId) => {\n const network = networks.find(n => n.id === networkId);\n setSelectedNetwork(network);\n setSelectedToken(null);\n }}\n placeholder=\"Choose your network...\"\n renderOption={renderNetworkOption}\n getOptionKey={(network) => network.id}\n getOptionValue={(network) => network.id}\n getSearchableText={(network) => `${network.name} ${network.shortName}`}\n disabled={loading}\n />\n </div>\n\n {/* Token Selection */}\n {selectedNetwork && (\n <div className=\"space-y-3 mb-4\">\n <label className=\"block text-sm font-medium text-gray-700\" style={{ fontFamily: FONT_FAMILY }}>Select Token</label>\n <ModernDropdown\n options={tokens.filter(token =>\n token.Network?.shortName === selectedNetwork?.shortName ||\n token.networkId === selectedNetwork?.id\n )}\n value={selectedToken?.id || ''}\n onChange={(tokenId) => {\n const token = tokens\n .filter(token =>\n token.Network?.shortName === selectedNetwork?.shortName ||\n token.networkId === selectedNetwork?.id\n )\n .find(t => t.id === tokenId);\n setSelectedToken(token);\n }}\n placeholder=\"Choose your token...\"\n renderOption={renderTokenOption}\n getOptionKey={(token) => token.id}\n getOptionValue={(token) => token.id}\n getSearchableText={(token) => `${token.name} ${token.symbol}`}\n disabled={loading}\n />\n </div>\n )}\n\n {/* Continue Button */}\n {selectedNetwork && selectedToken && (\n <button\n onClick={() => createPayment(config)}\n disabled={loading}\n 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\"\n style={{ fontFamily: FONT_FAMILY }}\n >\n {loading ? 'Creating Payment...' : 'Continue'}\n </button>\n )}\n </div>\n </ScreenTransition>\n\n {/* Step 2: Confirm Payment */}\n <ScreenTransition currentStep={currentStep} targetStep={PAYMENT_STEPS.CONFIRM}>\n {selectedNetwork && selectedToken && paymentData && (\n <div className=\"pb-4 pt-4 px-4 bg-white rounded-t-2xl\">\n {/* Payment Method Tabs - Only show tabs on desktop */}\n {!isMobile && (\n <div className=\"mb-4\">\n <div className=\"flex border-b border-gray-200\">\n <button\n onClick={() => setPaymentType(PAYMENT_TYPES.WALLET)}\n className={`py-3 px-6 text-sm font-semibold transition-all duration-200 ${paymentType === PAYMENT_TYPES.WALLET\n ? 'border-b-2 border-[#7042D2] text-[#7042D2]'\n : 'text-gray-500 hover:text-gray-700'\n }`}\n style={{ fontFamily: FONT_FAMILY }}\n >\n Connect Wallet\n </button>\n <button\n onClick={() => setPaymentType(PAYMENT_TYPES.QR)}\n className={`py-3 px-6 text-sm font-semibold transition-all duration-200 ${paymentType === PAYMENT_TYPES.QR\n ? 'border-b-2 border-[#7042D2] text-[#7042D2]'\n : 'text-gray-500 hover:text-gray-700'\n }`}\n style={{ fontFamily: FONT_FAMILY }}\n >\n QR Code\n </button>\n </div>\n </div>\n )}\n\n {/* AUTO-SELECT: Show mobile dropdown on mobile, extension wallet on desktop */}\n {isMobile ? (\n // Mobile: Show dropdown with deep link wallets\n <MobileWalletDropdown\n paymentData={paymentData}\n selectedToken={selectedToken}\n selectedNetwork={selectedNetwork}\n config={config}\n onPaymentStarted={(details) => {\n setMobilePaymentStarted(true);\n if (typeof window !== 'undefined' && window.sessionStorage) {\n sessionStorage.setItem('coinley_mobile_payment_started', 'true');\n }\n // Optional: Show a success message or track event\n if (details.walletName) {\n }\n }}\n onError={(error) => {\n setError(error);\n }}\n />\n ) : (\n // Desktop: Show extension wallet or QR based on tab\n paymentType === PAYMENT_TYPES.WALLET ? (\n <WalletSelector\n selectedNetwork={selectedNetwork}\n onWalletSelect={handleWalletSelection}\n onConnect={handleConnect}\n connectedWallet={connectedWallet}\n loading={loading}\n />\n ) : null\n )}\n\n {/* QR Code Display */}\n {paymentType === PAYMENT_TYPES.QR && (\n <>\n {/* ✅ ULTRA-COMPACT: Horizontal wallet pills instead of dropdown */}\n <div className=\"mb-2\">\n <div className=\"text-xs font-medium text-gray-600 mb-1.5 text-center\" style={{ fontFamily: FONT_FAMILY }}>\n Optimize QR for:\n </div>\n <div className=\"flex gap-1.5 justify-center flex-wrap\">\n {[\n { id: 'metamask', name: 'MetaMask', icon: '🦊' },\n { id: 'trust', name: 'Trust', icon: '🛡️' },\n { id: 'coinbase', name: 'Coinbase', icon: '💙' }\n ].map((wallet) => (\n <button\n key={wallet.id}\n onClick={() => setQrWalletPreference(wallet.id)}\n className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all duration-200 ${\n qrWalletPreference === wallet.id\n ? 'bg-[#7042D2] text-white shadow-md'\n : 'bg-gray-100 text-gray-700 hover:bg-gray-200'\n }`}\n style={{ fontFamily: FONT_FAMILY }}\n >\n <span className=\"text-sm\">{wallet.icon}</span>\n <span>{wallet.name}</span>\n </button>\n ))}\n </div>\n </div>\n\n <QRCodeDisplay\n amount={paymentData?.totalAmount || paymentData?.amount || config?.amount}\n currency={selectedToken?.symbol}\n network={selectedNetwork?.shortName}\n theme={theme}\n paymentData={paymentData}\n config={config}\n selectedToken={selectedToken}\n selectedNetwork={selectedNetwork}\n preferredWallet={qrWalletPreference}\n compact={true}\n />\n </>\n )}\n\n {/* Error Display */}\n {(error || transactionError) && (\n <div className=\"mt-4\">\n <ErrorDisplay\n error={transactionError || error}\n onRetry={() => {\n setError('');\n transactionHandling.resetTransaction();\n // Retry the current step\n if (transactionStep === 'error' && connectedWallet) {\n executePaymentTransaction();\n }\n }}\n onDismiss={() => {\n setError('');\n transactionHandling.resetTransaction();\n }}\n context=\"payment\"\n />\n </div>\n )}\n\n {/* Action Buttons - ✅ COMPACT */}\n <div className=\"grid grid-cols-2 gap-2 mt-4\">\n <button\n type=\"button\"\n onClick={() => setCurrentStep(PAYMENT_STEPS.METHOD)}\n 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\"\n style={{ fontFamily: FONT_FAMILY }}\n >\n Back\n </button>\n <button\n type=\"button\"\n onClick={async () => {\n // For mobile deep link payments, verify payment on blockchain\n if (isMobile && mobilePaymentStarted) {\n if (!paymentData?.id) {\n setError('Payment ID not found. Please refresh and try again.');\n return;\n }\n\n try {\n setVerifyingPayment(true);\n setCurrentStep(PAYMENT_STEPS.PROCESSING);\n setError('');\n\n\n // First check if backend already knows about completed payment\n const statusResult = await paymentFlow.api.checkPaymentStatus(paymentData.id);\n\n if (statusResult.payment?.status === 'completed') {\n setCurrentStep(PAYMENT_STEPS.SUCCESS);\n if (onSuccess) {\n onSuccess({\n paymentId: paymentData.id,\n transactionHash: statusResult.payment.transactionHash,\n paymentDetails: statusResult.payment\n });\n }\n } else if (statusResult.payment?.status === 'pending') {\n // Payment exists but not completed yet - try blockchain verification\n\n const verificationResult = await paymentFlow.api.verifyQRPayment(paymentData.id);\n\n if (verificationResult.success && verificationResult.verified) {\n setCurrentStep(PAYMENT_STEPS.SUCCESS);\n if (onSuccess) {\n onSuccess({\n paymentId: paymentData.id,\n transactionHash: verificationResult.onChainData?.transactionHash,\n paymentDetails: verificationResult.payment\n });\n }\n } else {\n // Payment not yet confirmed on blockchain\n const message = verificationResult.message || 'Payment not yet confirmed on blockchain';\n setError(`${message}. Please complete the payment in your wallet and try again.`);\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n }\n } else if (statusResult.payment?.status === 'failed') {\n setError('Payment failed. Please try creating a new payment.');\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n } else {\n setError('Payment not found. Please verify the payment ID and try again.');\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n }\n } catch (error) {\n setError(`Verification failed: ${error.message}. Please ensure payment was completed and try again.`);\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n } finally {\n setVerifyingPayment(false);\n }\n return;\n }\n\n // For QR code, verify payment on blockchain\n if (paymentType === PAYMENT_TYPES.QR) {\n if (!paymentData?.id) {\n setError('Payment ID not found. Please refresh and try again.');\n return;\n }\n\n try {\n setCurrentStep(PAYMENT_STEPS.PROCESSING);\n setError('');\n\n\n // First check if backend already knows about completed payment\n const statusResult = await paymentFlow.api.checkPaymentStatus(paymentData.id);\n\n if (statusResult.payment?.status === 'completed') {\n setCurrentStep(PAYMENT_STEPS.SUCCESS);\n if (onSuccess) {\n onSuccess({\n paymentId: paymentData.id,\n transactionHash: statusResult.payment.transactionHash,\n paymentDetails: statusResult.payment\n });\n }\n } else if (statusResult.payment?.status === 'pending') {\n // Payment exists but not completed yet - try blockchain verification\n\n const verificationResult = await paymentFlow.api.verifyQRPayment(paymentData.id);\n\n if (verificationResult.success && verificationResult.verified) {\n setCurrentStep(PAYMENT_STEPS.SUCCESS);\n if (onSuccess) {\n onSuccess({\n paymentId: paymentData.id,\n transactionHash: verificationResult.onChainData?.transactionHash,\n paymentDetails: verificationResult.payment\n });\n }\n } else {\n // Payment not yet confirmed on blockchain\n const message = verificationResult.message || 'Payment not yet confirmed on blockchain';\n setError(`${message}. Please complete the payment and try again.`);\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n }\n } else if (statusResult.payment?.status === 'failed') {\n setError('Payment failed. Please try creating a new payment.');\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n } else {\n setError('Payment not found. Please verify the payment ID and try again.');\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n }\n } catch (error) {\n setError(`Verification failed: ${error.message}. Please ensure payment was completed and try again.`);\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n }\n return;\n } else if (connectedWallet && address) {\n // Handle wallet transaction\n try {\n setCurrentStep(PAYMENT_STEPS.PROCESSING);\n setError('');\n\n // Execute the payment transaction (handles backend notification internally)\n const txHash = await executePaymentTransaction();\n\n if (txHash) {\n // ✅ FIX: Clear any previous errors before success\n setError('');\n transactionHandling.setTransactionError('');\n\n // Payment processed successfully, show success screen\n setCurrentStep(PAYMENT_STEPS.SUCCESS);\n\n\n if (onSuccess) {\n // ✅ FIX: Ensure callback is called even on retry\n onSuccess({\n paymentId: paymentData.id,\n transactionHash: txHash,\n paymentDetails: paymentData\n });\n }\n }\n } catch (error) {\n\n // ✅ FIX: Clear previous success state to allow retry\n setCurrentStep(PAYMENT_STEPS.CONFIRM);\n\n // Check if user rejected the transaction\n if (error.message?.includes('User rejected') ||\n error.message?.includes('User denied') ||\n error.code === 4001 ||\n error.code === 'ACTION_REJECTED') {\n setError('Transaction was cancelled by user. Please try again.');\n } else {\n setError(error.message || 'Transaction failed. Please try again.');\n }\n\n // Reset transaction state\n transactionHandling.resetTransaction();\n\n // ✅ FIX: Don't call onError on first failure to allow retry\n // Only log the error, don't close the modal\n }\n }\n }}\n 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\"\n disabled={(paymentType === PAYMENT_TYPES.WALLET && !connectedWallet && !isMobile) ||\n (isMobile && !mobilePaymentStarted) ||\n transactionStep === 'processing' ||\n verifyingPayment}\n style={{ fontFamily: FONT_FAMILY }}\n >\n {verifyingPayment ? 'Verifying...' :\n transactionStep === 'processing' ? 'Processing...' :\n isMobile && mobilePaymentStarted ? 'I Have Paid' :\n isMobile ? 'Select Wallet' :\n paymentType === PAYMENT_TYPES.QR ? 'I Have Paid' :\n 'Pay Now'}\n </button>\n </div>\n </div>\n )}\n </ScreenTransition>\n\n {/* Processing Screen */}\n <ScreenTransition currentStep={currentStep} targetStep={PAYMENT_STEPS.PROCESSING}>\n <PaymentStatus\n status=\"processing\"\n message={\n transactionStep === 'approve' ? \"Approving token spending...\" :\n transactionStep === 'splitPayment' ? \"Processing payment split...\" :\n currentTransactionHash ? \"Confirming transaction on blockchain...\" :\n \"Processing your payment...\"\n }\n theme={theme}\n transactionHash={currentTransactionHash}\n selectedNetwork={selectedNetwork}\n />\n </ScreenTransition>\n\n {/* Success Screen */}\n <ScreenTransition currentStep={currentStep} targetStep={PAYMENT_STEPS.SUCCESS}>\n <PaymentStatus\n status=\"success\"\n message=\"Payment completed successfully!\"\n theme={theme}\n payment={paymentData}\n transactionHash={currentTransactionHash || paymentData?.transactionHash}\n selectedPaymentMethod={selectedToken}\n selectedNetwork={selectedNetwork}\n merchantName={config?.merchantName || 'Merchant'}\n onClose={onClose}\n />\n </ScreenTransition>\n\n {/* Error Display */}\n {(error || transactionError) && (\n <div className=\"p-4 bg-red-50 border border-red-200 rounded-lg mx-6 mb-4\">\n <p className=\"text-red-800 text-sm\">{error || transactionError}</p>\n <button\n onClick={() => {\n setError('');\n transactionHandling.setTransactionError('');\n }}\n className=\"mt-2 text-red-600 hover:text-red-800 text-xs underline\"\n >\n Dismiss\n </button>\n </div>\n )}\n </div>\n\n {/* Enhanced Footer */}\n {currentStep !== PAYMENT_STEPS.SUCCESS && (\n <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: FONT_FAMILY }}>\n <p>Powered by <span className='text-[#7042D2] font-semibold'>Coinley</span> - Multi-Wallet Support</p>\n <svg className=\"inline w-4 h-4 text-green-500 ml-1\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" viewBox=\"0 0 24 24\">\n <circle cx=\"12\" cy=\"12\" r=\"10\" stroke=\"currentColor\" strokeWidth=\"2\" fill=\"none\" />\n <path d=\"M9 12l2 2 4-4\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n </div>\n )}\n </div>\n </div>\n </div>\n );\n};\n\n// Main export with Wagmi provider wrapper\nconst EnhancedSimpleCoinleyPayment = (props) => {\n return (\n <WagmiProvider config={wagmiConfig}>\n <QueryClientProvider client={queryClient}>\n <EnhancedSimpleCoinleyPaymentInternal {...props} />\n </QueryClientProvider>\n </WagmiProvider>\n );\n};\n\nexport default EnhancedSimpleCoinleyPayment;","//src/CoinleyProvider.jsx - coinley-test\nimport React, { createContext, useContext, useRef, forwardRef, useImperativeHandle } from 'react';\n// import CoinleyPayment from './CoinleyPayment';\nimport CoinleyPayment from './components/EnhancedSimpleCoinleyPayment';\n\nconst CoinleyContext = createContext(null);\n\n// CoinleyProvider supports both new publicKey auth and legacy apiKey+apiSecret auth\n// New usage: <CoinleyProvider publicKey=\"pk_xxx\" apiUrl=\"...\" />\n// Legacy usage: <CoinleyProvider apiKey=\"xxx\" apiSecret=\"xxx\" apiUrl=\"...\" />\nexport const CoinleyProvider = ({\n publicKey, // New: Single public key for authentication (recommended)\n apiKey, // Legacy: API key (used with apiSecret)\n apiSecret, // Legacy: API secret (used with apiKey)\n apiUrl,\n theme = 'light',\n debug = false,\n children\n}) => {\n const [isOpen, setIsOpen] = React.useState(false);\n const [paymentConfig, setPaymentConfig] = React.useState(null);\n const [callbacks, setCallbacks] = React.useState({});\n const [merchantName, setMerchantName] = React.useState('');\n\n const openPayment = (config, checkoutCallbacks) => {\n setPaymentConfig(config);\n if (checkoutCallbacks) {\n setCallbacks(checkoutCallbacks);\n }\n setIsOpen(true);\n };\n\n const closePayment = () => {\n setIsOpen(false);\n setPaymentConfig(null);\n if (callbacks.onClose) {\n callbacks.onClose();\n }\n };\n\n const contextValue = {\n openPayment,\n closePayment\n };\n\n return (\n <CoinleyContext.Provider value={contextValue}>\n {children}\n {isOpen && paymentConfig && (\n <CoinleyPayment\n publicKey={publicKey}\n apiKey={apiKey}\n apiSecret={apiSecret}\n apiUrl={apiUrl}\n isOpen={isOpen}\n config={paymentConfig}\n theme={theme}\n debug={debug}\n merchantName={merchantName}\n onSuccess={callbacks.onSuccess}\n onError={callbacks.onError}\n onClose={closePayment}\n />\n )}\n </CoinleyContext.Provider>\n );\n};\n\nexport const CoinleyCheckout = forwardRef((\n {\n customerEmail = '',\n merchantName = '',\n onSuccess,\n onError,\n onClose,\n theme = 'light',\n autoOpen = false,\n testMode = false,\n debug = false,\n merchantWalletAddresses = {}\n },\n ref\n) => {\n const context = useContext(CoinleyContext);\n\n if (!context) {\n throw new Error('CoinleyCheckout must be used within a CoinleyProvider');\n }\n\n const { openPayment, closePayment } = context;\n\n const open = (config) => {\n try {\n if (debug) {\n }\n\n if (!config.amount || config.amount <= 0) {\n throw new Error('Amount must be greater than 0');\n }\n\n const finalConfig = {\n ...config,\n customerEmail: config.customerEmail || customerEmail,\n merchantWalletAddresses: {\n ...merchantWalletAddresses,\n ...config.merchantWalletAddresses\n },\n metadata: {\n ...config.metadata,\n testMode,\n checkoutVersion: '1.0.0'\n }\n };\n\n const checkoutCallbacks = {\n onSuccess,\n onError,\n onClose\n };\n\n openPayment(finalConfig, checkoutCallbacks);\n } catch (error) {\n if (onError) {\n onError(error);\n }\n }\n };\n\n const close = () => {\n closePayment();\n };\n\n useImperativeHandle(ref, () => ({\n open,\n close\n }));\n\n return null;\n});\n\nCoinleyCheckout.displayName = 'CoinleyCheckout';\n\nexport const useCoinley = () => {\n const context = useContext(CoinleyContext);\n if (!context) {\n throw new Error('useCoinley must be used within a CoinleyProvider');\n }\n return context;\n};\n\nexport const ThemeProvider = ({\n initialTheme = 'light',\n children\n}) => {\n const [theme, setTheme] = React.useState(initialTheme);\n\n React.useEffect(() => {\n document.documentElement.setAttribute('data-coinley-theme', theme);\n }, [theme]);\n\n const toggleTheme = () => {\n setTheme(prev => prev === 'light' ? 'dark' : 'light');\n };\n\n return (\n <div className={`coinley-theme-${theme}`}>\n {children}\n </div>\n );\n};","//src/PaymentAPI.js\nimport axios from 'axios';\n\nexport class PaymentAPI {\n // Supports both new publicKey auth and legacy apiKey+apiSecret auth\n constructor(baseURL, publicKeyOrApiKey, apiSecret = null) {\n // Determine if using new publicKey auth (starts with 'pk_') or legacy auth\n if (publicKeyOrApiKey && publicKeyOrApiKey.startsWith('pk_')) {\n // New public key authentication\n this.publicKey = publicKeyOrApiKey;\n this.apiKey = null;\n this.apiSecret = null;\n } else {\n // Legacy authentication with apiKey + apiSecret\n this.publicKey = null;\n this.apiKey = publicKeyOrApiKey;\n this.apiSecret = apiSecret;\n }\n\n this.api = axios.create({\n baseURL: baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL,\n timeout: 30000,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n // Add request interceptor\n this.api.interceptors.request.use(\n (config) => {\n // Use public key if available (new method)\n if (this.publicKey) {\n config.headers['x-public-key'] = this.publicKey;\n } else {\n // Fall back to legacy apiKey + apiSecret\n config.headers['x-api-key'] = this.apiKey;\n config.headers['x-api-secret'] = this.apiSecret;\n\n const token = this.generateMerchantToken();\n if (token) {\n config.headers['Authorization'] = `Bearer ${token}`;\n }\n }\n\n\n return config;\n },\n (error) => {\n return Promise.reject(error);\n }\n );\n\n // Add response interceptor\n this.api.interceptors.response.use(\n (response) => {\n return response;\n },\n (error) => {\n\n if (error.response?.status === 401) {\n throw new Error('Authentication failed. Please check your API credentials.');\n } else if (error.response?.status === 404) {\n throw new Error('API endpoint not found. Please check your API URL.');\n } else if (error.response?.status >= 500) {\n throw new Error('Server error. Please try again later.');\n }\n\n throw error;\n }\n );\n }\n\n generateMerchantToken() {\n try {\n const credentials = `${this.apiKey}:${this.apiSecret}`;\n return btoa(credentials);\n } catch (error) {\n return null;\n }\n }\n\n // ✅ FIXED: Add generic request method for internal use\n async request(endpoint, options = {}) {\n try {\n const response = await this.api({\n url: endpoint,\n method: options.method || 'GET',\n data: options.data || options.body ? JSON.parse(options.body || '{}') : undefined,\n ...options\n });\n return response.data;\n } catch (error) {\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Request failed');\n }\n }\n\n async createPayment(params) {\n try {\n const response = await this.api.post('/api/payments/create', params);\n return response.data;\n } catch (error) {\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Failed to create payment');\n }\n }\n\n async getPayment(paymentId) {\n try {\n const response = await this.api.get(`/api/payments/${paymentId}`);\n return response.data;\n } catch (error) {\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Failed to get payment details');\n }\n }\n\n async getNetworks() {\n try {\n const response = await this.api.get('/api/networks');\n return response.data;\n } catch (error) {\n \n // Return fallback networks\n // ✅ FIXED: chainId now returned as decimal integers for consistency with backend\n return {\n networks: [\n {\n id: 'ethereum',\n name: 'Ethereum',\n shortName: 'ethereum',\n chainId: 1, // ✅ Decimal integer\n type: 'ethereum',\n explorerUrl: 'https://etherscan.io',\n isTestnet: false,\n },\n {\n id: 'bsc',\n name: 'Binance Smart Chain',\n shortName: 'bsc',\n chainId: 56, // ✅ Decimal integer\n type: 'bsc',\n explorerUrl: 'https://bscscan.com',\n isTestnet: false,\n },\n {\n id: 'polygon',\n name: 'Polygon',\n shortName: 'polygon',\n chainId: 137, // ✅ Decimal integer\n type: 'ethereum',\n explorerUrl: 'https://polygonscan.com',\n isTestnet: false,\n },\n ]\n };\n }\n }\n\n async getStablecoins() {\n try {\n const response = await this.api.get('/api/networks/stablecoins');\n return response.data;\n } catch (error) {\n \n // Return fallback stablecoins\n return {\n stablecoins: [\n {\n id: 'usdt-eth',\n name: 'Tether USD',\n symbol: 'USDT',\n contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n decimals: 6,\n isStablecoin: true,\n networkId: 'ethereum',\n Network: {\n id: 'ethereum',\n name: 'Ethereum',\n shortName: 'ethereum',\n type: 'ethereum',\n }\n },\n {\n id: 'usdc-eth',\n name: 'USD Coin',\n symbol: 'USDC',\n contractAddress: '0xA0b86a33E6441d81d0B93bF9EE0f74ca32F7e6f6',\n decimals: 6,\n isStablecoin: true,\n networkId: 'ethereum',\n Network: {\n id: 'ethereum',\n name: 'Ethereum',\n shortName: 'ethereum',\n type: 'ethereum',\n }\n }\n ]\n };\n }\n }\n\n async verifyQRPayment(paymentId) {\n try {\n const response = await this.api.post('/api/payments/verify-qr', {\n paymentId\n });\n return response.data;\n } catch (error) {\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Failed to verify payment');\n }\n }\n\n // ✅ PaymentSplitter: Process payment with transaction hash (ENHANCED ERROR HANDLING)\n async processPayment(paymentId, transactionHash, network, senderAddress) {\n try {\n\n const response = await this.api.post('/api/payments/process', {\n paymentId,\n transactionHash,\n network,\n senderAddress\n });\n\n return response.data;\n } catch (error) {\n\n // ✅ ENHANCED: Better error categorization for frontend handling\n if (error.response?.data) {\n const errorData = error.response.data;\n const errorMessage = errorData.error || errorData.message || 'Payment processing failed';\n\n // Create enhanced error with additional context\n const enhancedError = new Error(errorMessage);\n enhancedError.isAlreadyCompleted = errorData.isAlreadyCompleted || false;\n enhancedError.verificationAttempts = errorData.verificationAttempts || 0;\n enhancedError.statusCode = error.response.status;\n enhancedError.originalData = errorData;\n\n throw enhancedError;\n }\n\n throw new Error(error.message || 'Failed to process PaymentSplitter transaction');\n }\n }\n\n // ✅ PaymentSplitter: Get contract information for a specific chain\n async getContractInfo(chainId) {\n try {\n\n const response = await this.api.get(`/api/payments/contract/${chainId}`);\n \n return response.data.contractInfo;\n } catch (error) {\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Failed to get contract information');\n }\n }\n\n // ✅ PaymentSplitter: Get payment splitter status\n async getPaymentSplitterStatus(paymentId) {\n try {\n\n const response = await this.api.get(`/api/payments/splitter-status/${paymentId}`);\n \n return response.data.paymentSplitterStatus;\n } catch (error) {\n if (error.response?.data?.error) {\n throw new Error(error.response.data.error);\n }\n throw new Error(error.message || 'Failed to get PaymentSplitter status');\n }\n }\n\n // ✅ PaymentSplitter: Health check\n async checkPaymentSplitterHealth() {\n try {\n const response = await this.api.get('/api/payments/health');\n return response.data.paymentSplitterHealth;\n } catch (error) {\n return { error: error.message };\n }\n }\n\n async healthCheck() {\n try {\n const response = await this.api.get('/api/health');\n return response.status === 200;\n } catch (error) {\n return false;\n }\n }\n}","// Balance checking utilities for both ERC-20 tokens and native currencies\nimport { createPublicClient, http, formatUnits, getContract } from 'viem';\nimport { mainnet, bsc, polygon, arbitrum, optimism, avalanche } from 'viem/chains';\n\n// Network chain configurations\nconst NETWORK_CHAINS = {\n ethereum: mainnet,\n bsc: bsc,\n polygon: polygon,\n arbitrum: arbitrum,\n optimism: optimism,\n avalanche: avalanche\n};\n\n// ERC-20 ABI for balance checking\nconst ERC20_ABI = [\n {\n constant: true,\n inputs: [{ name: '_owner', type: 'address' }],\n name: 'balanceOf',\n outputs: [{ name: 'balance', type: 'uint256' }],\n type: 'function',\n },\n {\n constant: true,\n inputs: [],\n name: 'decimals',\n outputs: [{ name: '', type: 'uint8' }],\n type: 'function',\n },\n {\n constant: true,\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '', type: 'string' }],\n type: 'function',\n },\n];\n\nclass BalanceChecker {\n constructor() {\n this.clients = new Map();\n }\n\n // Get or create viem client for network\n getClient(networkShortName) {\n if (!this.clients.has(networkShortName)) {\n const chain = NETWORK_CHAINS[networkShortName];\n if (!chain) {\n throw new Error(`Unsupported network: ${networkShortName}`);\n }\n \n const client = createPublicClient({\n chain,\n transport: http()\n });\n this.clients.set(networkShortName, client);\n }\n \n return this.clients.get(networkShortName);\n }\n\n // Check native token balance (ETH, BNB, MATIC, etc.)\n async checkNativeBalance(walletAddress, networkShortName) {\n try {\n \n const client = this.getClient(networkShortName);\n const balanceWei = await client.getBalance({ \n address: walletAddress \n });\n const balanceEther = formatUnits(balanceWei, 18);\n \n \n return {\n balance: parseFloat(balanceEther),\n balanceWei: balanceWei.toString(),\n symbol: this.getNativeTokenSymbol(networkShortName),\n decimals: 18\n };\n } catch (error) {\n throw new Error(`Failed to check native balance: ${error.message}`);\n }\n }\n\n // Check ERC-20 token balance\n async checkTokenBalance(walletAddress, tokenAddress, networkShortName) {\n try {\n \n const client = this.getClient(networkShortName);\n \n // Create contract instance\n const contract = getContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n client\n });\n \n // Get token info and balance in parallel\n const [balanceWei, decimals, symbol] = await Promise.all([\n contract.read.balanceOf([walletAddress]),\n contract.read.decimals().catch(() => 18), // Default to 18 if fails\n contract.read.symbol().catch(() => 'TOKEN')\n ]);\n \n const balance = parseFloat(formatUnits(balanceWei, decimals));\n \n \n return {\n balance: balance,\n balanceWei: balanceWei.toString(),\n symbol: symbol,\n decimals: decimals,\n tokenAddress: tokenAddress\n };\n } catch (error) {\n throw new Error(`Failed to check token balance: ${error.message}`);\n }\n }\n\n // Check if user has sufficient balance for transaction\n async validateBalance(walletAddress, token, requiredAmount, networkShortName, includeGasFee = true) {\n try {\n \n let tokenBalance;\n let nativeBalance = null;\n \n // Check token balance\n if (token.contractAddress) {\n // ERC-20 token\n tokenBalance = await this.checkTokenBalance(walletAddress, token.contractAddress, networkShortName);\n } else {\n // Native token\n tokenBalance = await this.checkNativeBalance(walletAddress, networkShortName);\n }\n \n // Always check native balance for gas fees (unless it's the same as the payment token)\n if (token.contractAddress && includeGasFee) {\n nativeBalance = await this.checkNativeBalance(walletAddress, networkShortName);\n }\n \n // Validate token balance\n const hasEnoughTokens = tokenBalance.balance >= requiredAmount;\n const tokenShortfall = hasEnoughTokens ? 0 : requiredAmount - tokenBalance.balance;\n \n // Estimate gas fees\n let estimatedGasFee = 0;\n let hasEnoughForGas = true;\n let gasShortfall = 0;\n \n if (includeGasFee) {\n estimatedGasFee = this.estimateGasFee(networkShortName, !!token.contractAddress);\n \n if (token.contractAddress) {\n // ERC-20 payment - need native tokens for gas\n hasEnoughForGas = nativeBalance.balance >= estimatedGasFee;\n gasShortfall = hasEnoughForGas ? 0 : estimatedGasFee - nativeBalance.balance;\n } else {\n // Native token payment - need extra for gas\n const totalRequired = requiredAmount + estimatedGasFee;\n hasEnoughForGas = tokenBalance.balance >= totalRequired;\n gasShortfall = hasEnoughForGas ? 0 : totalRequired - tokenBalance.balance;\n }\n }\n \n const validationResult = {\n isValid: hasEnoughTokens && hasEnoughForGas,\n tokenBalance: tokenBalance,\n nativeBalance: nativeBalance,\n requiredAmount: requiredAmount,\n estimatedGasFee: estimatedGasFee,\n hasEnoughTokens: hasEnoughTokens,\n hasEnoughForGas: hasEnoughForGas,\n tokenShortfall: tokenShortfall,\n gasShortfall: gasShortfall,\n errors: []\n };\n \n // Add specific error messages\n if (!hasEnoughTokens) {\n validationResult.errors.push(\n `Insufficient ${token.symbol} balance. Need ${requiredAmount} ${token.symbol}, have ${tokenBalance.balance.toFixed(6)} ${token.symbol}`\n );\n }\n \n if (!hasEnoughForGas) {\n const gasTokenSymbol = nativeBalance?.symbol || this.getNativeTokenSymbol(networkShortName);\n if (token.contractAddress) {\n validationResult.errors.push(\n `Insufficient ${gasTokenSymbol} for gas fees. Need ~${estimatedGasFee.toFixed(6)} ${gasTokenSymbol}, have ${nativeBalance.balance.toFixed(6)} ${gasTokenSymbol}`\n );\n } else {\n validationResult.errors.push(\n `Insufficient ${gasTokenSymbol} for payment + gas. Need ${(requiredAmount + estimatedGasFee).toFixed(6)} ${gasTokenSymbol} total, have ${tokenBalance.balance.toFixed(6)} ${gasTokenSymbol}`\n );\n }\n }\n \n return validationResult;\n \n } catch (error) {\n return {\n isValid: false,\n errors: [`Failed to check balance: ${error.message}`],\n tokenBalance: null,\n nativeBalance: null\n };\n }\n }\n\n // Estimate gas fee for the transaction\n estimateGasFee(networkShortName, isERC20 = false) {\n // Conservative gas fee estimates (in native token)\n const gasEstimates = {\n ethereum: isERC20 ? 0.001 : 0.0005, // ETH - higher for ERC-20\n bsc: isERC20 ? 0.0005 : 0.0003, // BNB - cheaper than ETH\n polygon: isERC20 ? 0.01 : 0.005, // MATIC - very cheap\n arbitrum: isERC20 ? 0.0003 : 0.0002, // ETH on L2 - very cheap\n optimism: isERC20 ? 0.0003 : 0.0002, // ETH on L2 - very cheap\n avalanche: isERC20 ? 0.001 : 0.0005 // AVAX - moderate fees\n };\n \n return gasEstimates[networkShortName] || 0.001; // Default conservative estimate\n }\n\n // Get native token symbol for network\n getNativeTokenSymbol(networkShortName) {\n const nativeTokens = {\n ethereum: 'ETH',\n bsc: 'BNB',\n polygon: 'MATIC',\n arbitrum: 'ETH',\n optimism: 'ETH',\n avalanche: 'AVAX'\n };\n \n return nativeTokens[networkShortName] || 'ETH';\n }\n\n // Quick balance check (just returns balance, no validation)\n async getBalance(walletAddress, token, networkShortName) {\n if (token.contractAddress) {\n return await this.checkTokenBalance(walletAddress, token.contractAddress, networkShortName);\n } else {\n return await this.checkNativeBalance(walletAddress, networkShortName);\n }\n }\n\n // Format balance for display\n formatBalance(balance, symbol, decimals = 6) {\n if (balance === null || balance === undefined) return 'Unknown';\n \n if (balance === 0) return `0 ${symbol}`;\n \n // Show more decimals for small amounts\n if (balance < 0.001) {\n return `${balance.toFixed(8)} ${symbol}`;\n } else if (balance < 1) {\n return `${balance.toFixed(6)} ${symbol}`;\n } else {\n return `${balance.toFixed(4)} ${symbol}`;\n }\n }\n\n // Check multiple token balances at once\n async checkMultipleBalances(walletAddress, tokens, networkShortName) {\n try {\n const balancePromises = tokens.map(token => \n this.getBalance(walletAddress, token, networkShortName)\n .catch(error => ({\n error: error.message,\n symbol: token.symbol,\n balance: 0\n }))\n );\n \n const results = await Promise.all(balancePromises);\n return results;\n } catch (error) {\n throw error;\n }\n }\n}\n\n// Singleton instance\nconst balanceChecker = new BalanceChecker();\n\n// Export both the class and instance\nexport { BalanceChecker, balanceChecker };\nexport default balanceChecker;","import React, { useState, useEffect, useRef } from 'react';\nimport QRCode from 'qrcode';\nimport balanceChecker from '../utils/balanceChecker';\n\n// Simple Payment API (reusing same structure)\nclass SimplePaymentAPI {\n constructor(baseURL, apiKey, apiSecret) {\n this.baseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;\n this.apiKey = apiKey;\n this.apiSecret = apiSecret;\n }\n\n async request(endpoint, options = {}) {\n const url = `${this.baseURL}${endpoint}`;\n const headers = {\n 'Content-Type': 'application/json',\n 'X-API-Key': this.apiKey,\n 'X-API-Secret': this.apiSecret,\n ...options.headers\n };\n\n const response = await fetch(url, {\n ...options,\n headers\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new Error(error.error || `HTTP ${response.status}`);\n }\n\n return response.json();\n }\n\n async getNetworks() {\n try {\n return await this.request('/api/networks');\n } catch (error) {\n return {\n networks: [\n { id: '1', name: 'Ethereum', shortName: 'ethereum', chainId: '0x1', type: 'ethereum' },\n { id: '56', name: 'BSC', shortName: 'bsc', chainId: '0x38', type: 'bsc' },\n { id: '137', name: 'Polygon', shortName: 'polygon', chainId: '0x89', type: 'polygon' },\n { id: '42161', name: 'Arbitrum', shortName: 'arbitrum', chainId: '0xa4b1', type: 'arbitrum' },\n { id: '10', name: 'Optimism', shortName: 'optimism', chainId: '0xa', type: 'optimism' },\n { id: '43114', name: 'Avalanche', shortName: 'avalanche', chainId: '0xa86a', type: 'avalanche' },\n { id: '42220', name: 'Celo', shortName: 'celo', chainId: '0xa4ec', type: 'celo' },\n { id: '8453', name: 'Base', shortName: 'base', chainId: '0x2105', type: 'base' }\n ]\n };\n }\n }\n\n async getTokens() {\n try {\n return await this.request('/api/networks/stablecoins');\n } catch (error) {\n return {\n stablecoins: [\n {\n id: '1', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n decimals: 6, networkId: '1',\n Network: { shortName: 'ethereum', name: 'Ethereum' }\n },\n {\n id: '2', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xA0b86a33E641a3FA62e50A9da1CE0647a2bFBC5A',\n decimals: 6, networkId: '1',\n Network: { shortName: 'ethereum', name: 'Ethereum' }\n },\n {\n id: '3', name: 'Binance USD', symbol: 'BUSD',\n contractAddress: '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56',\n decimals: 18, networkId: '56',\n Network: { shortName: 'bsc', name: 'BSC' }\n },\n {\n id: '4', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',\n decimals: 18, networkId: '56',\n Network: { shortName: 'bsc', name: 'BSC' }\n },\n {\n id: '5', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174',\n decimals: 6, networkId: '137',\n Network: { shortName: 'polygon', name: 'Polygon' }\n },\n {\n id: '6', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F',\n decimals: 6, networkId: '137',\n Network: { shortName: 'polygon', name: 'Polygon' }\n },\n \n // Arbitrum Network\n {\n id: '7', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',\n decimals: 6, networkId: '42161',\n Network: { shortName: 'arbitrum', name: 'Arbitrum' }\n },\n {\n id: '8', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n decimals: 6, networkId: '42161',\n Network: { shortName: 'arbitrum', name: 'Arbitrum' }\n },\n \n // Optimism Network\n {\n id: '9', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58',\n decimals: 6, networkId: '10',\n Network: { shortName: 'optimism', name: 'Optimism' }\n },\n {\n id: '10', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n decimals: 6, networkId: '10',\n Network: { shortName: 'optimism', name: 'Optimism' }\n },\n \n // Avalanche Network\n {\n id: '11', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7',\n decimals: 6, networkId: '43114',\n Network: { shortName: 'avalanche', name: 'Avalanche' }\n },\n {\n id: '12', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',\n decimals: 6, networkId: '43114',\n Network: { shortName: 'avalanche', name: 'Avalanche' }\n },\n \n // Celo Network\n {\n id: '13', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e',\n decimals: 6, networkId: '42220',\n Network: { shortName: 'celo', name: 'Celo' }\n },\n {\n id: '14', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0xcebA9300f2b948710d2653dD7B07f33A8B32118C',\n decimals: 6, networkId: '42220',\n Network: { shortName: 'celo', name: 'Celo' }\n },\n\n // Base Network\n {\n id: '15', name: 'Tether USD', symbol: 'USDT',\n contractAddress: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2',\n decimals: 6, networkId: '8453',\n Network: { shortName: 'base', name: 'Base' }\n },\n {\n id: '16', name: 'USD Coin', symbol: 'USDC',\n contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n decimals: 6, networkId: '8453',\n Network: { shortName: 'base', name: 'Base' }\n }\n ]\n };\n }\n }\n\n async createPayment(data) {\n return await this.request('/api/payments/create', {\n method: 'POST',\n body: JSON.stringify(data)\n });\n }\n\n async updatePaymentStatus(paymentId, status, transactionHash = null) {\n return await this.request(`/api/payments/${paymentId}/status`, {\n method: 'PUT',\n body: JSON.stringify({ status, transactionHash })\n });\n }\n}\n\n// QR Code Payment Component\nconst QRCodePayment = ({\n apiKey,\n apiSecret,\n apiUrl,\n config,\n onSuccess,\n onError,\n onClose,\n isOpen,\n theme = 'light',\n mode = 'splitpayment', // Always use split payment mode for QR codes\n splitPaymentUrl = 'https://paymentscreen.vercel.app/'\n}) => {\n const [currentStep, setCurrentStep] = useState('network');\n const [networks, setNetworks] = useState([]);\n const [tokens, setTokens] = useState([]);\n const [selectedNetwork, setSelectedNetwork] = useState(null);\n const [selectedToken, setSelectedToken] = useState(null);\n const [paymentData, setPaymentData] = useState(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState('');\n const [qrCodeData, setQrCodeData] = useState('');\n const [qrCodeImage, setQrCodeImage] = useState('');\n const [connectionId, setConnectionId] = useState('');\n const [walletConnected, setWalletConnected] = useState(false);\n const [walletAddress, setWalletAddress] = useState('');\n const [checkingPayment, setCheckingPayment] = useState(false);\n const [balanceValidation, setBalanceValidation] = useState(null);\n \n const api = useRef(new SimplePaymentAPI(apiUrl, apiKey, apiSecret));\n const checkInterval = useRef(null);\n\n useEffect(() => {\n if (isOpen) {\n loadData();\n resetState();\n }\n return () => {\n if (checkInterval.current) {\n clearInterval(checkInterval.current);\n }\n };\n }, [isOpen]);\n\n const resetState = () => {\n setCurrentStep('network');\n setSelectedNetwork(null);\n setSelectedToken(null);\n setPaymentData(null);\n setError('');\n setQrCodeData('');\n setQrCodeImage('');\n setConnectionId('');\n setWalletConnected(false);\n setWalletAddress('');\n setCheckingPayment(false);\n setBalanceValidation(null);\n if (checkInterval.current) {\n clearInterval(checkInterval.current);\n }\n };\n\n const loadData = async () => {\n try {\n setLoading(true);\n setError('');\n \n const [networksRes, tokensRes] = await Promise.all([\n api.current.getNetworks(),\n api.current.getTokens()\n ]);\n \n setNetworks(networksRes.networks || []);\n setTokens(tokensRes.stablecoins || []);\n \n } catch (err) {\n setError('Failed to load payment options.');\n } finally {\n setLoading(false);\n }\n };\n\n const createPayment = async () => {\n try {\n setLoading(true);\n setError('');\n \n const paymentPayload = {\n amount: config.amount,\n currency: selectedToken.symbol,\n network: selectedNetwork.shortName,\n customerEmail: config.customerEmail,\n callbackUrl: config.callbackUrl,\n metadata: {\n ...config.metadata,\n merchantWalletAddresses: config.merchantWalletAddresses,\n paymentMethod: 'qr_code',\n selectedNetwork: selectedNetwork.shortName,\n selectedToken: selectedToken.symbol\n }\n };\n\n const payment = await api.current.createPayment(paymentPayload);\n setPaymentData(payment.payment);\n \n // Generate connection ID for this payment session\n const connId = `qr_${payment.payment.id}_${Date.now()}`;\n setConnectionId(connId);\n \n // Generate QR code with payment details\n await generateQRCode(payment.payment, connId);\n \n setCurrentStep('scan');\n \n } catch (err) {\n setError(err.message);\n } finally {\n setLoading(false);\n }\n };\n\n // Helper function to convert amounts to base units (no floating point)\n const toBaseUnits = (amountStr, decimals) => {\n const [intPart, fracPart = ''] = String(amountStr).split('.');\n const frac = (fracPart + '0'.repeat(decimals)).slice(0, decimals);\n const raw = (intPart || '0') + frac;\n return BigInt(raw.replace(/^0+/, '') || '0').toString();\n };\n\n // Build EIP-681 compliant URI for wallet compatibility\n const buildEip681 = ({ recipient, token, network, totalAmount }) => {\n // 1) Convert chain ID to decimal\n const chainId = typeof network.chainId === 'string' && network.chainId.startsWith('0x')\n ? parseInt(network.chainId, 16)\n : Number(network.chainId);\n \n if (!Number.isFinite(chainId)) {\n throw new Error(`Invalid chain ID: ${network.chainId}`);\n }\n\n // 2) Validate required fields\n if (!recipient) throw new Error(`No merchant address configured for ${network.shortName}`);\n if (!token?.contractAddress) throw new Error('Missing token contract address');\n if (totalAmount == null) throw new Error('Missing payment amount');\n\n // 3) Convert amount to base units using token decimals\n const amountBase = toBaseUnits(String(totalAmount), token.decimals ?? 18);\n\n // 4) Build EIP-681 URI for ERC-20 transfer(address,uint256)\n return `ethereum:${token.contractAddress}@${chainId}/transfer?address=${recipient}&uint256=${amountBase}`;\n };\n\n // Generate Split Payment QR with backend record creation\n const generateSplitPaymentQRDirect = async (token) => {\n try {\n setLoading(true);\n setError('');\n\n // First create payment record in backend (same as before)\n const paymentPayload = {\n amount: config.amount,\n currency: token.symbol,\n network: selectedNetwork.shortName,\n customerEmail: config.customerEmail,\n callbackUrl: config.callbackUrl,\n metadata: {\n ...config.metadata,\n merchantWalletAddresses: config.merchantWalletAddresses,\n paymentMethod: 'split_payment_qr',\n selectedNetwork: selectedNetwork.shortName,\n selectedToken: token.symbol\n }\n };\n\n const payment = await api.current.createPayment(paymentPayload);\n setPaymentData(payment.payment);\n\n const contractAddress = config.merchantWalletAddresses?.splitPaymentContract ||\n config.merchantWalletAddresses?.[selectedNetwork.shortName];\n\n if (!contractAddress) {\n throw new Error('Split payment contract address not found in config');\n }\n\n // Generate payment screen URL instead of EIP-681\n const params = new URLSearchParams({\n merchant: config.merchantName || 'Coinley Merchant',\n amount: payment.payment.totalAmount.toString(),\n productAmount: (payment.payment.totalAmount * 0.95).toFixed(2),\n platformFee: (payment.payment.totalAmount * 0.03).toFixed(2),\n networkFee: (payment.payment.totalAmount * 0.02).toFixed(2),\n token: token.symbol,\n network: selectedNetwork.name,\n merchantAddress: contractAddress,\n paymentId: payment.payment.id // Include payment ID for backend tracking\n });\n\n const splitPaymentUri = splitPaymentUrl + '?' + params.toString();\n setQrCodeData(splitPaymentUri);\n\n // Generate QR code image\n const qrImage = await QRCode.toDataURL(splitPaymentUri, {\n width: 256,\n margin: 2,\n color: {\n dark: '#7c3aed',\n light: '#ffffff'\n }\n });\n\n setQrCodeImage(qrImage);\n setCurrentStep('scan');\n\n\n } catch (error) {\n setError(error.message || 'Failed to generate split payment QR code');\n } finally {\n setLoading(false);\n }\n };\n\n // Generate Split Payment QR (redirects to payment screen)\n const generateSplitPaymentQR = async (payment) => {\n try {\n const contractAddress = config.merchantWalletAddresses?.splitPaymentContract ||\n config.merchantWalletAddresses?.[selectedNetwork.shortName];\n\n if (!contractAddress) {\n throw new Error('Split payment contract address not found');\n }\n\n // Build payment screen URL with parameters\n const params = new URLSearchParams({\n merchant: config.merchantName || 'Coinley Merchant',\n amount: payment.totalAmount.toString(),\n productAmount: (payment.totalAmount * 0.95).toFixed(2),\n platformFee: (payment.totalAmount * 0.03).toFixed(2),\n networkFee: (payment.totalAmount * 0.02).toFixed(2),\n token: selectedToken.symbol,\n network: selectedNetwork.name,\n merchantAddress: contractAddress\n });\n\n const splitPaymentUri = splitPaymentUrl + '?' + params.toString();\n setQrCodeData(splitPaymentUri);\n\n // Generate QR code image\n const qrImage = await QRCode.toDataURL(splitPaymentUri, {\n width: 256,\n margin: 2,\n color: {\n dark: '#7c3aed',\n light: '#ffffff'\n }\n });\n\n setQrCodeImage(qrImage);\n\n\n } catch (error) {\n setError(error.message || 'Failed to generate split payment QR code');\n }\n };\n\n const generateQRCode = async (payment, connId) => {\n try {\n if (mode === 'splitpayment') {\n // Generate split payment QR (redirects to payment screen)\n await generateSplitPaymentQR(payment);\n } else {\n // Generate wallet QR (EIP-681 format)\n const recipient = config.merchantWalletAddresses?.[selectedNetwork.shortName];\n\n // Build standards-compliant EIP-681 URI\n const eip681Uri = buildEip681({\n recipient,\n token: selectedToken,\n network: selectedNetwork,\n totalAmount: payment.totalAmount\n });\n\n setQrCodeData(eip681Uri);\n\n // Generate QR code image\n const qrImage = await QRCode.toDataURL(eip681Uri, {\n width: 256,\n margin: 2,\n color: {\n dark: theme === 'dark' ? '#FFFFFF' : '#000000',\n light: theme === 'dark' ? '#000000' : '#FFFFFF'\n }\n });\n\n setQrCodeImage(qrImage);\n\n }\n\n } catch (error) {\n setError(error.message || 'Failed to generate QR code');\n }\n };\n\n // Mock wallet connection via QR scan (simulate mobile wallet scanning)\n const simulateWalletScan = async () => {\n try {\n setLoading(true);\n setError('');\n \n // Simulate wallet address from scan\n const mockWalletAddress = '0x742d35Cc6634C0532925a3b8D9a5C7C47C77E4';\n setWalletAddress(mockWalletAddress);\n setWalletConnected(true);\n \n // Check balance\n await checkWalletBalance(mockWalletAddress);\n \n setCurrentStep('confirm');\n \n } catch (error) {\n setError('Failed to simulate wallet connection');\n } finally {\n setLoading(false);\n }\n };\n\n const checkWalletBalance = async (address) => {\n if (!selectedToken || !selectedNetwork || !paymentData) {\n return false;\n }\n\n try {\n \n const validation = await balanceChecker.validateBalance(\n address,\n selectedToken,\n paymentData.totalAmount,\n selectedNetwork.shortName,\n true\n );\n\n setBalanceValidation(validation);\n\n if (!validation.isValid) {\n setError(`Insufficient balance: ${validation.errors.join(', ')}`);\n return false;\n }\n\n return true;\n\n } catch (error) {\n setError(`Failed to check balance: ${error.message}`);\n return false;\n }\n };\n\n // Simulate transaction confirmation\n const simulateTransaction = async () => {\n try {\n setCheckingPayment(true);\n setError('');\n \n // Simulate transaction hash\n const mockTxHash = `0x${Math.random().toString(16).substring(2, 66)}`;\n \n // Simulate delay for blockchain confirmation\n await new Promise(resolve => setTimeout(resolve, 3000));\n \n setCurrentStep('success');\n \n onSuccess?.(paymentData.id, mockTxHash, {\n network: selectedNetwork.name,\n token: selectedToken.symbol,\n amount: paymentData.totalAmount,\n method: 'qr_code',\n walletAddress: walletAddress\n });\n\n } catch (error) {\n setError('Transaction confirmation failed');\n } finally {\n setCheckingPayment(false);\n }\n };\n\n if (!isOpen) return null;\n\n const isDark = theme === 'dark';\n\n return (\n <div className=\"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50\">\n <div className={`rounded-lg shadow-xl max-w-md w-full mx-4 ${isDark ? 'bg-gray-900 text-white' : 'bg-white text-gray-900'}`}>\n \n {/* Header */}\n <div className={`p-4 border-b flex justify-between items-center ${isDark ? 'border-gray-700' : 'border-gray-200'}`}>\n <div className=\"text-center flex-1\">\n <h2 className=\"text-lg font-semibold\">\n {mode === 'splitpayment' ? 'Split Payment QR' : 'QR Code Payment'}\n </h2>\n {config.amount && (\n <p className=\"text-2xl font-bold text-purple-600\">${config.amount.toFixed(2)}</p>\n )}\n <p className=\"text-xs text-blue-600\">\n {mode === 'splitpayment'\n ? '📱 Scan to redirect to payment screen'\n : '📱 Scan with mobile wallet'\n }\n </p>\n </div>\n <button\n onClick={onClose}\n className={`ml-4 text-gray-500 hover:text-gray-700 ${isDark ? 'hover:text-gray-300' : ''}`}\n >\n ✕\n </button>\n </div>\n\n {/* Content */}\n <div className=\"p-4 min-h-[400px]\">\n {error && (\n <div className=\"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200\">\n {error}\n <button \n onClick={() => setError('')}\n className=\"ml-2 text-red-500 hover:text-red-700\"\n >\n ✕\n </button>\n </div>\n )}\n\n {/* Step 1: Select Network */}\n {currentStep === 'network' && (\n <div className=\"space-y-4\">\n <h3 className=\"font-medium text-center\">Select Network</h3>\n <div className=\"space-y-2\">\n {networks.map((network) => {\n const hasAddress = config.merchantWalletAddresses?.[network.shortName];\n return (\n <button\n key={network.id}\n onClick={() => { setSelectedNetwork(network); setCurrentStep('token'); }}\n disabled={!hasAddress}\n className={`w-full p-3 border rounded-lg text-left transition-colors ${\n hasAddress \n ? `hover:border-purple-500 ${isDark ? 'border-gray-600 hover:bg-gray-800' : 'border-gray-200 hover:bg-gray-50'}`\n : `opacity-50 cursor-not-allowed ${isDark ? 'border-gray-700' : 'border-gray-100'}`\n }`}\n >\n <div className=\"font-medium\">{network.name}</div>\n <div className={`text-sm ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>\n {network.shortName.toUpperCase()}\n {!hasAddress && ' (No merchant address configured)'}\n </div>\n </button>\n );\n })}\n </div>\n </div>\n )}\n\n {/* Step 2: Select Token */}\n {currentStep === 'token' && (\n <div className=\"space-y-4\">\n <div className=\"flex items-center space-x-2\">\n <button \n onClick={() => setCurrentStep('network')} \n className={`${isDark ? 'text-gray-400 hover:text-gray-200' : 'text-gray-500 hover:text-gray-700'}`}\n >\n ←\n </button>\n <h3 className=\"font-medium\">Select Token on {selectedNetwork?.name}</h3>\n </div>\n <div className=\"space-y-2\">\n {tokens\n .filter(token => token.Network?.shortName === selectedNetwork?.shortName)\n .map((token) => (\n <button\n key={token.id}\n onClick={() => {\n setSelectedToken(token);\n generateSplitPaymentQRDirect(token);\n }}\n disabled={loading}\n className={`w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors disabled:opacity-50 ${isDark ? 'border-gray-600 hover:bg-gray-800' : 'border-gray-200 hover:bg-gray-50'}`}\n >\n <div className=\"font-medium\">{token.name}</div>\n <div className={`text-sm ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>{token.symbol}</div>\n </button>\n ))\n }\n </div>\n </div>\n )}\n\n {/* Step 3: Scan QR Code */}\n {currentStep === 'scan' && (\n <div className=\"space-y-4\">\n <div className=\"text-center\">\n <h3 className=\"font-medium mb-4\">\n {mode === 'splitpayment'\n ? 'Scan QR Code to Open Payment Screen'\n : 'Scan QR Code with Mobile Wallet'\n }\n </h3>\n\n {qrCodeImage ? (\n <div className=\"flex flex-col items-center space-y-4\">\n <div className={`p-4 rounded-lg ${isDark ? 'bg-gray-800' : 'bg-gray-50'}`}>\n <img\n src={qrCodeImage}\n alt=\"Payment QR Code\"\n className=\"mx-auto\"\n style={{ width: '200px', height: '200px' }}\n />\n </div>\n\n <div className={`text-sm space-y-1 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>\n <div className=\"flex justify-between\">\n <span>Amount:</span>\n <span className=\"font-medium\">{paymentData?.totalAmount} {selectedToken?.symbol}</span>\n </div>\n <div className=\"flex justify-between\">\n <span>Network:</span>\n <span className=\"font-medium\">{selectedNetwork?.name}</span>\n </div>\n {mode === 'splitpayment' && (\n <div className=\"flex justify-between\">\n <span>Merchant:</span>\n <span className=\"font-medium\">{config.merchantName || 'Coinley Merchant'}</span>\n </div>\n )}\n </div>\n\n <div className={`p-3 rounded-lg text-xs ${isDark ? 'bg-blue-900 text-blue-200' : 'bg-blue-50 text-blue-600'}`}>\n {mode === 'splitpayment' ? (\n <>\n 📱 Scan this QR code with your mobile wallet to open the payment screen.\n <br />The payment screen will auto-connect your wallet and execute the split payment.\n </>\n ) : (\n '📱 Open your mobile wallet and scan this QR code to connect and pay'\n )}\n </div>\n\n {/* Test buttons */}\n {mode === 'splitpayment' ? (\n <button\n onClick={() => window.open(qrCodeData, '_blank')}\n className=\"w-full bg-purple-600 text-white py-2 px-4 rounded hover:bg-purple-700 text-sm\"\n >\n 🔗 Test Payment Screen (Opens in new tab)\n </button>\n ) : (\n <button\n onClick={simulateWalletScan}\n disabled={loading}\n className=\"w-full bg-gray-600 text-white py-2 px-4 rounded hover:bg-gray-700 disabled:opacity-50 text-sm\"\n >\n {loading ? 'Connecting...' : '🧪 Simulate Wallet Scan (Test)'}\n </button>\n )}\n </div>\n ) : (\n <div className=\"flex items-center justify-center py-8\">\n <div className=\"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600\"></div>\n <span className=\"ml-2\">Generating QR Code...</span>\n </div>\n )}\n </div>\n </div>\n )}\n\n {/* Step 4: Confirm Payment */}\n {currentStep === 'confirm' && (\n <div className=\"space-y-4\">\n <div className=\"text-center\">\n <div className=\"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4\">\n <span className=\"text-2xl\">📱</span>\n </div>\n <h3 className=\"font-medium\">Mobile Wallet Connected</h3>\n <p className={`text-sm mt-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>\n Ready to complete payment\n </p>\n </div>\n \n <div className=\"space-y-4\">\n <div className=\"p-3 bg-green-50 rounded-lg border border-green-200\">\n <p className=\"text-green-600 text-sm font-medium\">✅ Wallet Connected</p>\n <p className=\"font-mono text-xs text-green-700 mt-1\">\n {walletAddress?.slice(0, 6)}...{walletAddress?.slice(-4)}\n </p>\n </div>\n\n {balanceValidation && (\n <div className={`p-3 rounded-lg border ${\n balanceValidation.isValid \n ? 'bg-green-50 border-green-200' \n : 'bg-red-50 border-red-200'\n }`}>\n <div className=\"space-y-2 text-sm\">\n <div className=\"flex justify-between\">\n <span>Required:</span>\n <span className=\"font-medium\">{paymentData?.totalAmount} {selectedToken?.symbol}</span>\n </div>\n <div className=\"flex justify-between\">\n <span>Your Balance:</span>\n <span className={`font-medium ${\n balanceValidation.hasEnoughTokens ? 'text-green-600' : 'text-red-600'\n }`}>\n {balanceChecker.formatBalance(\n balanceValidation.tokenBalance?.balance, \n selectedToken?.symbol\n )}\n </span>\n </div>\n {balanceValidation.nativeBalance && (\n <div className=\"flex justify-between\">\n <span>Gas Balance:</span>\n <span className={`font-medium ${\n balanceValidation.hasEnoughForGas ? 'text-green-600' : 'text-red-600'\n }`}>\n {balanceChecker.formatBalance(\n balanceValidation.nativeBalance.balance, \n balanceValidation.nativeBalance.symbol\n )}\n </span>\n </div>\n )}\n </div>\n </div>\n )}\n\n <button\n onClick={simulateTransaction}\n disabled={checkingPayment || !balanceValidation?.isValid}\n className=\"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium\"\n >\n {checkingPayment ? 'Processing Payment...' : \n !balanceValidation?.isValid ? 'Insufficient Balance' :\n `Confirm Payment of ${paymentData?.totalAmount} ${selectedToken?.symbol}`}\n </button>\n </div>\n </div>\n )}\n\n {/* Success */}\n {currentStep === 'success' && (\n <div className=\"text-center space-y-4\">\n <div className=\"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto\">\n <span className=\"text-2xl\">✅</span>\n </div>\n <h3 className=\"font-medium text-green-600\">Payment Successful!</h3>\n <p className={`text-sm ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>\n Transaction completed via QR code scan\n </p>\n <button\n onClick={onClose}\n className=\"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 font-medium\"\n >\n Close\n </button>\n </div>\n )}\n\n {/* Loading */}\n {loading && currentStep !== 'scan' && currentStep !== 'confirm' && (\n <div className=\"flex items-center justify-center py-8\">\n <div className=\"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600\"></div>\n </div>\n )}\n </div>\n </div>\n </div>\n );\n};\n\nexport default QRCodePayment;","/**\n * Coinley Vanilla JS SDK\n * Version: 2.0.0\n *\n * A framework-agnostic payment SDK for cryptocurrency payments.\n * Works with vanilla JavaScript, WordPress, and any other platform.\n *\n * @example\n * // NEW: Using publicKey (recommended - safe to expose in frontend)\n * const coinley = new CoinleyVanilla({\n * publicKey: 'pk_your-public-key',\n * apiUrl: 'https://api.coinley.io',\n * theme: 'light',\n * debug: false\n * });\n *\n * // LEGACY: Using apiKey + apiSecret (still supported)\n * const coinleyLegacy = new CoinleyVanilla({\n * apiKey: 'your-api-key',\n * apiSecret: 'your-api-secret',\n * apiUrl: 'https://api.coinley.io',\n * theme: 'light',\n * debug: false\n * });\n *\n * coinley.open({\n * amount: 100.00,\n * customerEmail: 'customer@example.com',\n * merchantName: 'My Store',\n * merchantWalletAddresses: {\n * ethereum: '0x...',\n * bsc: '0x...',\n * polygon: '0x...',\n * arbitrum: '0x...',\n * optimism: '0x...',\n * avalanche: '0x...',\n * celo: '0x...',\n * base: '0x...'\n * },\n * metadata: { orderId: '12345' }\n * }, {\n * onSuccess: (paymentId, txHash, details) => { ... },\n * onError: (error) => { ... },\n * onClose: () => { ... }\n * });\n */\n\nimport React from 'react';\nimport { createRoot } from 'react-dom/client';\nimport EnhancedSimpleCoinleyPayment from '../components/EnhancedSimpleCoinleyPayment';\nimport '../styles/index.css';\n\n/**\n * CoinleyVanilla - Vanilla JavaScript SDK for Coinley Payments\n */\nclass CoinleyVanilla {\n /**\n * Initialize Coinley payment SDK\n * @param {Object} config - SDK configuration\n * @param {string} [config.publicKey] - Merchant public key (recommended - starts with 'pk_')\n * @param {string} [config.apiKey] - Merchant API key (legacy, used with apiSecret)\n * @param {string} [config.apiSecret] - Merchant API secret (legacy, used with apiKey)\n * @param {string} config.apiUrl - API base URL (required)\n * @param {string} [config.theme='light'] - UI theme ('light' or 'dark')\n * @param {boolean} [config.debug=false] - Enable debug logging\n */\n constructor(config = {}) {\n // Validate required configuration\n if (!config.publicKey && !config.apiKey) {\n throw new Error('CoinleyVanilla: publicKey or apiKey is required');\n }\n if (!config.publicKey && !config.apiSecret) {\n throw new Error('CoinleyVanilla: apiSecret is required when using apiKey');\n }\n if (!config.apiUrl) {\n throw new Error('CoinleyVanilla: apiUrl is required');\n }\n\n // Store configuration with defaults\n this.config = {\n publicKey: config.publicKey || null,\n apiKey: config.apiKey || null,\n apiSecret: config.apiSecret || null,\n apiUrl: config.apiUrl.replace(/\\/$/, ''), // Remove trailing slash\n theme: config.theme || 'light',\n debug: config.debug || false,\n ...config\n };\n\n // Internal state\n this.isOpen = false;\n this.root = null;\n this.container = null;\n this.callbacks = {};\n this.currentPayment = null;\n\n // Log initialization\n if (this.config.debug) {\n }\n }\n\n /**\n * Open payment modal\n * @param {Object} paymentConfig - Payment configuration\n * @param {number} paymentConfig.amount - Payment amount (required)\n * @param {string} paymentConfig.customerEmail - Customer email (required)\n * @param {string} [paymentConfig.merchantName] - Merchant display name\n * @param {string} [paymentConfig.callbackUrl] - Webhook callback URL\n * @param {Object} paymentConfig.merchantWalletAddresses - Network-specific wallet addresses\n * @param {string} [paymentConfig.preferredNetwork] - Default network to select\n * @param {string} [paymentConfig.preferredCurrency] - Default token to select\n * @param {Object} [paymentConfig.metadata] - Custom metadata to attach\n * @param {Object} callbacks - Event callbacks\n * @param {Function} callbacks.onSuccess - Called when payment succeeds (paymentId, txHash, details)\n * @param {Function} callbacks.onError - Called when payment fails (error)\n * @param {Function} callbacks.onClose - Called when modal closes\n */\n open(paymentConfig, callbacks = {}) {\n // Check if already open\n if (this.isOpen) {\n return;\n }\n\n try {\n // Validate payment configuration\n this._validatePaymentConfig(paymentConfig);\n\n // Store callbacks and payment config\n this.callbacks = callbacks;\n this.currentPayment = paymentConfig;\n\n // Create container for React component\n this._createContainer();\n\n // Create React root and render component\n this.root = createRoot(this.container);\n this.isOpen = true;\n\n // Render payment component\n this.root.render(\n React.createElement(EnhancedSimpleCoinleyPayment, {\n publicKey: this.config.publicKey,\n apiKey: this.config.apiKey,\n apiSecret: this.config.apiSecret,\n apiUrl: this.config.apiUrl,\n isOpen: true,\n theme: this.config.theme,\n config: {\n amount: paymentConfig.amount,\n customerEmail: paymentConfig.customerEmail,\n merchantName: paymentConfig.merchantName || 'Merchant',\n callbackUrl: paymentConfig.callbackUrl || this._getDefaultCallbackUrl(),\n merchantWalletAddresses: paymentConfig.merchantWalletAddresses || {},\n preferredNetwork: paymentConfig.preferredNetwork,\n preferredCurrency: paymentConfig.preferredCurrency,\n metadata: {\n ...paymentConfig.metadata,\n source: 'vanilla-sdk',\n sdkVersion: '2.0.0',\n timestamp: new Date().toISOString()\n }\n },\n onSuccess: this._handleSuccess.bind(this),\n onError: this._handleError.bind(this),\n onClose: this._handleClose.bind(this)\n })\n );\n\n if (this.config.debug) {\n }\n\n } catch (error) {\n\n if (callbacks.onError) {\n callbacks.onError(error.message || 'Failed to open payment modal');\n }\n }\n }\n\n /**\n * Close payment modal programmatically\n */\n close() {\n if (!this.isOpen) {\n return;\n }\n\n this._cleanup();\n\n if (this.config.debug) {\n }\n }\n\n /**\n * Check if payment modal is currently open\n * @returns {boolean}\n */\n isPaymentOpen() {\n return this.isOpen;\n }\n\n /**\n * Update SDK configuration\n * @param {Object} newConfig - Configuration updates\n */\n updateConfig(newConfig) {\n this.config = { ...this.config, ...newConfig };\n\n if (this.config.debug) {\n }\n }\n\n /**\n * Get current configuration (read-only)\n * @returns {Object}\n */\n getConfig() {\n return { ...this.config };\n }\n\n /**\n * Get current payment details\n * @returns {Object|null}\n */\n getCurrentPayment() {\n return this.currentPayment ? { ...this.currentPayment } : null;\n }\n\n // ==================== PRIVATE METHODS ====================\n\n /**\n * Validate payment configuration\n * @private\n */\n _validatePaymentConfig(config) {\n if (!config) {\n throw new Error('Payment configuration is required');\n }\n\n if (!config.amount || typeof config.amount !== 'number' || config.amount <= 0) {\n throw new Error('Valid amount (number > 0) is required');\n }\n\n if (!config.customerEmail || typeof config.customerEmail !== 'string') {\n throw new Error('Customer email is required');\n }\n\n // Email format validation\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n if (!emailRegex.test(config.customerEmail)) {\n throw new Error('Invalid email format');\n }\n\n // Validate merchant wallet addresses if provided\n if (config.merchantWalletAddresses) {\n if (typeof config.merchantWalletAddresses !== 'object') {\n throw new Error('merchantWalletAddresses must be an object');\n }\n\n const walletCount = Object.keys(config.merchantWalletAddresses).length;\n if (walletCount === 0) {\n }\n }\n }\n\n /**\n * Create DOM container for payment modal\n * @private\n */\n _createContainer() {\n if (this.container) {\n return; // Already exists\n }\n\n this.container = document.createElement('div');\n this.container.id = 'coinley-payment-container';\n this.container.style.cssText = `\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 999999;\n `;\n\n document.body.appendChild(this.container);\n }\n\n /**\n * Get default callback URL\n * @private\n */\n _getDefaultCallbackUrl() {\n if (typeof window !== 'undefined') {\n return `${window.location.origin}/api/webhooks/coinley`;\n }\n return '';\n }\n\n /**\n * Handle successful payment\n * @private\n */\n _handleSuccess(paymentId, transactionHash, paymentDetails) {\n if (this.config.debug) {\n }\n\n if (this.callbacks.onSuccess) {\n this.callbacks.onSuccess(paymentId, transactionHash, paymentDetails);\n }\n\n // Don't auto-close - let component handle it or user calls close()\n }\n\n /**\n * Handle payment error\n * @private\n */\n _handleError(error) {\n if (this.config.debug) {\n }\n\n if (this.callbacks.onError) {\n this.callbacks.onError(error);\n }\n }\n\n /**\n * Handle modal close\n * @private\n */\n _handleClose() {\n this._cleanup();\n\n if (this.callbacks.onClose) {\n this.callbacks.onClose();\n }\n }\n\n /**\n * Cleanup resources\n * @private\n */\n _cleanup() {\n this.isOpen = false;\n\n // Unmount React component\n if (this.root) {\n try {\n this.root.unmount();\n } catch (error) {\n }\n this.root = null;\n }\n\n // Remove DOM container\n if (this.container && this.container.parentNode) {\n this.container.parentNode.removeChild(this.container);\n this.container = null;\n }\n\n // Clear current payment\n this.currentPayment = null;\n }\n}\n\n// Export as ES module\nexport default CoinleyVanilla;\n\n// Make available globally for vanilla JS/WordPress usage\nif (typeof window !== 'undefined') {\n window.CoinleyVanilla = CoinleyVanilla;\n\n // Auto-initialize from script tag data attributes\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', autoInitialize);\n } else {\n autoInitialize();\n }\n}\n\n/**\n * Auto-initialize from script tag attributes\n * @private\n */\nfunction autoInitialize() {\n const scripts = document.querySelectorAll('script[src*=\"coinley-vanilla\"]');\n\n scripts.forEach(script => {\n const publicKey = script.getAttribute('data-public-key');\n const apiKey = script.getAttribute('data-api-key');\n const apiSecret = script.getAttribute('data-api-secret');\n const apiUrl = script.getAttribute('data-api-url');\n const theme = script.getAttribute('data-theme') || 'light';\n const debug = script.hasAttribute('data-debug');\n\n // Support publicKey (new) or apiKey+apiSecret (legacy)\n if ((publicKey || (apiKey && apiSecret)) && apiUrl) {\n try {\n window.coinley = new CoinleyVanilla({\n publicKey,\n apiKey,\n apiSecret,\n apiUrl,\n theme,\n debug\n });\n\n } catch (error) {\n }\n }\n });\n}","// Payment QR Generator for Coinley SDK\n// Generates QR codes that point to the payment screen for split payments\n\nimport QRCode from 'qrcode';\n\nexport class PaymentQRGenerator {\n constructor(basePaymentUrl = 'https://paymentscreen.vercel.app/') {\n this.basePaymentUrl = basePaymentUrl.endsWith('/') ? basePaymentUrl : basePaymentUrl + '/';\n }\n\n /**\n * Generate a payment URL for QR code scanning\n * @param {Object} paymentData - Payment configuration\n * @param {string} paymentData.merchant - Merchant name\n * @param {number} paymentData.amount - Total amount\n * @param {number} paymentData.productAmount - Product amount (before fees)\n * @param {number} paymentData.platformFee - Platform fee\n * @param {number} paymentData.networkFee - Network fee\n * @param {string} paymentData.token - Token symbol (USDC, USDT, etc.)\n * @param {string} paymentData.network - Network name\n * @param {string} paymentData.merchantAddress - Smart contract address for split payment\n * @returns {string} - Payment URL for QR code\n */\n generatePaymentURL(paymentData) {\n const {\n merchant,\n amount,\n productAmount,\n platformFee,\n networkFee,\n token = 'USDC',\n network = 'Ethereum Mainnet',\n merchantAddress\n } = paymentData;\n\n // Validate required fields\n if (!merchant) throw new Error('Merchant name is required');\n if (!amount) throw new Error('Amount is required');\n if (!merchantAddress) throw new Error('Merchant address (smart contract) is required');\n\n // Auto-calculate fees if not provided\n const calculatedProductAmount = productAmount || (amount * 0.95);\n const calculatedPlatformFee = platformFee || (amount * 0.03);\n const calculatedNetworkFee = networkFee || (amount * 0.02);\n\n // Create URL parameters\n const params = new URLSearchParams({\n merchant: merchant,\n amount: amount.toString(),\n productAmount: calculatedProductAmount.toString(),\n platformFee: calculatedPlatformFee.toString(),\n networkFee: calculatedNetworkFee.toString(),\n token: token,\n network: network,\n merchantAddress: merchantAddress\n });\n\n return this.basePaymentUrl + '?' + params.toString();\n }\n\n /**\n * Generate QR code data URL for the payment\n * @param {Object} paymentData - Payment configuration\n * @param {Object} options - QR code options\n * @param {number} options.width - QR code width (default: 300)\n * @param {number} options.margin - QR code margin (default: 2)\n * @param {string} options.colorDark - Dark color (default: '#7c3aed')\n * @param {string} options.colorLight - Light color (default: '#ffffff')\n * @returns {Promise<string>} - QR code data URL\n */\n async generateQRCode(paymentData, options = {}) {\n const {\n width = 300,\n margin = 2,\n colorDark = '#7c3aed',\n colorLight = '#ffffff'\n } = options;\n\n try {\n const paymentURL = this.generatePaymentURL(paymentData);\n\n const qrCodeDataURL = await QRCode.toDataURL(paymentURL, {\n width,\n margin,\n color: {\n dark: colorDark,\n light: colorLight\n }\n });\n\n return {\n qrCodeDataURL,\n paymentURL,\n paymentData: {\n ...paymentData,\n qrCodeUrl: paymentURL\n }\n };\n } catch (error) {\n throw new Error(`Failed to generate QR code: ${error.message}`);\n }\n }\n\n /**\n * Generate QR code as canvas element\n * @param {Object} paymentData - Payment configuration\n * @param {HTMLCanvasElement} canvas - Canvas element to render to\n * @param {Object} options - QR code options\n * @returns {Promise<string>} - Payment URL\n */\n async generateQRCodeToCanvas(paymentData, canvas, options = {}) {\n const {\n width = 300,\n margin = 2,\n colorDark = '#7c3aed',\n colorLight = '#ffffff'\n } = options;\n\n try {\n const paymentURL = this.generatePaymentURL(paymentData);\n\n await QRCode.toCanvas(canvas, paymentURL, {\n width,\n margin,\n color: {\n dark: colorDark,\n light: colorLight\n }\n });\n\n return paymentURL;\n } catch (error) {\n throw new Error(`Failed to generate QR code to canvas: ${error.message}`);\n }\n }\n\n /**\n * Validate payment data structure\n * @param {Object} paymentData - Payment configuration to validate\n * @returns {Object} - Validation result\n */\n validatePaymentData(paymentData) {\n const errors = [];\n const warnings = [];\n\n // Required fields\n if (!paymentData.merchant) errors.push('Merchant name is required');\n if (!paymentData.amount || paymentData.amount <= 0) errors.push('Valid amount is required');\n if (!paymentData.merchantAddress) errors.push('Merchant address (smart contract) is required');\n\n // Address format validation\n if (paymentData.merchantAddress && !/^0x[a-fA-F0-9]{40}$/.test(paymentData.merchantAddress)) {\n errors.push('Invalid Ethereum address format for merchantAddress');\n }\n\n // Amount validation\n if (paymentData.amount > 10000) {\n warnings.push('Large payment amount detected');\n }\n\n // Fee validation\n const totalFees = (paymentData.platformFee || 0) + (paymentData.networkFee || 0);\n if (totalFees > paymentData.amount * 0.1) {\n warnings.push('High fees detected (>10% of total amount)');\n }\n\n return {\n isValid: errors.length === 0,\n errors,\n warnings\n };\n }\n\n /**\n * Create a comprehensive payment QR for SDK usage\n * @param {Object} config - Payment configuration from SDK\n * @returns {Promise<Object>} - Complete QR payment package\n */\n async createPaymentQR(config) {\n const {\n merchantName,\n amount,\n productAmount,\n platformFee,\n networkFee,\n token,\n network,\n merchantWalletAddresses,\n selectedNetwork = 'ethereum',\n ...otherConfig\n } = config;\n\n // Extract smart contract address from merchant wallet addresses\n const merchantAddress = merchantWalletAddresses?.[selectedNetwork] ||\n merchantWalletAddresses?.ethereum ||\n merchantWalletAddresses?.splitPaymentContract;\n\n const paymentData = {\n merchant: merchantName || 'Coinley Merchant',\n amount,\n productAmount,\n platformFee,\n networkFee,\n token: token || 'USDC',\n network: network || 'Ethereum Mainnet',\n merchantAddress,\n ...otherConfig\n };\n\n // Validate payment data\n const validation = this.validatePaymentData(paymentData);\n if (!validation.isValid) {\n throw new Error(`Payment validation failed: ${validation.errors.join(', ')}`);\n }\n\n // Generate QR code\n const qrResult = await this.generateQRCode(paymentData);\n\n return {\n ...qrResult,\n validation,\n instructions: {\n userAction: 'Scan this QR code with your mobile wallet to pay',\n expectedFlow: 'QR Scan → Payment Screen → Wallet Connect → Split Payment → Confirmation',\n supportedWallets: ['MetaMask', 'Trust Wallet', 'Coinbase Wallet', 'WalletConnect compatible wallets']\n }\n };\n }\n}\n\n// Default instance for easy usage\nexport const paymentQR = new PaymentQRGenerator();\n\n// Utility functions for quick access\nexport const generatePaymentQR = (paymentData, options) => {\n return paymentQR.generateQRCode(paymentData, options);\n};\n\nexport const generatePaymentURL = (paymentData) => {\n return paymentQR.generatePaymentURL(paymentData);\n};\n\nexport default PaymentQRGenerator;","\n// src/index.js - Updated to include vanilla exports\n\n// Original React exports (keep these for backward compatibility)\nexport {\n CoinleyProvider,\n CoinleyCheckout,\n ThemeProvider,\n useCoinley\n} from './CoinleyProvider';\n\nexport { PaymentAPI } from './PaymentAPI';\n\n\n// Keep the original simple component (working version)\n// export { default as SimpleCoinleyPayment } from './components/SimpleCoinleyPayment';\n\n// Enhanced component with modern design\nexport { default as EnhancedSimpleCoinleyPayment } from './components/EnhancedSimpleCoinleyPayment';\n\n// QR Code Payment component (supports both wallet and split payment modes)\nexport { default as QRCodePayment } from './components/QRCodePayment';\n\n// Simple provider for both components\nexport const SimpleCoinleyProvider = ({ children, ...props }) => children;\n\n// NEW: Vanilla JavaScript wrapper (for those who want to import it in React too)\nexport { default as CoinleyVanilla } from './vanilla/index';\n\n// NEW: Payment QR Generator for split payments\nexport {\n PaymentQRGenerator,\n paymentQR,\n generatePaymentQR,\n generatePaymentURL\n} from './utils/paymentQRGenerator';\n\n// Import styles\nimport './styles/index.css';\n\n// Version\nexport const VERSION = '0.0.26';\n\n// Utils (keep your existing utils)\nexport const utils = {\n formatAmount: (amount, decimals = 2) => amount.toFixed(decimals),\n\n truncateAddress: (address, startChars = 6, endChars = 4) => {\n if (!address) return '';\n if (address.length <= startChars + endChars) return address;\n return `${address.slice(0, startChars)}...${address.slice(-endChars)}`;\n },\n\n isValidAddress: (address, network) => {\n if (!address) return false;\n\n switch (network.toLowerCase()) {\n case 'ethereum':\n case 'bsc':\n case 'polygon':\n return /^0x[a-fA-F0-9]{40}$/.test(address);\n case 'tron':\n return /^T[a-zA-Z0-9]{33}$/.test(address);\n case 'solana':\n return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);\n default:\n return address.length > 0;\n }\n },\n\n copyToClipboard: async (text) => {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n return false;\n }\n }\n};\n\n// Error classes\nexport class CoinleyError extends Error {\n constructor(message, code) {\n super(message);\n this.name = 'CoinleyError';\n this.code = code;\n }\n}\n\n// Default config\nexport const DEFAULT_CONFIG = {\n theme: 'light',\n debug: false,\n testMode: false,\n autoOpen: false\n};\n\n// Usage examples for documentation\nexport const USAGE_EXAMPLES = {\n // React usage with new publicKey (recommended)\n 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 `,\n\n // Vanilla JavaScript usage\n vanilla: `\n<!-- Include via CDN -->\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 `\n};\n"],"names":["mainnet","bsc","polygon","arbitrum","optimism","avalanche","celo","base","SimplePaymentAPI","_a","_b","error","size","encoder","toBytes","size_","formatAuthorizationList","isLE","_32n","sha256","sha256n","noble_sha256","version","serializeTransaction","blobs","commitments","proofs","v","formatters","serializeTransaction_","serializers","chainConfig","sourceId","serializeTransaction_op","wagmiConfig","http","fallback","splitPaymentHash","gasFees","selectedToken","paymentData","selectedNetwork","generateQRPaymentURI","generateMobilePaymentDeepLink","token","CoinleyPayment","formatUnits"],"mappings":";;;;;;;;;;;;AAAA,MAAA,OAAe;ACMf,MAAM,0BAA0B;AAChC,MAAM,4BAA4B;AAGlC,MAAM,uBAAuB;AAC7B,QAAQ,IAAI,+BAA+B,o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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqCX;","x_google_ignoreList":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78]}