@zubari/sdk 0.3.3 → 0.3.4

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,"sources":["../../src/config/contracts.ts","../../src/services/SwapService.ts","../../src/services/WdkApiClient.ts","../../src/services/ZubariApiClient.ts","../../src/services/BrowserAddressDerivation.ts","../../src/services/ZubariWdkService.ts","../../src/services/TransactionService.ts"],"names":["DEFAULT_API_URL","HDNodeWallet","mnemonicToSeedSync","HDKey","ripemd160","sha256","bech32","base58check","validateMnemonic","wordlist","generateMnemonic","dynamicImport"],"mappings":";;;;;;;;;;;;;;;;;AAqDO,IAAM,eAAA,GAAkB;AAAA,EAId;AAAA,EAEf,kBAAA,EAAoB,EAAA;AAAA,EAEgB;AAAA,EAEpC,kBAAkB,EAAA,GAAK;AACzB,CAAA;;;AC5DA,IAAM,iBAAA,GAAoB;AAAA,EACxB,OAAA,EAAS;AAAA,IACP,UAAA,EAAY,4CAAA;AAAA,IACZ,MAAA,EAAQ,4CAAA;AAAA,IACR,OAAA,EAAS;AAAA,GACX;AAAA,EACA,OAAA,EAAS;AAAA,IACP,UAAA,EAAY,4CAAA;AAAA,IACZ,MAAA,EAAQ,4CAAA;AAAA,IACR,OAAA,EAAS;AAAA;AAEb,CAAA;AAGA,IAAM,iBAAA,GAAoB;AAAA,EACxB,qBAAA,EAAuB,YAAA;AAAA;AAAA,EACvB,gBAAA,EAAkB;AAAA;AACpB,CAAA;AAGA,IAAM,MAAA,GAAS;AAAA,EACb,OAAA,EAAS;AAAA,IACP,IAAA,EAAM,4CAAA;AAAA,IACN,IAAA,EAAM,4CAAA;AAAA,IACN,IAAA,EAAM;AAAA,GACR;AAAA,EACA,OAAA,EAAS;AAAA,IACP,IAAA,EAAM,4CAAA;AAAA,IACN,IAAA,EAAM,4CAAA;AAAA,IACN,IAAA,EAAM;AAAA;AAEV,CAAA;AAGA,IAAM,WAAA,GAAc,4CAAA;AAQb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B,MAAM,CAAA;AAAA,EAC5D;AACA,EAAA,OAAO,0BAAA;AACT;AAKO,SAAS,yBAAyB,MAAA,EAAgE;AACvG,EAAA,OAAO,IAAI,mBAAmB,MAAM,CAAA;AACtC","file":"index.js","sourcesContent":["// Contract addresses for Zubari ecosystem\nexport interface ContractAddresses {\n registry: string;\n nft: string;\n nft1155: string; // ERC-1155 multi-edition NFT\n marketplace: string;\n tips: string;\n subscriptions: string;\n payouts: string;\n entryPoint: string;\n paymaster: string;\n accountFactory: string;\n usdt: string;\n weth: string;\n}\n\n// Zero address for ETH payments and placeholder addresses\nexport const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';\n\nexport const ZUBARI_CONTRACTS: Record<'testnet' | 'mainnet', ContractAddresses> = {\n testnet: {\n // Ethereum Sepolia (11155111) - Deployed 2024-12-31\n registry: '0xe5CE1Eb986f58BE42EEDFe5C18ee5956803b2BDC',\n nft: '0xc165b8C6843e8f0B1489525D0f853d23f22c677B', // ZubariNFT ERC-721 with payment\n nft1155: '0x5e618B5bEaE1dc41369E7aa235Cc3b9245905192', // Zubari1155 ERC-1155 multi-edition\n marketplace: '0xfcEfDa6C73aC357b8695E5F8F8d17820750BF207',\n tips: '0x86a9A306C7fCC9e0B8cd6859f6f15498d0046BB7',\n subscriptions: '0xaB7F17A85F61d9ab9f96bCB4e73e910D019978F7',\n payouts: '0x8aaB23Fb2a83A259E965Aae8Ee0938b1400B7E6b',\n entryPoint: '0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789',\n paymaster: ZERO_ADDRESS, // Deploy with: npx hardhat run deploy/deploy.ts --network ethereum-sepolia\n accountFactory: ZERO_ADDRESS, // Not yet deployed\n usdt: '0xaA8E23Fb1079EA71e0a56F48a2aA51851D8433D0', // USDT on Sepolia\n weth: '0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14',\n },\n mainnet: {\n // Ethereum Mainnet (1)\n registry: ZERO_ADDRESS,\n nft: ZERO_ADDRESS,\n nft1155: ZERO_ADDRESS,\n marketplace: ZERO_ADDRESS,\n tips: ZERO_ADDRESS,\n subscriptions: ZERO_ADDRESS,\n payouts: ZERO_ADDRESS,\n entryPoint: '0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789',\n paymaster: ZERO_ADDRESS,\n accountFactory: ZERO_ADDRESS,\n usdt: '0xdAC17F958D2ee523a2206206994597C13D831ec7', // USDT on Ethereum\n weth: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n },\n};\n\n// Platform configuration\nexport const PLATFORM_CONFIG = {\n // Platform fee in basis points (300 = 3%)\n tipFeeBps: 300,\n // Maximum royalty in basis points (1000 = 10%)\n maxRoyaltyBps: 1000,\n // Default slippage tolerance for swaps (50 = 0.5%)\n defaultSlippageBps: 50,\n // Voucher validity in seconds (30 days)\n voucherValiditySecs: 30 * 24 * 60 * 60,\n // Swap deadline in seconds (30 minutes)\n swapDeadlineSecs: 30 * 60,\n} as const;\n\n// EIP-712 Domain for lazy minting\nexport const NFT_VOUCHER_DOMAIN = {\n name: 'ZubariNFT',\n version: '1',\n} as const;\n\nexport const NFT_VOUCHER_TYPES = {\n NFTVoucher: [\n { name: 'tokenId', type: 'bytes32' },\n { name: 'uri', type: 'string' },\n { name: 'creator', type: 'address' },\n { name: 'royaltyBps', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n // Pricing fields\n { name: 'price', type: 'uint256' },\n { name: 'currency', type: 'address' },\n { name: 'nonce', type: 'uint256' },\n // Watermarking fields\n { name: 'contentHash', type: 'bytes32' },\n { name: 'userId', type: 'bytes32' },\n { name: 'watermarkTimestamp', type: 'uint256' },\n { name: 'sessionId', type: 'bytes32' },\n ],\n} as const;\n\n// EIP-712 Domain for ERC-1155 edition minting\nexport const EDITION_VOUCHER_DOMAIN = {\n name: 'Zubari1155',\n version: '1',\n} as const;\n\n// EIP-712 Types for EditionVoucher (ERC-1155)\nexport const EDITION_VOUCHER_TYPES = {\n EditionVoucher: [\n { name: 'tokenId', type: 'bytes32' },\n { name: 'uri', type: 'string' },\n { name: 'creator', type: 'address' },\n { name: 'maxSupply', type: 'uint256' },\n { name: 'royaltyBps', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n ],\n} as const;\n\n// Currency addresses per network\nexport const CURRENCY_ADDRESSES = {\n testnet: {\n ETH: ZERO_ADDRESS,\n USDT: '0xaA8E23Fb1079EA71e0a56F48a2aA51851D8433D0', // USDT on Sepolia\n },\n mainnet: {\n ETH: ZERO_ADDRESS,\n USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7', // USDT on Ethereum\n },\n} as const;\n\nexport function getContractAddresses(network: 'testnet' | 'mainnet'): ContractAddresses {\n return ZUBARI_CONTRACTS[network];\n}\n\n// Multi-chain Fee/Treasury Wallet Addresses\n// These wallets receive platform fees from transactions on their respective chains\nexport interface FeeWalletConfig {\n address: string;\n name: string;\n network: string;\n chainId?: number;\n}\n\nexport type SupportedFeeChain = 'ETH' | 'BTC' | 'SOLANA' | 'TON' | 'TRON';\n\n/**\n * Mainnet Fee Wallet Addresses\n * These are the production treasury wallets for collecting platform fees\n */\nexport const MAINNET_FEE_WALLETS: Record<SupportedFeeChain, FeeWalletConfig> = {\n // Ethereum (ETH, ERC-20 tokens like USDT)\n ETH: {\n address: '0x40Df60a57d02a7bB04B6624c65E2908Cc006badE',\n name: 'Zubari ETH Treasury',\n network: 'ethereum',\n chainId: 1,\n },\n // Bitcoin\n BTC: {\n address: 'bc1qh20fx23wk34pcm3zp0v9wctwprtl02uvh6q9qj',\n name: 'Zubari BTC Treasury',\n network: 'bitcoin',\n },\n // Solana (SOL, SPL tokens)\n SOLANA: {\n address: '2hXGumVRpD5KgdqNZUuYJ2YoyLR6jc8mvWbubciWjPuZ',\n name: 'Zubari Solana Treasury',\n network: 'solana',\n },\n // TON (The Open Network)\n TON: {\n address: 'UQB5hOrm9YGoKjrCVmvAUFgmApkvKWqVMROjieKs3z4kDz99',\n name: 'Zubari TON Treasury',\n network: 'ton',\n },\n // Tron (TRX, TRC-20 tokens like USDT)\n TRON: {\n address: 'TVBPjQFNe8JgVctDKWMxJNgjbPZoP6uu5h',\n name: 'Zubari Tron Treasury',\n network: 'tron',\n },\n} as const;\n\n/**\n * Testnet Fee Wallet Addresses\n * These are used for development and testing\n */\nexport const TESTNET_FEE_WALLETS: Record<SupportedFeeChain, FeeWalletConfig> = {\n // Ethereum Sepolia\n ETH: {\n address: ZERO_ADDRESS, // Configure via environment\n name: 'Zubari ETH Testnet Treasury',\n network: 'sepolia',\n chainId: 11155111,\n },\n // Bitcoin Testnet\n BTC: {\n address: '',\n name: 'Zubari BTC Testnet Treasury',\n network: 'bitcoin-testnet',\n },\n // Solana Devnet\n SOLANA: {\n address: '',\n name: 'Zubari Solana Devnet Treasury',\n network: 'solana-devnet',\n },\n // TON Testnet\n TON: {\n address: '',\n name: 'Zubari TON Testnet Treasury',\n network: 'ton-testnet',\n },\n // Tron Shasta Testnet\n TRON: {\n address: '',\n name: 'Zubari Tron Testnet Treasury',\n network: 'tron-shasta',\n },\n} as const;\n\n/**\n * Get fee wallet address for a specific chain\n * @param chain - The blockchain network\n * @param isMainnet - Whether to use mainnet addresses (default: false for testnet)\n */\nexport function getFeeWallet(chain: SupportedFeeChain, isMainnet: boolean = false): FeeWalletConfig {\n return isMainnet ? MAINNET_FEE_WALLETS[chain] : TESTNET_FEE_WALLETS[chain];\n}\n\n/**\n * Get all fee wallets for a network type\n * @param isMainnet - Whether to use mainnet addresses\n */\nexport function getAllFeeWallets(isMainnet: boolean = false): Record<SupportedFeeChain, FeeWalletConfig> {\n return isMainnet ? MAINNET_FEE_WALLETS : TESTNET_FEE_WALLETS;\n}\n","import type { SwapQuote, TxResult, TokenInfo } from '../types';\nimport { PLATFORM_CONFIG, getContractAddresses } from '../config/contracts';\n\n// Uniswap V3 contract addresses (Ethereum mainnet)\nconst UNISWAP_ADDRESSES = {\n mainnet: {\n swapRouter: '0xE592427A0AEce92De3Edee1F18E0157C05861564',\n quoter: '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6',\n factory: '0x1F98431c8aD98523631AE4a59f267346ea31F984',\n },\n sepolia: {\n swapRouter: '0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48E',\n quoter: '0xEd1f6473345F45b75F8179591dd5bA1888cf2FB3',\n factory: '0x0227628f3F023bb0B980b67D528571c95c6DaC1c',\n },\n};\n\n// Uniswap V3 function selectors\nconst UNISWAP_SELECTORS = {\n quoteExactInputSingle: '0xf7729d43', // quoteExactInputSingle(address,address,uint24,uint256,uint160)\n exactInputSingle: '0x414bf389', // exactInputSingle((address,address,uint24,address,uint256,uint256,uint256,uint160))\n};\n\n// Common token addresses\nconst TOKENS = {\n mainnet: {\n WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n USDC: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n },\n sepolia: {\n WETH: '0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14',\n USDT: '0x7169D38820dfd117C3FA1f22a697dBA58d90BA06',\n USDC: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',\n },\n};\n\n// Zero address for native ETH\nconst ETH_ADDRESS = '0x0000000000000000000000000000000000000000';\n\n/**\n * SwapService - DEX integration via Uniswap V3\n *\n * Handles token swaps with slippage protection,\n * quote fetching, and earnings conversion.\n */\nexport class SwapService {\n private readonly chainId: number;\n private readonly isTestnet: boolean;\n private readonly addresses: typeof UNISWAP_ADDRESSES.mainnet;\n private readonly tokens: typeof TOKENS.mainnet;\n\n constructor(chainId: number, isTestnet: boolean = false) {\n this.chainId = chainId;\n this.isTestnet = isTestnet;\n this.addresses = isTestnet ? UNISWAP_ADDRESSES.sepolia : UNISWAP_ADDRESSES.mainnet;\n this.tokens = isTestnet ? TOKENS.sepolia : TOKENS.mainnet;\n }\n\n /**\n * Get a swap quote from Uniswap V3 Quoter\n */\n async getQuote(\n tokenIn: string,\n tokenOut: string,\n amountIn: bigint,\n provider?: { call: (tx: object) => Promise<string> }\n ): Promise<SwapQuote> {\n if (amountIn <= 0n) {\n throw new Error('Amount must be greater than 0');\n }\n\n // Convert ETH address to WETH\n const actualTokenIn = tokenIn === ETH_ADDRESS ? this.tokens.WETH : tokenIn;\n const actualTokenOut = tokenOut === ETH_ADDRESS ? this.tokens.WETH : tokenOut;\n\n if (!provider) {\n // Return estimate without actual quote\n console.warn('No provider for quote, returning estimate');\n return {\n tokenIn,\n tokenOut,\n amountIn,\n amountOut: amountIn * BigInt(95) / BigInt(100), // Rough estimate\n priceImpact: 0.5,\n route: [tokenIn, tokenOut],\n estimatedGas: BigInt(150000),\n };\n }\n\n try {\n // Encode quoteExactInputSingle call\n // quoteExactInputSingle(address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96)\n const encodedTokenIn = actualTokenIn.toLowerCase().replace('0x', '').padStart(64, '0');\n const encodedTokenOut = actualTokenOut.toLowerCase().replace('0x', '').padStart(64, '0');\n const encodedFee = (3000).toString(16).padStart(64, '0'); // 0.3% fee tier\n const encodedAmountIn = amountIn.toString(16).padStart(64, '0');\n const encodedSqrtPriceLimit = '0'.padStart(64, '0'); // No price limit\n\n const data = `${UNISWAP_SELECTORS.quoteExactInputSingle}${encodedTokenIn}${encodedTokenOut}${encodedFee}${encodedAmountIn}${encodedSqrtPriceLimit}`;\n\n const result = await provider.call({\n to: this.addresses.quoter,\n data,\n });\n\n // Decode the result (uint256 amountOut)\n const amountOut = BigInt(result);\n\n // Calculate price impact\n const priceImpact = this.calculatePriceImpact(amountIn, amountOut, tokenIn, tokenOut);\n\n return {\n tokenIn,\n tokenOut,\n amountIn,\n amountOut,\n priceImpact,\n route: [tokenIn, tokenOut],\n estimatedGas: BigInt(150000),\n };\n } catch (error) {\n console.error('Failed to get quote:', error);\n throw new Error(`Quote failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n\n /**\n * Execute a swap with slippage protection via Uniswap V3 SwapRouter\n */\n async executeSwap(\n quote: SwapQuote,\n signer: { sendTransaction: (tx: object) => Promise<{ hash: string }> },\n recipient: string,\n slippageToleranceBps: number = PLATFORM_CONFIG.defaultSlippageBps\n ): Promise<TxResult> {\n // Calculate minimum output with slippage\n const minAmountOut = quote.amountOut - (quote.amountOut * BigInt(slippageToleranceBps)) / BigInt(10000);\n\n // Calculate deadline\n const deadline = Math.floor(Date.now() / 1000) + PLATFORM_CONFIG.swapDeadlineSecs;\n\n // Warn if price impact is high\n if (quote.priceImpact > 5) {\n console.warn(`High price impact: ${quote.priceImpact}%`);\n }\n\n // Convert ETH address to WETH for router\n const actualTokenIn = quote.tokenIn === ETH_ADDRESS ? this.tokens.WETH : quote.tokenIn;\n const actualTokenOut = quote.tokenOut === ETH_ADDRESS ? this.tokens.WETH : quote.tokenOut;\n const isETHIn = quote.tokenIn === ETH_ADDRESS;\n\n try {\n // Encode exactInputSingle call\n // struct ExactInputSingleParams {\n // address tokenIn;\n // address tokenOut;\n // uint24 fee;\n // address recipient;\n // uint256 deadline;\n // uint256 amountIn;\n // uint256 amountOutMinimum;\n // uint160 sqrtPriceLimitX96;\n // }\n const encodedTokenIn = actualTokenIn.toLowerCase().replace('0x', '').padStart(64, '0');\n const encodedTokenOut = actualTokenOut.toLowerCase().replace('0x', '').padStart(64, '0');\n const encodedFee = (3000).toString(16).padStart(64, '0');\n const encodedRecipient = recipient.toLowerCase().replace('0x', '').padStart(64, '0');\n const encodedDeadline = deadline.toString(16).padStart(64, '0');\n const encodedAmountIn = quote.amountIn.toString(16).padStart(64, '0');\n const encodedMinAmountOut = minAmountOut.toString(16).padStart(64, '0');\n const encodedSqrtPriceLimit = '0'.padStart(64, '0');\n\n const data = `${UNISWAP_SELECTORS.exactInputSingle}${encodedTokenIn}${encodedTokenOut}${encodedFee}${encodedRecipient}${encodedDeadline}${encodedAmountIn}${encodedMinAmountOut}${encodedSqrtPriceLimit}`;\n\n const tx = await signer.sendTransaction({\n to: this.addresses.swapRouter,\n data,\n value: isETHIn ? `0x${quote.amountIn.toString(16)}` : '0x0',\n });\n\n return {\n hash: tx.hash,\n network: 'ethereum',\n status: 'pending',\n metadata: {\n tokenIn: quote.tokenIn,\n tokenOut: quote.tokenOut,\n amountIn: quote.amountIn.toString(),\n minAmountOut: minAmountOut.toString(),\n deadline,\n },\n };\n } catch (error) {\n console.error('Failed to execute swap:', error);\n throw new Error(`Swap failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n\n /**\n * Convert earnings to USDT, keeping some ETH for gas\n */\n async convertEarningsToStable(\n ethBalance: bigint,\n signer: { sendTransaction: (tx: object) => Promise<{ hash: string }> },\n recipient: string,\n provider?: { call: (tx: object) => Promise<string> },\n reserveForGas: bigint = BigInt('10000000000000000') // 0.01 ETH\n ): Promise<TxResult> {\n const amountToSwap = ethBalance - reserveForGas;\n\n if (amountToSwap <= 0n) {\n throw new Error('Insufficient balance after gas reserve');\n }\n\n // Get quote for ETH -> USDT\n const quote = await this.getQuote(\n ETH_ADDRESS,\n this.tokens.USDT,\n amountToSwap,\n provider\n );\n\n return this.executeSwap(quote, signer, recipient);\n }\n\n /**\n * Check if a swap route exists\n */\n async hasRoute(\n tokenIn: string,\n tokenOut: string,\n provider?: { call: (tx: object) => Promise<string> }\n ): Promise<boolean> {\n try {\n const quote = await this.getQuote(tokenIn, tokenOut, BigInt(10 ** 18), provider);\n return quote.amountOut > 0n;\n } catch {\n return false;\n }\n }\n\n /**\n * Get supported tokens for swapping\n */\n async getSupportedTokens(): Promise<TokenInfo[]> {\n return [\n { address: ETH_ADDRESS, symbol: 'ETH', decimals: 18, name: 'Ether' },\n { address: this.tokens.WETH, symbol: 'WETH', decimals: 18, name: 'Wrapped Ether' },\n { address: this.tokens.USDT, symbol: 'USDT', decimals: 6, name: 'Tether USD' },\n { address: this.tokens.USDC, symbol: 'USDC', decimals: 6, name: 'USD Coin' },\n ];\n }\n\n /**\n * Get Uniswap router address for approvals\n */\n getRouterAddress(): string {\n return this.addresses.swapRouter;\n }\n\n /**\n * Calculate price impact (simplified)\n */\n private calculatePriceImpact(\n amountIn: bigint,\n amountOut: bigint,\n _tokenIn: string,\n _tokenOut: string\n ): number {\n // Simplified price impact calculation\n // In production, would compare to oracle price\n if (amountIn === 0n || amountOut === 0n) return 0;\n\n // Assume 1:1 ratio for ETH:stablecoin as baseline\n // Real implementation would use price feeds\n const expectedOut = amountIn; // Simplified\n const actualRatio = Number(amountOut) / Number(expectedOut);\n const impact = (1 - actualRatio) * 100;\n\n return Math.max(0, impact);\n }\n}\n","/**\n * WDK API Client\n *\n * Client for calling the backend WDK endpoints to derive addresses\n * using Tether WDK (which runs server-side in Node.js).\n */\n\nimport type { NetworkType } from '../types';\n\nexport interface WdkApiConfig {\n baseUrl: string;\n timeout?: number;\n}\n\nexport interface DeriveAddressResponse {\n success: boolean;\n address?: string;\n chain?: string;\n path?: string;\n network?: string;\n error?: string;\n}\n\nexport interface DeriveAllAddressesResponse {\n success: boolean;\n addresses?: {\n ethereum: string | null;\n bitcoin: string | null;\n ton: string | null;\n tron: string | null;\n solana: string | null;\n spark: string | null;\n };\n network?: string;\n error?: string;\n}\n\nexport interface ValidateSeedResponse {\n success: boolean;\n isValid?: boolean;\n wordCount?: number;\n error?: string;\n}\n\nexport interface GenerateSeedResponse {\n success: boolean;\n seed?: string;\n wordCount?: number;\n error?: string;\n}\n\nexport interface TransactionHistoryItem {\n hash: string;\n from: string;\n to: string;\n value: string;\n timestamp: number;\n status: 'confirmed' | 'pending' | 'failed';\n blockNumber?: number;\n}\n\nexport interface TransactionHistoryResponse {\n success: boolean;\n address?: string;\n transactions?: TransactionHistoryItem[];\n chain?: string;\n network?: string;\n error?: string;\n}\n\nexport interface SendTransactionResponse {\n success: boolean;\n txHash?: string;\n from?: string;\n to?: string;\n amount?: string;\n chain?: string;\n network?: string;\n error?: string;\n}\n\nexport interface TransactionStatusResponse {\n success: boolean;\n hash?: string;\n status?: 'confirmed' | 'pending' | 'failed';\n blockNumber?: number;\n confirmations?: number;\n timestamp?: number;\n from?: string;\n to?: string;\n value?: string;\n fee?: string;\n chain?: string;\n network?: string;\n error?: string;\n}\n\n/**\n * WDK API Client for server-side Tether WDK integration\n */\nexport class WdkApiClient {\n private config: Required<WdkApiConfig>;\n\n constructor(config: WdkApiConfig) {\n this.config = {\n baseUrl: config.baseUrl,\n timeout: config.timeout || 30000,\n };\n }\n\n /**\n * Generate a new BIP-39 seed phrase using Tether WDK\n */\n async generateSeed(): Promise<GenerateSeedResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/generate-seed`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to generate seed',\n };\n }\n }\n\n /**\n * Validate a BIP-39 seed phrase\n */\n async validateSeed(seed: string): Promise<ValidateSeedResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/validate-seed`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ seed }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to validate seed',\n };\n }\n }\n\n /**\n * Derive address for a specific chain using Tether WDK\n */\n async deriveAddress(\n seed: string,\n chain: NetworkType,\n network: 'mainnet' | 'testnet' = 'testnet'\n ): Promise<DeriveAddressResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-address`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ seed, chain, network }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to derive address',\n };\n }\n }\n\n /**\n * Derive addresses for all chains using Tether WDK\n */\n async deriveAllAddresses(\n seed: string,\n network: 'mainnet' | 'testnet' = 'testnet'\n ): Promise<DeriveAllAddressesResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-all`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ seed, network }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to derive addresses',\n };\n }\n }\n\n /**\n * Send a transaction on a specific chain using Tether WDK\n */\n async sendTransaction(\n seed: string,\n chain: NetworkType,\n to: string,\n amount: string,\n network: 'mainnet' | 'testnet' = 'testnet'\n ): Promise<SendTransactionResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/send`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ seed, chain, to, amount, network }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to send transaction',\n };\n }\n }\n\n /**\n * Get transaction history for an address on a specific chain\n * Fetches from blockchain explorers (Etherscan, mempool.space, etc.)\n */\n async getTransactionHistory(\n seed: string,\n chain: NetworkType,\n network: 'mainnet' | 'testnet' = 'testnet',\n limit: number = 10\n ): Promise<TransactionHistoryResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/history`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ seed, chain, network, limit }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get transaction history',\n };\n }\n }\n\n /**\n * Get transaction status by hash\n * Fetches from blockchain explorers to check confirmation status\n */\n async getTransactionStatus(\n txHash: string,\n chain: NetworkType,\n network: 'mainnet' | 'testnet' = 'testnet'\n ): Promise<TransactionStatusResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/tx-status`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ txHash, chain, network }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get transaction status',\n };\n }\n }\n}\n\n// Default API URL (can be overridden)\n// Uses the Zubari production API which has Tether WDK integrated\nconst DEFAULT_API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://ckgwifsxka.us-east-2.awsapprunner.com';\n\n// Singleton instance\nlet wdkApiClient: WdkApiClient | null = null;\n\n/**\n * Get or create the WDK API client instance\n */\nexport function getWdkApiClient(baseUrl?: string): WdkApiClient {\n if (!wdkApiClient || (baseUrl && wdkApiClient['config'].baseUrl !== baseUrl)) {\n wdkApiClient = new WdkApiClient({\n baseUrl: baseUrl || DEFAULT_API_URL,\n });\n }\n return wdkApiClient;\n}\n","/**\n * Zubari API Client\n *\n * Comprehensive client for interacting with the Zubari backend API.\n * Includes NFT, Marketplace, Tips, and Subscription operations.\n */\n\nimport type { NetworkType, NFTCurrency } from '../types';\n\nexport interface ZubariApiConfig {\n baseUrl: string;\n timeout?: number;\n authToken?: string;\n}\n\n// ============ NFT Types ============\n\nexport interface NFTVoucher {\n tokenId: string;\n uri: string;\n creator: string;\n royaltyBps: number;\n deadline: number;\n signature: string;\n price: string;\n currency: string;\n nonce: number;\n contentHash?: string;\n userId?: string;\n watermarkTimestamp?: number;\n sessionId?: string;\n}\n\nexport interface CreateVoucherRequest {\n creatorAddress: string;\n price: string;\n currency: NFTCurrency;\n}\n\nexport interface CreateVoucherResponse {\n success: boolean;\n voucher?: NFTVoucher;\n signature?: string;\n nftId?: string;\n error?: string;\n}\n\nexport interface RedeemVoucherRequest {\n buyerAddress: string;\n paymentTxHash?: string;\n}\n\nexport interface RedeemVoucherResponse {\n success: boolean;\n transactionHash?: string;\n tokenId?: string;\n owner?: string;\n nftId?: string;\n error?: string;\n}\n\nexport interface VoucherStatusResponse {\n success: boolean;\n nftId?: string;\n hasVoucher?: boolean;\n isRedeemed?: boolean;\n voucher?: NFTVoucher;\n error?: string;\n}\n\nexport interface NFTResponse {\n id: string;\n tokenId?: string;\n contractAddress?: string;\n name: string;\n description?: string;\n imageUrl?: string;\n animationUrl?: string;\n externalUrl?: string;\n attributes?: Array<{\n trait_type: string;\n value: string | number;\n }>;\n creatorId: string;\n ownerId: string;\n price?: string;\n currency?: string;\n royaltyBps: number;\n isLazyMinted: boolean;\n isMinted: boolean;\n mintedAt?: string;\n transactionHash?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface CreateNFTRequest {\n name: string;\n description?: string;\n price: string;\n currency: NFTCurrency;\n royaltyBps?: number;\n attributes?: Array<{\n trait_type: string;\n value: string | number;\n }>;\n externalUrl?: string;\n}\n\nexport interface NFTListResponse {\n success: boolean;\n nfts?: NFTResponse[];\n pagination?: {\n page: number;\n limit: number;\n total: number;\n pages: number;\n };\n error?: string;\n}\n\n// ============ Marketplace Types ============\n\nexport interface MarketListing {\n id: string;\n nftId: string;\n nft?: NFTResponse;\n sellerId: string;\n sellerAddress: string;\n price: string;\n currency: string;\n expiresAt: string;\n status: 'ACTIVE' | 'SOLD' | 'CANCELLED' | 'EXPIRED';\n transactionHash?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ListItemRequest {\n nftId: string;\n price: string;\n currency: NFTCurrency;\n duration?: number; // Duration in seconds, default 7 days\n}\n\nexport interface ListItemResponse {\n success: boolean;\n listing?: MarketListing;\n transactionHash?: string;\n error?: string;\n}\n\nexport interface BuyItemRequest {\n listingId: string;\n buyerAddress: string;\n}\n\nexport interface BuyItemResponse {\n success: boolean;\n transactionHash?: string;\n tokenId?: string;\n newOwner?: string;\n error?: string;\n}\n\nexport interface CancelListingRequest {\n listingId: string;\n}\n\nexport interface CancelListingResponse {\n success: boolean;\n transactionHash?: string;\n error?: string;\n}\n\nexport interface UpdatePriceRequest {\n listingId: string;\n newPrice: string;\n}\n\nexport interface UpdatePriceResponse {\n success: boolean;\n listing?: MarketListing;\n transactionHash?: string;\n error?: string;\n}\n\nexport interface ListingsResponse {\n success: boolean;\n listings?: MarketListing[];\n pagination?: {\n page: number;\n limit: number;\n total: number;\n pages: number;\n };\n error?: string;\n}\n\nexport interface MarketStatsResponse {\n success: boolean;\n stats?: {\n totalListings: number;\n activeListings: number;\n totalVolume: string;\n totalSales: number;\n averagePrice: string;\n topSellers: Array<{\n address: string;\n sales: number;\n volume: string;\n }>;\n };\n error?: string;\n}\n\n// ============ Filter Types ============\n\nexport interface NFTFilters {\n creatorId?: string;\n ownerId?: string;\n isLazyMinted?: boolean;\n isMinted?: boolean;\n minPrice?: string;\n maxPrice?: string;\n currency?: NFTCurrency;\n page?: number;\n limit?: number;\n}\n\nexport interface ListingFilters {\n sellerId?: string;\n status?: 'ACTIVE' | 'SOLD' | 'CANCELLED' | 'EXPIRED';\n minPrice?: string;\n maxPrice?: string;\n currency?: NFTCurrency;\n sortBy?: 'price' | 'createdAt' | 'expiresAt';\n sortOrder?: 'asc' | 'desc';\n page?: number;\n limit?: number;\n}\n\n// ============ Tips Types ============\n\nexport interface TipUser {\n id: string;\n username?: string;\n displayName?: string;\n avatarUrl?: string;\n}\n\nexport interface Tip {\n id: string;\n senderId: string;\n recipientId?: string;\n senderAddress: string;\n recipientAddress: string;\n tokenAddress?: string;\n amount: string;\n amountUsd?: string;\n platformFee: string;\n message?: string;\n network: string;\n transactionHash?: string;\n status: 'PENDING' | 'CONFIRMED' | 'FAILED';\n createdAt: string;\n sender?: TipUser;\n recipient?: TipUser;\n}\n\nexport interface SendTipRequest {\n recipientAddress: string;\n recipientUsername?: string;\n amount: string;\n tokenAddress?: string;\n network?: string;\n message?: string;\n transactionHash?: string;\n}\n\nexport interface SendTipResponse {\n success: boolean;\n message?: string;\n tip?: Tip;\n platformFee?: string;\n platformFeeBps?: number;\n error?: string;\n}\n\nexport interface TipStatsResponse {\n success: boolean;\n sent?: {\n count: number;\n totalAmount: string;\n totalAmountUsd: string;\n };\n received?: {\n count: number;\n totalAmount: string;\n totalAmountUsd: string;\n platformFees: string;\n };\n error?: string;\n}\n\nexport interface TipsListResponse {\n success: boolean;\n tips?: Tip[];\n pagination?: {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n };\n totals?: {\n count: number;\n amount: string;\n amountUsd: string;\n };\n error?: string;\n}\n\nexport interface TipFilters {\n page?: number;\n limit?: number;\n status?: 'PENDING' | 'CONFIRMED' | 'FAILED';\n}\n\nexport interface UpdateTipStatusRequest {\n status: 'PENDING' | 'CONFIRMED' | 'FAILED';\n transactionHash?: string;\n}\n\n// ============ Subscription Types ============\n\nexport interface SubscriptionPlan {\n id: string;\n creatorId: string;\n name: string;\n description?: string;\n price: string;\n priceUsd?: string;\n paymentToken?: string;\n durationDays: number;\n perks: string[];\n nftBadge: boolean;\n maxSubscribers?: number;\n isActive: boolean;\n activeSubscribers?: number;\n createdAt: string;\n updatedAt: string;\n creator?: TipUser & { isVerified?: boolean };\n}\n\nexport interface Subscription {\n id: string;\n planId: string;\n subscriberId: string;\n creatorId: string;\n subscriberAddress?: string;\n creatorAddress?: string;\n transactionHash?: string;\n amount?: string;\n startDate: string;\n endDate: string;\n expiresAt: string;\n autoRenew: boolean;\n status: 'ACTIVE' | 'EXPIRED' | 'CANCELLED';\n createdAt: string;\n plan?: Partial<SubscriptionPlan>;\n creator?: TipUser & { isVerified?: boolean };\n subscriber?: TipUser;\n}\n\nexport interface CreatePlanRequest {\n name: string;\n description?: string;\n price: string;\n priceUsd?: number;\n paymentToken?: string;\n durationDays?: number;\n perks?: string[];\n nftBadge?: boolean;\n maxSubscribers?: number;\n}\n\nexport interface CreatePlanResponse {\n success: boolean;\n message?: string;\n plan?: SubscriptionPlan;\n error?: string;\n}\n\nexport interface SubscribeRequest {\n planId: string;\n transactionHash?: string;\n autoRenew?: boolean;\n}\n\nexport interface SubscribeResponse {\n success: boolean;\n message?: string;\n subscription?: Subscription;\n error?: string;\n}\n\nexport interface SubscriptionListResponse {\n success: boolean;\n subscriptions?: Subscription[];\n pagination?: {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n };\n stats?: {\n totalSubscribers: number;\n };\n error?: string;\n}\n\nexport interface SubscriptionFilters {\n page?: number;\n limit?: number;\n status?: 'ACTIVE' | 'EXPIRED' | 'CANCELLED';\n}\n\nexport interface ContractSubscribeRequest {\n planId: string;\n months?: number;\n seed: string;\n}\n\nexport interface ContractSubscribeResponse {\n success: boolean;\n transactionHash?: string;\n subscription?: Subscription;\n message?: string;\n error?: string;\n}\n\nexport interface ContractCreatePlanRequest {\n name: string;\n description?: string;\n price: string;\n paymentToken?: string;\n durationDays?: number;\n maxSubscribers?: number;\n seed: string;\n}\n\nexport interface ContractCreatePlanResponse {\n success: boolean;\n transactionHash?: string;\n plan?: SubscriptionPlan;\n message?: string;\n error?: string;\n}\n\nexport interface IsSubscribedResponse {\n subscriber: string;\n creator: string;\n isSubscribed: boolean;\n}\n\nexport interface PlatformFeeResponse {\n feeBps: number;\n feePercent: string;\n}\n\n// ============ Payouts Types ============\n\nexport interface EarningsResponse {\n success: boolean;\n address?: string;\n pendingEarnings?: string;\n totalEarnings?: string;\n earningsBreakdown?: {\n tips: string;\n subscriptions: string;\n nftSales: string;\n royalties: string;\n };\n recentPayouts?: Array<{\n id: string;\n amount: string;\n txHash: string;\n createdAt: string;\n }>;\n error?: string;\n}\n\nexport interface ClaimEarningsRequest {\n seed: string;\n}\n\nexport interface ClaimEarningsResponse {\n success: boolean;\n transactionHash?: string;\n amount?: string;\n message?: string;\n error?: string;\n}\n\nexport interface PayoutHistoryResponse {\n success: boolean;\n payouts?: Array<{\n id: string;\n amount: string;\n status: string;\n txHash: string;\n createdAt: string;\n confirmedAt?: string;\n }>;\n pagination?: {\n page: number;\n limit: number;\n total: number;\n pages: number;\n };\n error?: string;\n}\n\nexport interface EarningsBreakdownResponse {\n success: boolean;\n breakdown?: {\n tips: string;\n subscriptions: string;\n nftSales: string;\n royalties: string;\n total: string;\n };\n percentages?: {\n tips: string;\n subscriptions: string;\n nftSales: string;\n royalties: string;\n };\n error?: string;\n}\n\n/**\n * Zubari API Client for backend integration\n */\nexport class ZubariApiClient {\n private config: Required<Omit<ZubariApiConfig, 'authToken'>> & { authToken?: string };\n\n constructor(config: ZubariApiConfig) {\n this.config = {\n baseUrl: config.baseUrl.replace(/\\/$/, ''), // Remove trailing slash\n timeout: config.timeout || 30000,\n authToken: config.authToken,\n };\n }\n\n /**\n * Set the authentication token\n */\n setAuthToken(token: string): void {\n this.config.authToken = token;\n }\n\n /**\n * Clear the authentication token\n */\n clearAuthToken(): void {\n this.config.authToken = undefined;\n }\n\n /**\n * Make an authenticated request to the API\n */\n private async request<T>(\n method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE',\n path: string,\n body?: unknown\n ): Promise<T> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.config.authToken) {\n headers['Authorization'] = `Bearer ${this.config.authToken}`;\n }\n\n const response = await fetch(`${this.config.baseUrl}${path}`, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);\n }\n\n return response.json();\n }\n\n // ============ NFT Methods ============\n\n /**\n * Get all NFTs with optional filters\n */\n async getNFTs(filters?: NFTFilters): Promise<NFTListResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/nfts${queryString ? `?${queryString}` : ''}`;\n return await this.request<NFTListResponse>('GET', path);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get NFTs',\n };\n }\n }\n\n /**\n * Get a single NFT by ID\n */\n async getNFT(nftId: string): Promise<{ success: boolean; nft?: NFTResponse; error?: string }> {\n try {\n const nft = await this.request<NFTResponse>('GET', `/api/nfts/${nftId}`);\n return { success: true, nft };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get NFT',\n };\n }\n }\n\n /**\n * Create a new NFT (lazy minted)\n */\n async createNFT(\n data: CreateNFTRequest,\n image: File | Blob\n ): Promise<{ success: boolean; nft?: NFTResponse; error?: string }> {\n try {\n const formData = new FormData();\n formData.append('image', image);\n formData.append('name', data.name);\n if (data.description) formData.append('description', data.description);\n formData.append('price', data.price);\n formData.append('currency', data.currency);\n if (data.royaltyBps !== undefined) formData.append('royaltyBps', String(data.royaltyBps));\n if (data.attributes) formData.append('attributes', JSON.stringify(data.attributes));\n if (data.externalUrl) formData.append('externalUrl', data.externalUrl);\n\n const headers: Record<string, string> = {};\n if (this.config.authToken) {\n headers['Authorization'] = `Bearer ${this.config.authToken}`;\n }\n\n const response = await fetch(`${this.config.baseUrl}/api/nfts`, {\n method: 'POST',\n headers,\n body: formData,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(errorData.error || `HTTP ${response.status}`);\n }\n\n const nft = await response.json();\n return { success: true, nft };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create NFT',\n };\n }\n }\n\n /**\n * Create a voucher for an NFT (EIP-712 signed)\n */\n async createVoucher(nftId: string, params: CreateVoucherRequest): Promise<CreateVoucherResponse> {\n try {\n return await this.request<CreateVoucherResponse>('POST', `/api/nfts/${nftId}/voucher`, params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create voucher',\n };\n }\n }\n\n /**\n * Redeem an NFT voucher (buy/mint)\n */\n async redeemVoucher(nftId: string, params: RedeemVoucherRequest): Promise<RedeemVoucherResponse> {\n try {\n return await this.request<RedeemVoucherResponse>('POST', `/api/nfts/${nftId}/redeem`, params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to redeem voucher',\n };\n }\n }\n\n /**\n * Get voucher status for an NFT\n */\n async getVoucherStatus(nftId: string): Promise<VoucherStatusResponse> {\n try {\n return await this.request<VoucherStatusResponse>('GET', `/api/nfts/${nftId}/voucher/status`);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get voucher status',\n };\n }\n }\n\n // ============ Marketplace Methods ============\n\n /**\n * Get all active listings\n */\n async getListings(filters?: ListingFilters): Promise<ListingsResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/market/listings${queryString ? `?${queryString}` : ''}`;\n return await this.request<ListingsResponse>('GET', path);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get listings',\n };\n }\n }\n\n /**\n * List an NFT for sale\n */\n async listItem(params: ListItemRequest): Promise<ListItemResponse> {\n try {\n return await this.request<ListItemResponse>('POST', '/api/market/list', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to list item',\n };\n }\n }\n\n /**\n * Buy a listed NFT\n */\n async buyItem(params: BuyItemRequest): Promise<BuyItemResponse> {\n try {\n return await this.request<BuyItemResponse>('POST', '/api/market/buy', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to buy item',\n };\n }\n }\n\n /**\n * Cancel a listing\n */\n async cancelListing(params: CancelListingRequest): Promise<CancelListingResponse> {\n try {\n return await this.request<CancelListingResponse>('POST', '/api/market/cancel', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to cancel listing',\n };\n }\n }\n\n /**\n * Update listing price\n */\n async updateListingPrice(params: UpdatePriceRequest): Promise<UpdatePriceResponse> {\n try {\n return await this.request<UpdatePriceResponse>('PATCH', '/api/market/price', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to update price',\n };\n }\n }\n\n /**\n * Get current user's listings\n */\n async getMyListings(filters?: Omit<ListingFilters, 'sellerId'>): Promise<ListingsResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/market/my/listings${queryString ? `?${queryString}` : ''}`;\n return await this.request<ListingsResponse>('GET', path);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get my listings',\n };\n }\n }\n\n /**\n * Get marketplace statistics\n */\n async getMarketStats(): Promise<MarketStatsResponse> {\n try {\n return await this.request<MarketStatsResponse>('GET', '/api/market/stats');\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get market stats',\n };\n }\n }\n\n // ============ Tips Methods ============\n\n /**\n * Send a tip to a creator\n */\n async sendTip(params: SendTipRequest): Promise<SendTipResponse> {\n try {\n return await this.request<SendTipResponse>('POST', '/api/tips', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to send tip',\n };\n }\n }\n\n /**\n * Get tip statistics for current user\n */\n async getTipStats(): Promise<TipStatsResponse> {\n try {\n const data = await this.request<{\n sent: { count: number; totalAmount: string; totalAmountUsd: string };\n received: { count: number; totalAmount: string; totalAmountUsd: string; platformFees: string };\n }>('GET', '/api/tips/my/stats');\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get tip stats',\n };\n }\n }\n\n /**\n * Get tips sent by current user\n */\n async getSentTips(filters?: TipFilters): Promise<TipsListResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/tips/sent${queryString ? `?${queryString}` : ''}`;\n const data = await this.request<{\n tips: Tip[];\n pagination: { page: number; limit: number; total: number; totalPages: number };\n totals: { count: number; amount: string; amountUsd: string };\n }>('GET', path);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get sent tips',\n };\n }\n }\n\n /**\n * Get tips received by current user\n */\n async getReceivedTips(filters?: TipFilters): Promise<TipsListResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/tips/received${queryString ? `?${queryString}` : ''}`;\n const data = await this.request<{\n tips: Tip[];\n pagination: { page: number; limit: number; total: number; totalPages: number };\n totals: { count: number; amount: string; amountUsd: string };\n }>('GET', path);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get received tips',\n };\n }\n }\n\n /**\n * Get a single tip by ID\n */\n async getTip(tipId: string): Promise<{ success: boolean; tip?: Tip; error?: string }> {\n try {\n const data = await this.request<{ tip: Tip }>('GET', `/api/tips/${tipId}`);\n return { success: true, tip: data.tip };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get tip',\n };\n }\n }\n\n /**\n * Update tip status (for transaction confirmation)\n */\n async updateTipStatus(\n tipId: string,\n params: UpdateTipStatusRequest\n ): Promise<{ success: boolean; tip?: Tip; message?: string; error?: string }> {\n try {\n const data = await this.request<{ message: string; tip: Tip }>(\n 'PATCH',\n `/api/tips/${tipId}/status`,\n params\n );\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to update tip status',\n };\n }\n }\n\n // ============ Subscription Methods ============\n\n /**\n * Create a new subscription plan (creator only)\n */\n async createSubscriptionPlan(params: CreatePlanRequest): Promise<CreatePlanResponse> {\n try {\n return await this.request<CreatePlanResponse>('POST', '/api/subscriptions/plans', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create subscription plan',\n };\n }\n }\n\n /**\n * Get current user's subscription plans\n */\n async getMySubscriptionPlans(): Promise<{ success: boolean; plans?: SubscriptionPlan[]; error?: string }> {\n try {\n const data = await this.request<{ plans: SubscriptionPlan[] }>('GET', '/api/subscriptions/plans');\n return { success: true, plans: data.plans };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get subscription plans',\n };\n }\n }\n\n /**\n * Get subscription plan by ID\n */\n async getSubscriptionPlan(\n planId: string\n ): Promise<{ success: boolean; plan?: SubscriptionPlan & { isSubscribed?: boolean }; error?: string }> {\n try {\n const plan = await this.request<SubscriptionPlan & { isSubscribed?: boolean }>(\n 'GET',\n `/api/subscriptions/plans/${planId}`\n );\n return { success: true, plan };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get subscription plan',\n };\n }\n }\n\n /**\n * Delete/deactivate subscription plan\n */\n async deleteSubscriptionPlan(\n planId: string\n ): Promise<{ success: boolean; message?: string; deactivated?: boolean; error?: string }> {\n try {\n const data = await this.request<{ message: string; deactivated?: boolean }>(\n 'DELETE',\n `/api/subscriptions/plans/${planId}`\n );\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to delete subscription plan',\n };\n }\n }\n\n /**\n * Subscribe to a plan\n */\n async subscribe(params: SubscribeRequest): Promise<SubscribeResponse> {\n try {\n return await this.request<SubscribeResponse>('POST', '/api/subscriptions/subscribe', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to subscribe',\n };\n }\n }\n\n /**\n * Get current user's subscriptions (as subscriber)\n */\n async getMySubscriptions(filters?: SubscriptionFilters): Promise<SubscriptionListResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/subscriptions${queryString ? `?${queryString}` : ''}`;\n const data = await this.request<{\n subscriptions: Subscription[];\n pagination: { page: number; limit: number; total: number; totalPages: number };\n }>('GET', path);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get subscriptions',\n };\n }\n }\n\n /**\n * Get subscribers to current user's plans (as creator)\n */\n async getMySubscribers(filters?: SubscriptionFilters): Promise<SubscriptionListResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/subscriptions/subscribers${queryString ? `?${queryString}` : ''}`;\n const data = await this.request<{\n subscriptions: Subscription[];\n pagination: { page: number; limit: number; total: number; totalPages: number };\n stats: { totalSubscribers: number };\n }>('GET', path);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get subscribers',\n };\n }\n }\n\n /**\n * Cancel subscription\n */\n async cancelSubscription(subscriptionId: string): Promise<{ success: boolean; message?: string; error?: string }> {\n try {\n const data = await this.request<{ message: string }>('DELETE', `/api/subscriptions/${subscriptionId}`);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to cancel subscription',\n };\n }\n }\n\n /**\n * Create a subscription plan on-chain\n */\n async createSubscriptionPlanOnChain(params: ContractCreatePlanRequest): Promise<ContractCreatePlanResponse> {\n try {\n return await this.request<ContractCreatePlanResponse>('POST', '/api/subscriptions/contract/plans', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create plan on-chain',\n };\n }\n }\n\n /**\n * Subscribe to a plan on-chain\n */\n async subscribeOnChain(params: ContractSubscribeRequest): Promise<ContractSubscribeResponse> {\n try {\n return await this.request<ContractSubscribeResponse>('POST', '/api/subscriptions/contract/subscribe', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to subscribe on-chain',\n };\n }\n }\n\n /**\n * Cancel subscription on-chain\n */\n async cancelSubscriptionOnChain(\n subscriptionId: string,\n seed: string\n ): Promise<{ success: boolean; transactionHash?: string; message?: string; error?: string }> {\n try {\n return await this.request<{ success: boolean; transactionHash: string; message: string }>(\n 'POST',\n '/api/subscriptions/contract/cancel',\n { subscriptionId, seed }\n );\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to cancel subscription on-chain',\n };\n }\n }\n\n /**\n * Check if user is subscribed to a creator on-chain\n */\n async isSubscribed(subscriber: string, creator: string): Promise<IsSubscribedResponse> {\n try {\n return await this.request<IsSubscribedResponse>(\n 'GET',\n `/api/subscriptions/contract/is-subscribed?subscriber=${subscriber}&creator=${creator}`\n );\n } catch (error) {\n return {\n subscriber,\n creator,\n isSubscribed: false,\n };\n }\n }\n\n /**\n * Get subscription platform fee\n */\n async getSubscriptionPlatformFee(): Promise<PlatformFeeResponse> {\n try {\n return await this.request<PlatformFeeResponse>('GET', '/api/subscriptions/platform-fee');\n } catch (error) {\n return {\n feeBps: 0,\n feePercent: '0',\n };\n }\n }\n\n // ============ Payouts Methods ============\n\n /**\n * Get pending and claimed earnings for the authenticated user\n */\n async getEarnings(): Promise<EarningsResponse> {\n try {\n const data = await this.request<{\n address: string;\n pendingEarnings: string;\n totalEarnings: string;\n earningsBreakdown: { tips: string; subscriptions: string; nftSales: string; royalties: string };\n recentPayouts: Array<{ id: string; amount: string; txHash: string; createdAt: string }>;\n }>('GET', '/api/payouts/earnings');\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get earnings',\n };\n }\n }\n\n /**\n * Claim pending earnings\n */\n async claimEarnings(params: ClaimEarningsRequest): Promise<ClaimEarningsResponse> {\n try {\n return await this.request<ClaimEarningsResponse>('POST', '/api/payouts/claim', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to claim earnings',\n };\n }\n }\n\n /**\n * Get payout history for the authenticated user\n */\n async getPayoutHistory(filters?: { page?: number; limit?: number }): Promise<PayoutHistoryResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/payouts/history${queryString ? `?${queryString}` : ''}`;\n const data = await this.request<{\n payouts: Array<{\n id: string;\n amount: string;\n status: string;\n txHash: string;\n createdAt: string;\n confirmedAt?: string;\n }>;\n pagination: { page: number; limit: number; total: number; pages: number };\n }>('GET', path);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get payout history',\n };\n }\n }\n\n /**\n * Get earnings breakdown by source\n */\n async getEarningsBreakdown(): Promise<EarningsBreakdownResponse> {\n try {\n const data = await this.request<{\n breakdown: { tips: string; subscriptions: string; nftSales: string; royalties: string; total: string };\n percentages: { tips: string; subscriptions: string; nftSales: string; royalties: string };\n }>('GET', '/api/payouts/breakdown');\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get earnings breakdown',\n };\n }\n }\n\n /**\n * Get current platform fee for payouts\n */\n async getPayoutsPlatformFee(): Promise<PlatformFeeResponse> {\n try {\n return await this.request<PlatformFeeResponse>('GET', '/api/payouts/platform-fee');\n } catch (error) {\n return {\n feeBps: 0,\n feePercent: '0',\n };\n }\n }\n}\n\n// Default API URL (can be overridden)\nconst DEFAULT_API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://ckgwifsxka.us-east-2.awsapprunner.com';\n\n// Singleton instance\nlet zubariApiClient: ZubariApiClient | null = null;\n\n/**\n * Get or create the Zubari API client instance\n */\nexport function getZubariApiClient(config?: Partial<ZubariApiConfig>): ZubariApiClient {\n if (!zubariApiClient || (config?.baseUrl && zubariApiClient['config'].baseUrl !== config.baseUrl)) {\n zubariApiClient = new ZubariApiClient({\n baseUrl: config?.baseUrl || DEFAULT_API_URL,\n timeout: config?.timeout,\n authToken: config?.authToken,\n });\n } else if (config?.authToken) {\n zubariApiClient.setAuthToken(config.authToken);\n }\n return zubariApiClient;\n}\n\n/**\n * Create a new Zubari API client instance\n */\nexport function createZubariApiClient(config: ZubariApiConfig): ZubariApiClient {\n return new ZubariApiClient(config);\n}\n","/**\n * Browser-Compatible Address Derivation\n *\n * This module provides multi-chain address derivation that works in browser environments.\n * It uses the @scure libraries which are pure JS and don't require Node.js polyfills.\n *\n * Supported chains:\n * - Ethereum: ethers.js (BIP-44)\n * - Bitcoin: @scure/bip32 + @scure/base (BIP-84 native SegWit)\n * - Solana: ed25519-hd-key + tweetnacl (SLIP-0010)\n * - TON: ed25519 derivation with TON address format\n * - TRON: secp256k1 + base58check\n * - Spark: Bitcoin-based with custom derivation\n */\n\nimport { HDNodeWallet, keccak256, getBytes, sha256 as ethSha256 } from 'ethers';\nimport { mnemonicToSeedSync, validateMnemonic, generateMnemonic } from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english';\nimport { HDKey } from '@scure/bip32';\nimport { bech32, base58check } from '@scure/base';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\nimport type { NetworkType } from '../types';\n\nexport interface ChainAddress {\n chain: NetworkType;\n address: string;\n path: string;\n}\n\nexport interface BrowserMultiChainAddresses {\n ethereum: string | null;\n bitcoin: string | null;\n ton: string | null;\n tron: string | null;\n solana: string | null;\n spark: string | null;\n}\n\n// BIP-44/84 derivation paths\nconst DERIVATION_PATHS = {\n ethereum: \"m/44'/60'/0'/0/0\",\n bitcoin_mainnet: \"m/84'/0'/0'/0/0\",\n bitcoin_testnet: \"m/84'/1'/0'/0/0\",\n ton: \"m/44'/607'/0'/0'/0'\",\n tron: \"m/44'/195'/0'/0/0\",\n solana: \"m/44'/501'/0'/0'\",\n spark: \"m/44'/998'/0'/0/0\",\n};\n\n/**\n * Derive Ethereum address from seed phrase\n */\nexport function deriveEthereumAddress(seed: string): string {\n const hdNode = HDNodeWallet.fromPhrase(seed, undefined, DERIVATION_PATHS.ethereum);\n return hdNode.address;\n}\n\n/**\n * Derive Bitcoin address from seed phrase (BIP-84 native SegWit)\n * Uses @scure libraries for browser compatibility\n */\nexport function deriveBitcoinAddress(\n seed: string,\n network: 'mainnet' | 'testnet' = 'testnet'\n): string {\n try {\n // Convert mnemonic to seed using @scure/bip39\n const seedBytes = mnemonicToSeedSync(seed);\n\n // Derive HD key using @scure/bip32\n const hdKey = HDKey.fromMasterSeed(seedBytes);\n const path = network === 'testnet' ? DERIVATION_PATHS.bitcoin_testnet : DERIVATION_PATHS.bitcoin_mainnet;\n const child = hdKey.derive(path);\n\n if (!child.publicKey) {\n throw new Error('Failed to derive public key');\n }\n\n // Create P2WPKH address (native SegWit)\n // 1. Hash160 = RIPEMD160(SHA256(publicKey))\n const pubKeyHash = ripemd160(sha256(child.publicKey));\n\n // 2. Create witness program: version (0x00) + hash160\n // For bech32, we encode: witness version (0) + pubKeyHash as 5-bit words\n const witnessVersion = 0;\n const words = bech32.toWords(pubKeyHash);\n words.unshift(witnessVersion); // Prepend witness version\n\n // 3. Encode with bech32\n const hrp = network === 'testnet' ? 'tb' : 'bc';\n const address = bech32.encode(hrp, words);\n\n return address;\n } catch (error) {\n console.error('Bitcoin address derivation failed:', error);\n throw error;\n }\n}\n\n/**\n * Derive Solana address from seed phrase using SLIP-0010 (ed25519)\n */\nexport async function deriveSolanaAddress(seed: string): Promise<string> {\n try {\n const [ed25519, nacl, bs58Module] = await Promise.all([\n import('ed25519-hd-key'),\n import('tweetnacl'),\n import('bs58'),\n ]);\n\n // bs58 v6 uses default export\n const bs58 = bs58Module.default || bs58Module;\n\n // Use @scure/bip39 for seed generation (browser compatible)\n const seedBytes = mnemonicToSeedSync(seed);\n\n // SLIP-0010 derivation for ed25519\n const derived = ed25519.derivePath(DERIVATION_PATHS.solana, Buffer.from(seedBytes).toString('hex'));\n\n // Create keypair from derived seed\n const keypair = nacl.sign.keyPair.fromSeed(new Uint8Array(derived.key));\n\n // Solana address is the base58-encoded public key (32 bytes)\n return bs58.encode(keypair.publicKey);\n } catch (error) {\n console.error('Solana address derivation failed:', error);\n throw error;\n }\n}\n\n/**\n * Derive TON address from seed phrase\n * Uses proper BIP-44 derivation path m/44'/607'/0'/0'/0'\n */\nexport async function deriveTonAddress(seed: string): Promise<string> {\n try {\n const [ed25519, nacl] = await Promise.all([\n import('ed25519-hd-key'),\n import('tweetnacl'),\n ]);\n\n // Use @scure/bip39 for seed generation (browser compatible)\n const seedBytes = mnemonicToSeedSync(seed);\n\n // Use SLIP-0010 derivation for ed25519 with TON's coin type\n const derived = ed25519.derivePath(DERIVATION_PATHS.ton, Buffer.from(seedBytes).toString('hex'));\n\n // Create keypair\n const keypair = nacl.sign.keyPair.fromSeed(new Uint8Array(derived.key));\n\n // TON address is derived from public key using workchain + hash\n // Standard TON wallet v4r2 uses the public key to derive address\n const publicKey = keypair.publicKey;\n\n // Create TON bounceable address (EQ prefix for workchain 0)\n // Format: 1 byte flags + 1 byte workchain + 32 bytes hash + 2 bytes CRC16\n const workchain = 0;\n const flags = 0x11; // bounceable\n\n // For raw address, we use SHA256 of public key using @noble/hashes\n const hash = sha256(publicKey);\n\n // Build address bytes: flags + workchain + hash\n const addressData = new Uint8Array(34);\n addressData[0] = flags;\n addressData[1] = workchain;\n addressData.set(hash, 2);\n\n // Calculate CRC16\n const crc = crc16(addressData);\n\n // Full address with CRC\n const fullAddress = new Uint8Array(36);\n fullAddress.set(addressData);\n fullAddress[34] = (crc >> 8) & 0xff;\n fullAddress[35] = crc & 0xff;\n\n // Convert to base64url (TON standard format)\n const base64 = btoa(String.fromCharCode(...fullAddress))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n\n return base64;\n } catch (error) {\n console.error('TON address derivation failed:', error);\n throw error;\n }\n}\n\n/**\n * CRC16-CCITT for TON addresses\n */\nfunction crc16(data: Uint8Array): number {\n let crc = 0;\n for (const byte of data) {\n crc ^= byte << 8;\n for (let i = 0; i < 8; i++) {\n crc = (crc & 0x8000) ? ((crc << 1) ^ 0x1021) : (crc << 1);\n crc &= 0xffff;\n }\n }\n return crc;\n}\n\n/**\n * Derive TRON address from seed phrase\n * TRON uses secp256k1 like Ethereum but with base58check encoding\n * Uses @scure/base for browser compatibility\n */\nexport function deriveTronAddress(seed: string): string {\n try {\n // Derive using TRON's BIP-44 path\n const hdNode = HDNodeWallet.fromPhrase(seed, undefined, DERIVATION_PATHS.tron);\n\n // Get the Ethereum-style address (last 20 bytes of keccak256 of public key)\n // TRON uses same derivation but different encoding\n const ethAddressHex = hdNode.address.slice(2).toLowerCase();\n\n // TRON address: 0x41 prefix + 20 bytes address\n const addressBytes = new Uint8Array(21);\n addressBytes[0] = 0x41; // TRON mainnet prefix\n\n // Copy ETH address bytes\n for (let i = 0; i < 20; i++) {\n addressBytes[i + 1] = parseInt(ethAddressHex.slice(i * 2, i * 2 + 2), 16);\n }\n\n // Base58check encode using @scure/base (uses double SHA256 for checksum)\n const tronBase58check = base58check(sha256);\n return tronBase58check.encode(addressBytes);\n } catch (error) {\n console.error('TRON address derivation failed:', error);\n throw error;\n }\n}\n\n/**\n * Derive Spark address from seed phrase\n * Spark uses its own derivation path and bech32 format\n * Uses @scure libraries for browser compatibility\n */\nexport function deriveSparkAddress(\n seed: string,\n network: 'mainnet' | 'testnet' = 'testnet'\n): string {\n try {\n // Convert mnemonic to seed using @scure/bip39\n const seedBytes = mnemonicToSeedSync(seed);\n\n // Derive HD key using @scure/bip32\n const hdKey = HDKey.fromMasterSeed(seedBytes);\n const child = hdKey.derive(DERIVATION_PATHS.spark);\n\n if (!child.publicKey) {\n throw new Error('Failed to derive public key');\n }\n\n // Create P2WPKH-style address (same as Bitcoin but with Spark HRP)\n // 1. Hash160 = RIPEMD160(SHA256(publicKey))\n const pubKeyHash = ripemd160(sha256(child.publicKey));\n\n // 2. Create witness program with version 0\n const witnessVersion = 0;\n const words = bech32.toWords(pubKeyHash);\n words.unshift(witnessVersion);\n\n // 3. Encode with bech32 using Spark's HRP\n // Note: Spark uses 'sp' for mainnet and 'tsp' for testnet\n const hrp = network === 'testnet' ? 'tsp' : 'sp';\n const address = bech32.encode(hrp, words);\n\n return address;\n } catch (error) {\n console.error('Spark address derivation failed:', error);\n throw error;\n }\n}\n\n/**\n * Derive addresses for all supported chains\n */\nexport async function deriveAllAddresses(\n seed: string,\n network: 'mainnet' | 'testnet' = 'testnet'\n): Promise<BrowserMultiChainAddresses> {\n const addresses: BrowserMultiChainAddresses = {\n ethereum: null,\n bitcoin: null,\n ton: null,\n tron: null,\n solana: null,\n spark: null,\n };\n\n // Derive synchronous chains first (Ethereum, Bitcoin, Spark, TRON)\n try {\n addresses.ethereum = deriveEthereumAddress(seed);\n } catch (e) {\n console.error('ETH derivation failed:', e);\n }\n\n try {\n addresses.bitcoin = deriveBitcoinAddress(seed, network);\n } catch (e) {\n console.error('BTC derivation failed:', e);\n }\n\n try {\n addresses.spark = deriveSparkAddress(seed, network);\n } catch (e) {\n console.error('Spark derivation failed:', e);\n }\n\n try {\n addresses.tron = deriveTronAddress(seed);\n } catch (e) {\n console.error('TRON derivation failed:', e);\n }\n\n // Derive async chains in parallel (Solana, TON use ed25519 which requires async imports)\n const [solResult, tonResult] = await Promise.allSettled([\n deriveSolanaAddress(seed),\n deriveTonAddress(seed),\n ]);\n\n if (solResult.status === 'fulfilled') {\n addresses.solana = solResult.value;\n } else {\n console.error('SOL derivation failed:', solResult.reason);\n }\n\n if (tonResult.status === 'fulfilled') {\n addresses.ton = tonResult.value;\n } else {\n console.error('TON derivation failed:', tonResult.reason);\n }\n\n return addresses;\n}\n\n/**\n * Validate a BIP-39 seed phrase using @scure/bip39\n */\nexport function isValidSeed(seed: string): boolean {\n return validateMnemonic(seed, wordlist);\n}\n\n/**\n * Generate a random BIP-39 seed phrase using @scure/bip39\n */\nexport function generateSeedPhrase(): string {\n return generateMnemonic(wordlist);\n}\n","/**\n * Zubari WDK Service - Unified Multi-Chain Wallet Service\n *\n * This service provides a unified interface for multi-chain wallet operations\n * that works in both browser and Node.js environments.\n *\n * Strategy:\n * - Browser: Uses WdkApiClient to call the backend API (which has Tether WDK)\n * - Node.js: Uses WdkService natively (with Tether WDK modules)\n *\n * The Tether WDK (@tetherto/wdk-*) only works in Node.js environments due to\n * native dependencies (Electrum client, gRPC, etc.). For browser environments,\n * we route all operations through the backend API.\n *\n * @see https://docs.wallet.tether.io/\n */\n\nimport { WdkApiClient, getWdkApiClient } from './WdkApiClient';\nimport * as BrowserDerivation from './BrowserAddressDerivation';\nimport type { NetworkType } from '../types';\n\n// Default API URL for the Zubari backend with Tether WDK\nconst DEFAULT_API_URL = 'https://ckgwifsxka.us-east-2.awsapprunner.com';\n\nexport type SupportedChain = 'ethereum' | 'bitcoin' | 'ton' | 'tron' | 'solana' | 'spark';\n\nexport interface ChainAddress {\n chain: SupportedChain;\n address: string;\n path: string;\n}\n\nexport interface MultiChainAddresses {\n ethereum: string | null;\n bitcoin: string | null;\n ton: string | null;\n tron: string | null;\n solana: string | null;\n spark: string | null;\n}\n\nexport interface ChainBalance {\n chain: SupportedChain;\n address: string;\n balance: string;\n symbol: string;\n}\n\nexport interface FeeRates {\n slow: string;\n normal: string;\n fast: string;\n}\n\nexport interface TransactionResult {\n success: boolean;\n txHash?: string;\n from?: string;\n to?: string;\n amount?: string;\n chain?: string;\n network?: string;\n error?: string;\n}\n\nexport interface ZubariWdkServiceConfig {\n /** Network to use (mainnet or testnet) */\n network: 'mainnet' | 'testnet';\n /** API URL for the Zubari backend (required for browser environments) */\n apiUrl?: string;\n /** Force using API even in Node.js (useful for testing) */\n forceApi?: boolean;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\n/**\n * Check if we're running in a browser environment\n */\nfunction isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n}\n\n/**\n * Dynamic import helper that bypasses bundler analysis\n * This ensures the import is truly runtime and not analyzed at build time\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst dynamicImport = new Function('specifier', 'return import(specifier)') as (\n specifier: string\n) => Promise<any>;\n\n/**\n * Check if native WDK modules are available (Node.js only)\n */\nasync function canUseNativeWdk(): Promise<boolean> {\n // Never use native WDK in browser\n if (isBrowser()) {\n return false;\n }\n\n try {\n // Try to dynamically import WDK to check if it's available\n await dynamicImport('@tetherto/wdk');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * ZubariWdkService - Unified wallet service for browser and Node.js\n *\n * This service automatically routes operations to:\n * - API backend (browser) - using WdkApiClient\n * - Native WDK (Node.js) - using WdkService\n * - Browser derivation (fallback) - using BrowserAddressDerivation\n */\nexport class ZubariWdkService {\n private config: Required<ZubariWdkServiceConfig>;\n private apiClient: WdkApiClient;\n private nativeWdkService: unknown | null = null;\n private initialized = false;\n private useNativeWdk = false;\n\n constructor(config: Partial<ZubariWdkServiceConfig> = {}) {\n this.config = {\n network: config.network || 'testnet',\n apiUrl: config.apiUrl || process.env.NEXT_PUBLIC_API_URL || DEFAULT_API_URL,\n forceApi: config.forceApi ?? false,\n timeout: config.timeout || 30000,\n };\n\n this.apiClient = getWdkApiClient(this.config.apiUrl);\n }\n\n /**\n * Initialize the service and determine the best strategy\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n // In browser or if forceApi is set, always use API\n if (isBrowser() || this.config.forceApi) {\n this.useNativeWdk = false;\n this.initialized = true;\n return;\n }\n\n // In Node.js, try to use native WDK\n if (await canUseNativeWdk()) {\n try {\n // Use dynamic import helper to bypass bundler analysis\n // This ensures WdkService is never included in browser bundles\n const WdkServiceModule = await dynamicImport('./WdkService');\n const WdkService = WdkServiceModule.WdkService || WdkServiceModule.default;\n this.nativeWdkService = new WdkService({\n network: this.config.network,\n });\n this.useNativeWdk = true;\n } catch (error) {\n console.warn('Failed to initialize native WDK, falling back to API:', error);\n this.useNativeWdk = false;\n }\n }\n\n this.initialized = true;\n }\n\n /**\n * Get the current execution mode\n */\n getMode(): 'api' | 'native' | 'browser-fallback' {\n if (this.useNativeWdk) return 'native';\n if (isBrowser()) return 'api';\n return 'api';\n }\n\n /**\n * Check if running in browser\n */\n isBrowserEnvironment(): boolean {\n return isBrowser();\n }\n\n /**\n * Generate a new BIP-39 seed phrase (12 words)\n */\n async generateSeed(): Promise<string> {\n await this.initialize();\n\n // Try API first (most reliable, uses real WDK)\n try {\n const response = await this.apiClient.generateSeed();\n if (response.success && response.seed) {\n return response.seed;\n }\n } catch (error) {\n console.warn('API seed generation failed:', error);\n }\n\n // Try native WDK\n if (this.useNativeWdk && this.nativeWdkService) {\n try {\n const wdk = this.nativeWdkService as { generateSeedPhrase: () => Promise<string> };\n return await wdk.generateSeedPhrase();\n } catch (error) {\n console.warn('Native WDK seed generation failed:', error);\n }\n }\n\n // Fallback to browser-compatible generation\n return BrowserDerivation.generateSeedPhrase();\n }\n\n /**\n * Validate a BIP-39 seed phrase\n */\n async validateSeed(seed: string): Promise<boolean> {\n await this.initialize();\n\n // Try API first\n try {\n const response = await this.apiClient.validateSeed(seed);\n if (response.success) {\n return response.isValid ?? false;\n }\n } catch (error) {\n console.warn('API seed validation failed:', error);\n }\n\n // Try native WDK\n if (this.useNativeWdk && this.nativeWdkService) {\n try {\n const wdk = this.nativeWdkService as { isValidSeed: (seed: string) => Promise<boolean> };\n return await wdk.isValidSeed(seed);\n } catch (error) {\n console.warn('Native WDK seed validation failed:', error);\n }\n }\n\n // Fallback to browser-compatible validation\n return BrowserDerivation.isValidSeed(seed);\n }\n\n /**\n * Derive address for a specific chain using WDK API\n *\n * For Ethereum, falls back to local derivation if API fails.\n * For other chains, WDK API is required - no placeholder fallback.\n */\n async deriveAddress(seed: string, chain: SupportedChain): Promise<ChainAddress> {\n await this.initialize();\n\n const path = this.getDerivationPath(chain);\n\n // Try API first (uses real WDK on backend)\n try {\n const response = await this.apiClient.deriveAddress(seed, chain as NetworkType, this.config.network);\n if (response.success && response.address) {\n return {\n chain,\n address: response.address,\n path: response.path || path,\n };\n }\n } catch (error) {\n console.warn(`API address derivation failed for ${chain}:`, error);\n\n // For Ethereum only, fall back to local derivation\n if (chain === 'ethereum') {\n return this.deriveBrowserAddress(seed, chain);\n }\n }\n\n // Try native WDK (Node.js only)\n if (this.useNativeWdk && this.nativeWdkService) {\n try {\n const wdk = this.nativeWdkService as {\n initialize: (seed: string) => Promise<void>;\n deriveAddress: (chain: SupportedChain) => Promise<ChainAddress>;\n };\n await wdk.initialize(seed);\n return await wdk.deriveAddress(chain);\n } catch (error) {\n console.warn(`Native WDK address derivation failed for ${chain}:`, error);\n }\n }\n\n // For Ethereum, we can use browser derivation as final fallback\n if (chain === 'ethereum') {\n return this.deriveBrowserAddress(seed, chain);\n }\n\n // For other chains, throw error - no placeholder addresses\n throw new Error(\n `WDK API required for ${chain} address derivation. Ensure the backend is running.`\n );\n }\n\n /**\n * Derive addresses for all supported chains using WDK API\n *\n * Uses the backend WDK API for real cryptographically valid addresses.\n * No placeholder fallback - WDK API is required for multi-chain addresses.\n */\n async deriveAllAddresses(seed: string): Promise<MultiChainAddresses> {\n await this.initialize();\n\n // Try API first (uses real WDK on backend)\n try {\n const response = await this.apiClient.deriveAllAddresses(seed, this.config.network);\n if (response.success && response.addresses) {\n // Extract address strings from response - API may return objects or strings\n const extractAddress = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'string') return value;\n if (typeof value === 'object' && value !== null && 'address' in value) {\n return (value as { address: string }).address;\n }\n return null;\n };\n\n return {\n ethereum: extractAddress(response.addresses.ethereum),\n bitcoin: extractAddress(response.addresses.bitcoin),\n ton: extractAddress(response.addresses.ton),\n tron: extractAddress(response.addresses.tron),\n solana: extractAddress(response.addresses.solana),\n spark: extractAddress(response.addresses.spark),\n };\n }\n } catch (error) {\n console.warn('API address derivation failed:', error);\n }\n\n // Try native WDK (Node.js only)\n if (this.useNativeWdk && this.nativeWdkService) {\n try {\n const wdk = this.nativeWdkService as {\n initialize: (seed: string) => Promise<void>;\n deriveAllAddresses: () => Promise<MultiChainAddresses>;\n };\n await wdk.initialize(seed);\n return await wdk.deriveAllAddresses();\n } catch (error) {\n console.warn('Native WDK multi-chain derivation failed:', error);\n }\n }\n\n // No fallback - Tether WDK is required for multi-chain address derivation\n throw new Error(\n 'Tether WDK API required for multi-chain address derivation. Service temporarily unavailable.'\n );\n }\n\n /**\n * Get balances for all chains\n */\n async getAllBalances(seed: string): Promise<Record<string, ChainBalance | null>> {\n await this.initialize();\n\n // This always uses API as it requires blockchain RPC calls\n try {\n const response = await fetch(`${this.config.apiUrl}/api/wallets/wdk/balances`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ seed, network: this.config.network }),\n });\n\n if (response.ok) {\n const data = await response.json();\n if (data.success) {\n return data.balances;\n }\n }\n } catch (error) {\n console.warn('Failed to fetch balances:', error);\n }\n\n return {};\n }\n\n /**\n * Get fee rates for a chain\n */\n async getFeeRates(seed: string, chain: SupportedChain): Promise<FeeRates> {\n await this.initialize();\n\n try {\n const response = await fetch(`${this.config.apiUrl}/api/wallets/wdk/fee-rates`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ seed, chain, network: this.config.network }),\n });\n\n if (response.ok) {\n const data = await response.json();\n if (data.success && data.feeRates) {\n return data.feeRates;\n }\n }\n } catch (error) {\n console.warn(`Failed to fetch fee rates for ${chain}:`, error);\n }\n\n return { slow: '0', normal: '0', fast: '0' };\n }\n\n /**\n * Estimate transaction fee\n */\n async estimateFee(\n seed: string,\n chain: SupportedChain,\n to: string,\n amount: string\n ): Promise<{ fee: string; symbol: string }> {\n await this.initialize();\n\n try {\n const response = await fetch(`${this.config.apiUrl}/api/wallets/wdk/estimate-fee`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ seed, chain, to, amount, network: this.config.network }),\n });\n\n if (response.ok) {\n const data = await response.json();\n if (data.success) {\n return { fee: data.fee, symbol: data.symbol };\n }\n }\n } catch (error) {\n console.warn(`Failed to estimate fee for ${chain}:`, error);\n }\n\n return { fee: '0', symbol: this.getChainSymbol(chain) };\n }\n\n /**\n * Send a transaction\n */\n async sendTransaction(\n seed: string,\n chain: SupportedChain,\n to: string,\n amount: string\n ): Promise<TransactionResult> {\n await this.initialize();\n\n try {\n const response = await fetch(`${this.config.apiUrl}/api/wallets/wdk/send`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ seed, chain, to, amount, network: this.config.network }),\n });\n\n if (response.ok) {\n const data = await response.json();\n\n // Extract transaction hash from various possible properties\n let txHash = data.txHash || data.transactionHash || data.hash;\n\n // Handle case where txHash might be an object\n if (txHash && typeof txHash === 'object' && 'hash' in txHash) {\n txHash = txHash.hash;\n }\n\n // Validate Ethereum tx hash format (should be 66 chars: 0x + 64 hex)\n if (chain === 'ethereum' && txHash && (typeof txHash !== 'string' || !txHash.startsWith('0x') || txHash.length !== 66)) {\n console.warn(`Invalid Ethereum tx hash format: ${txHash} (length: ${txHash?.length}, expected: 66)`);\n }\n\n return {\n success: data.success,\n txHash,\n from: data.from,\n to: data.to,\n amount: data.amount,\n chain: data.chain,\n network: data.network,\n };\n }\n\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n error: errorData.error || `HTTP ${response.status}`,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Transaction failed',\n };\n }\n }\n\n /**\n * Get the network configuration\n */\n getNetwork(): 'mainnet' | 'testnet' {\n return this.config.network;\n }\n\n /**\n * Get API URL\n */\n getApiUrl(): string {\n return this.config.apiUrl;\n }\n\n // ==========================================\n // Private Helper Methods\n // ==========================================\n\n private getDerivationPath(chain: SupportedChain): string {\n const paths: Record<SupportedChain, string> = {\n bitcoin: this.config.network === 'testnet' ? \"m/84'/1'/0'/0/0\" : \"m/84'/0'/0'/0/0\",\n ethereum: \"m/44'/60'/0'/0/0\",\n ton: \"m/44'/607'/0'/0'/0'\",\n tron: \"m/44'/195'/0'/0/0\",\n solana: \"m/44'/501'/0'/0'\",\n spark: \"m/44'/998'/0'/0/0\",\n };\n return paths[chain];\n }\n\n private getChainSymbol(chain: SupportedChain): string {\n const symbols: Record<SupportedChain, string> = {\n ethereum: 'ETH',\n bitcoin: 'BTC',\n ton: 'TON',\n tron: 'TRX',\n solana: 'SOL',\n spark: 'SAT',\n };\n return symbols[chain];\n }\n\n /**\n * Derive address using browser-compatible libraries\n */\n private async deriveBrowserAddress(seed: string, chain: SupportedChain): Promise<ChainAddress> {\n const path = this.getDerivationPath(chain);\n\n try {\n let address: string;\n\n switch (chain) {\n case 'ethereum':\n address = BrowserDerivation.deriveEthereumAddress(seed);\n break;\n case 'bitcoin':\n address = BrowserDerivation.deriveBitcoinAddress(seed, this.config.network);\n break;\n case 'tron':\n address = BrowserDerivation.deriveTronAddress(seed);\n break;\n case 'spark':\n address = BrowserDerivation.deriveSparkAddress(seed, this.config.network);\n break;\n case 'solana':\n address = await BrowserDerivation.deriveSolanaAddress(seed);\n break;\n case 'ton':\n address = await BrowserDerivation.deriveTonAddress(seed);\n break;\n default:\n throw new Error(`Unsupported chain: ${chain}`);\n }\n\n return { chain, address, path };\n } catch (error) {\n console.error(`Browser derivation failed for ${chain}:`, error);\n throw error;\n }\n }\n\n /**\n * Derive all addresses using browser-compatible libraries\n */\n private async deriveAllBrowserAddresses(seed: string): Promise<MultiChainAddresses> {\n return BrowserDerivation.deriveAllAddresses(seed, this.config.network);\n }\n}\n\n// ==========================================\n// Factory Functions\n// ==========================================\n\nlet defaultService: ZubariWdkService | null = null;\n\n/**\n * Get or create the default ZubariWdkService instance\n */\nexport function getZubariWdkService(config?: Partial<ZubariWdkServiceConfig>): ZubariWdkService {\n if (!defaultService || (config && config.network !== defaultService.getNetwork())) {\n defaultService = new ZubariWdkService(config);\n }\n return defaultService;\n}\n\n/**\n * Create a new ZubariWdkService instance\n */\nexport function createZubariWdkService(config?: Partial<ZubariWdkServiceConfig>): ZubariWdkService {\n return new ZubariWdkService(config);\n}\n\n/**\n * Check if the current environment is a browser\n */\nexport { isBrowser };\n","/**\n * Transaction Service for Zubari SDK\n *\n * Provides multi-chain transaction capabilities using Tether WDK.\n * Supports Ethereum, Bitcoin, Solana, TON, TRON, and Spark (Lightning).\n *\n * @see https://docs.wallet.tether.io/\n */\n\nimport type { NetworkType, TxResult } from '../types';\n\n// Dynamic imports for ESM modules (WDK packages are ESM-only)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WdkManager: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerBtc: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerEvm: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerSolana: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerTon: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerTron: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerSpark: any;\n\nlet wdkLoaded = false;\nlet wdkLoadError: Error | null = null;\n\n/**\n * CoinGecko IDs for each supported chain\n */\nconst COINGECKO_IDS: Record<NetworkType, string> = {\n ethereum: 'ethereum',\n bitcoin: 'bitcoin',\n ton: 'the-open-network',\n tron: 'tron',\n solana: 'solana',\n spark: 'bitcoin', // Spark uses BTC\n};\n\n/**\n * Price cache to avoid excessive API calls\n */\ninterface PriceCache {\n prices: Record<string, number>;\n timestamp: number;\n}\n\nlet priceCache: PriceCache | null = null;\nconst PRICE_CACHE_TTL = 60000; // 1 minute cache\n\n/**\n * Fetch USD prices for all supported chains from CoinGecko\n */\nasync function fetchPrices(): Promise<Record<string, number>> {\n // Check cache\n if (priceCache && Date.now() - priceCache.timestamp < PRICE_CACHE_TTL) {\n return priceCache.prices;\n }\n\n const ids = Object.values(COINGECKO_IDS).filter((v, i, a) => a.indexOf(v) === i).join(',');\n\n try {\n const response = await fetch(\n `https://api.coingecko.com/api/v3/simple/price?ids=${ids}&vs_currencies=usd`,\n {\n headers: { 'Accept': 'application/json' },\n }\n );\n\n if (response.ok) {\n const data = await response.json();\n const prices: Record<string, number> = {};\n\n for (const [chain, geckoId] of Object.entries(COINGECKO_IDS)) {\n prices[chain] = data[geckoId]?.usd || 0;\n }\n\n // Update cache\n priceCache = { prices, timestamp: Date.now() };\n return prices;\n }\n } catch (error) {\n console.warn('Failed to fetch prices from CoinGecko:', error);\n }\n\n // Return cached prices if available, otherwise empty\n return priceCache?.prices || {};\n}\n\n/**\n * Get USD price for a specific chain\n */\nasync function getPriceForChain(chain: NetworkType): Promise<number> {\n const prices = await fetchPrices();\n return prices[chain] || 0;\n}\n\n/**\n * Dynamic import helper that bypasses TypeScript's CommonJS transformation\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst dynamicImport = new Function('specifier', 'return import(specifier)') as (\n specifier: string\n) => Promise<any>;\n\n/**\n * Dynamically load WDK modules (they are ESM-only)\n */\nasync function loadWdkModules(): Promise<void> {\n if (wdkLoaded) return;\n if (wdkLoadError) throw wdkLoadError;\n\n try {\n const [wdk, btc, evm, solana, ton, tron, spark] = await Promise.all([\n dynamicImport('@tetherto/wdk'),\n dynamicImport('@tetherto/wdk-wallet-btc'),\n dynamicImport('@tetherto/wdk-wallet-evm'),\n dynamicImport('@tetherto/wdk-wallet-solana'),\n dynamicImport('@tetherto/wdk-wallet-ton'),\n dynamicImport('@tetherto/wdk-wallet-tron'),\n dynamicImport('@tetherto/wdk-wallet-spark'),\n ]);\n\n WdkManager = wdk.default;\n WalletManagerBtc = btc.default;\n WalletManagerEvm = evm.default;\n WalletManagerSolana = solana.default;\n WalletManagerTon = ton.default;\n WalletManagerTron = tron.default;\n WalletManagerSpark = spark.default;\n wdkLoaded = true;\n } catch (error) {\n wdkLoadError = error instanceof Error ? error : new Error('Failed to load WDK modules');\n console.error('Failed to load WDK modules:', error);\n throw wdkLoadError;\n }\n}\n\n/**\n * Transaction parameters for sending\n */\nexport interface TransactionParams {\n /** Recipient address */\n to: string;\n /** Amount to send (in human-readable format, e.g., \"0.1\") */\n amount: string;\n /** Token address (optional, for ERC-20/SPL tokens) */\n token?: string;\n /** Transaction memo/message (for chains that support it) */\n memo?: string;\n /** Fee priority: 'slow' | 'medium' | 'fast' */\n feePriority?: 'slow' | 'medium' | 'fast';\n /** Custom gas limit (EVM chains) */\n gasLimit?: string;\n /** Custom gas price (EVM chains) */\n gasPrice?: string;\n}\n\n/**\n * Transaction result with detailed information\n */\nexport interface TransactionResult {\n /** Transaction hash */\n hash: string;\n /** Network/chain */\n network: NetworkType;\n /** Transaction status */\n status: 'pending' | 'confirmed' | 'failed';\n /** Block number (when confirmed) */\n blockNumber?: number;\n /** Gas used (EVM chains) */\n gasUsed?: string;\n /** Fee paid */\n fee?: string;\n /** Explorer URL */\n explorerUrl?: string;\n /** Error message if failed */\n error?: string;\n /** Timestamp */\n timestamp: number;\n}\n\n/**\n * Transaction history item\n */\nexport interface TransactionHistoryItem {\n hash: string;\n network: NetworkType;\n type: 'send' | 'receive' | 'swap' | 'contract';\n from: string;\n to: string;\n amount: string;\n token?: string;\n fee?: string;\n status: 'pending' | 'confirmed' | 'failed';\n timestamp: number;\n blockNumber?: number;\n}\n\n/**\n * Fee estimate for a transaction\n */\nexport interface FeeEstimate {\n slow: {\n fee: string;\n estimatedTime: string; // e.g., \"~30 min\"\n };\n medium: {\n fee: string;\n estimatedTime: string; // e.g., \"~5 min\"\n };\n fast: {\n fee: string;\n estimatedTime: string; // e.g., \"~1 min\"\n };\n}\n\n/**\n * Transaction Service configuration\n */\nexport interface TransactionServiceConfig {\n network: 'mainnet' | 'testnet';\n rpcUrls?: Partial<Record<NetworkType, string>>;\n}\n\n// Default RPC URLs\nconst DEFAULT_RPC_URLS = {\n mainnet: {\n ethereum: 'https://eth.llamarpc.com',\n bitcoin: '', // Uses Electrum\n solana: 'https://api.mainnet-beta.solana.com',\n ton: 'https://toncenter.com/api/v2/jsonRPC',\n tron: 'https://api.trongrid.io',\n spark: '', // Uses Spark network\n },\n testnet: {\n ethereum: 'https://ethereum-sepolia-rpc.publicnode.com',\n bitcoin: '', // Uses Electrum testnet\n solana: 'https://api.devnet.solana.com',\n ton: 'https://testnet.toncenter.com/api/v2/jsonRPC',\n tron: 'https://api.shasta.trongrid.io',\n spark: '', // Uses Spark testnet\n },\n};\n\n// Explorer URLs\nconst EXPLORER_URLS = {\n mainnet: {\n ethereum: 'https://etherscan.io/tx/',\n bitcoin: 'https://mempool.space/tx/',\n solana: 'https://solscan.io/tx/',\n ton: 'https://tonscan.org/tx/',\n tron: 'https://tronscan.org/#/transaction/',\n spark: 'https://spark.info/tx/',\n },\n testnet: {\n ethereum: 'https://sepolia.etherscan.io/tx/',\n bitcoin: 'https://mempool.space/testnet/tx/',\n solana: 'https://solscan.io/tx/?cluster=devnet&tx=',\n ton: 'https://testnet.tonscan.org/tx/',\n tron: 'https://shasta.tronscan.org/#/transaction/',\n spark: 'https://testnet.spark.info/tx/',\n },\n};\n\n/**\n * Transaction Service\n *\n * Provides multi-chain transaction capabilities:\n * - Send native tokens (ETH, BTC, SOL, TON, TRX)\n * - Send ERC-20/SPL tokens\n * - Fee estimation\n * - Transaction history\n */\nexport class TransactionService {\n private seed: string | null = null;\n private config: TransactionServiceConfig;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private wallets: Partial<Record<NetworkType, any>> = {};\n\n constructor(config: Partial<TransactionServiceConfig> = {}) {\n this.config = {\n network: config.network || 'testnet',\n rpcUrls: config.rpcUrls,\n };\n }\n\n /**\n * Ensure WDK modules are loaded\n */\n private async ensureLoaded(): Promise<void> {\n await loadWdkModules();\n }\n\n /**\n * Get RPC URL for a chain\n */\n private getRpcUrl(chain: NetworkType): string {\n const networkUrls = DEFAULT_RPC_URLS[this.config.network];\n\n if (this.config.rpcUrls?.[chain]) {\n return this.config.rpcUrls[chain]!;\n }\n\n return networkUrls[chain as keyof typeof networkUrls] || '';\n }\n\n /**\n * Get explorer URL for a transaction\n */\n getExplorerUrl(chain: NetworkType, txHash: string): string {\n const explorers = EXPLORER_URLS[this.config.network];\n const baseUrl = explorers[chain as keyof typeof explorers] || '';\n return `${baseUrl}${txHash}`;\n }\n\n /**\n * Initialize the service with a seed phrase\n */\n async initialize(seed: string): Promise<void> {\n await this.ensureLoaded();\n\n if (!WdkManager.isValidSeed(seed)) {\n throw new Error('Invalid seed phrase');\n }\n\n this.seed = seed;\n this.wallets = {};\n }\n\n /**\n * Check if service is initialized\n */\n isInitialized(): boolean {\n return this.seed !== null;\n }\n\n /**\n * Get or create wallet instance for a specific chain\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private async getWallet(chain: NetworkType): Promise<any> {\n if (!this.seed) {\n throw new Error('TransactionService not initialized. Call initialize() first.');\n }\n\n // Return cached wallet if exists\n if (this.wallets[chain]) {\n return this.wallets[chain];\n }\n\n const isTestnet = this.config.network === 'testnet';\n\n try {\n switch (chain) {\n case 'ethereum': {\n const rpcUrl = this.getRpcUrl('ethereum');\n const wallet = new WalletManagerEvm(this.seed, { provider: rpcUrl });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n case 'bitcoin': {\n const wallet = new WalletManagerBtc(this.seed, {\n network: isTestnet ? 'testnet' : 'bitcoin',\n });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n case 'solana': {\n const rpcUrl = this.getRpcUrl('solana');\n const wallet = new WalletManagerSolana(this.seed, {\n rpcUrl,\n });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n case 'ton': {\n const url = this.getRpcUrl('ton');\n const wallet = new WalletManagerTon(this.seed, {\n tonClient: { url },\n });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n case 'tron': {\n const fullHost = this.getRpcUrl('tron');\n const wallet = new WalletManagerTron(this.seed, {\n provider: fullHost,\n });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n case 'spark': {\n const wallet = new WalletManagerSpark(this.seed, {\n network: isTestnet ? 'TESTNET' : 'MAINNET',\n });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n default:\n throw new Error(`Unsupported chain: ${chain}`);\n }\n } catch (error) {\n console.error(`Failed to initialize ${chain} wallet:`, error);\n throw error;\n }\n }\n\n /**\n * Estimate transaction fee\n */\n async estimateFee(chain: NetworkType, params: TransactionParams): Promise<FeeEstimate> {\n const wallet = await this.getWallet(chain);\n\n try {\n // Get fee rates from the wallet\n const feeRates = await wallet.getFeeRates();\n\n // Format based on chain type\n if (chain === 'ethereum') {\n return {\n slow: {\n fee: `${feeRates.slow || '0'} Gwei`,\n estimatedTime: '~10 min',\n },\n medium: {\n fee: `${feeRates.medium || feeRates.standard || '0'} Gwei`,\n estimatedTime: '~3 min',\n },\n fast: {\n fee: `${feeRates.fast || feeRates.high || '0'} Gwei`,\n estimatedTime: '~30 sec',\n },\n };\n } else if (chain === 'bitcoin') {\n return {\n slow: {\n fee: `${feeRates.slow || feeRates.low || '0'} sat/vB`,\n estimatedTime: '~60 min',\n },\n medium: {\n fee: `${feeRates.medium || feeRates.normal || '0'} sat/vB`,\n estimatedTime: '~30 min',\n },\n fast: {\n fee: `${feeRates.fast || feeRates.high || '0'} sat/vB`,\n estimatedTime: '~10 min',\n },\n };\n } else {\n // Generic format for other chains\n return {\n slow: {\n fee: String(feeRates.slow || feeRates.low || '0'),\n estimatedTime: '~10 min',\n },\n medium: {\n fee: String(feeRates.medium || feeRates.standard || '0'),\n estimatedTime: '~3 min',\n },\n fast: {\n fee: String(feeRates.fast || feeRates.high || '0'),\n estimatedTime: '~1 min',\n },\n };\n }\n } catch (error) {\n console.error(`Error estimating fee for ${chain}:`, error);\n // Return default fees on error\n return {\n slow: { fee: '0', estimatedTime: 'Unknown' },\n medium: { fee: '0', estimatedTime: 'Unknown' },\n fast: { fee: '0', estimatedTime: 'Unknown' },\n };\n }\n }\n\n /**\n * Send a transaction\n */\n async send(chain: NetworkType, params: TransactionParams): Promise<TransactionResult> {\n const wallet = await this.getWallet(chain);\n const account = await wallet.getAccount(0);\n\n const timestamp = Date.now();\n\n try {\n // Build and send transaction based on chain\n let txHash: string;\n\n if (params.token) {\n // Token transfer (ERC-20, SPL, TRC-20, etc.)\n txHash = await account.sendToken(params.to, params.amount, params.token, {\n memo: params.memo,\n feePriority: params.feePriority || 'medium',\n });\n } else {\n // Native token transfer\n txHash = await account.send(params.to, params.amount, {\n memo: params.memo,\n feePriority: params.feePriority || 'medium',\n gasLimit: params.gasLimit,\n gasPrice: params.gasPrice,\n });\n }\n\n return {\n hash: txHash,\n network: chain,\n status: 'pending',\n explorerUrl: this.getExplorerUrl(chain, txHash),\n timestamp,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Transaction failed';\n console.error(`Transaction failed on ${chain}:`, error);\n\n return {\n hash: '',\n network: chain,\n status: 'failed',\n error: errorMessage,\n timestamp,\n };\n }\n }\n\n /**\n * Get transaction status\n */\n async getTransactionStatus(chain: NetworkType, txHash: string): Promise<TransactionResult> {\n const wallet = await this.getWallet(chain);\n\n try {\n const tx = await wallet.getTransaction(txHash);\n\n return {\n hash: txHash,\n network: chain,\n status: tx.confirmed ? 'confirmed' : 'pending',\n blockNumber: tx.blockNumber,\n gasUsed: tx.gasUsed?.toString(),\n fee: tx.fee?.toString(),\n explorerUrl: this.getExplorerUrl(chain, txHash),\n timestamp: tx.timestamp || Date.now(),\n };\n } catch (error) {\n console.error(`Error getting transaction status for ${txHash}:`, error);\n return {\n hash: txHash,\n network: chain,\n status: 'pending',\n explorerUrl: this.getExplorerUrl(chain, txHash),\n timestamp: Date.now(),\n };\n }\n }\n\n /**\n * Get transaction history for an address\n */\n async getTransactionHistory(\n chain: NetworkType,\n limit: number = 10\n ): Promise<TransactionHistoryItem[]> {\n const wallet = await this.getWallet(chain);\n const account = await wallet.getAccount(0);\n\n try {\n const history = await account.getTransactions({ limit });\n\n return history.map((tx: any) => ({\n hash: tx.hash || tx.txHash,\n network: chain,\n type: tx.type || (tx.from === account.address ? 'send' : 'receive'),\n from: tx.from,\n to: tx.to,\n amount: tx.amount || tx.value,\n token: tx.token,\n fee: tx.fee?.toString(),\n status: tx.confirmed ? 'confirmed' : 'pending',\n timestamp: tx.timestamp || Date.now(),\n blockNumber: tx.blockNumber,\n }));\n } catch (error) {\n console.error(`Error getting transaction history for ${chain}:`, error);\n return [];\n }\n }\n\n /**\n * Get balance for a specific chain\n */\n async getBalance(chain: NetworkType): Promise<{ balance: string; balanceUsd: number }> {\n const wallet = await this.getWallet(chain);\n const account = await wallet.getAccount(0);\n\n try {\n const balance = await account.getBalance();\n const balanceStr = balance.toString();\n\n // Fetch USD price for this chain\n const priceUsd = await getPriceForChain(chain);\n const balanceNum = parseFloat(balanceStr) || 0;\n const balanceUsd = balanceNum * priceUsd;\n\n return {\n balance: balanceStr,\n balanceUsd,\n };\n } catch (error) {\n console.error(`Error getting balance for ${chain}:`, error);\n return { balance: '0', balanceUsd: 0 };\n }\n }\n\n /**\n * Get the current network configuration\n */\n getNetwork(): 'mainnet' | 'testnet' {\n return this.config.network;\n }\n\n /**\n * Clean up and dispose of wallet instances\n */\n dispose(): void {\n for (const wallet of Object.values(this.wallets)) {\n if (wallet && typeof wallet.dispose === 'function') {\n try {\n wallet.dispose();\n } catch {\n // Ignore dispose errors\n }\n }\n }\n this.wallets = {};\n this.seed = null;\n }\n}\n\n// Singleton instance\nlet transactionServiceInstance: TransactionService | null = null;\n\n/**\n * Get or create the Transaction service singleton\n */\nexport function getTransactionService(config?: Partial<TransactionServiceConfig>): TransactionService {\n if (!transactionServiceInstance || (config && config.network !== transactionServiceInstance.getNetwork())) {\n transactionServiceInstance = new TransactionService(config);\n }\n return transactionServiceInstance;\n}\n\n/**\n * Create a new Transaction service instance (non-singleton)\n */\nexport function createTransactionService(config?: Partial<TransactionServiceConfig>): TransactionService {\n return new TransactionService(config);\n}\n"]}
1
+ {"version":3,"sources":["../../src/config/contracts.ts","../../src/services/SwapService.ts","../../src/services/WdkApiClient.ts","../../src/services/ZubariApiClient.ts","../../src/services/BrowserAddressDerivation.ts","../../src/services/ZubariWdkService.ts","../../src/services/TransactionService.ts"],"names":["DEFAULT_API_URL","HDNodeWallet","mnemonicToSeedSync","HDKey","ripemd160","sha256","bech32","base58check","validateMnemonic","wordlist","generateMnemonic","dynamicImport"],"mappings":";;;;;;;;;;;;;;;;;AAqDO,IAAM,eAAA,GAAkB;AAAA,EAMd;AAAA,EAEf,kBAAA,EAAoB,EAAA;AAAA,EAEgB;AAAA,EAEpC,kBAAkB,EAAA,GAAK;AACzB,CAAA;;;AC9DA,IAAM,iBAAA,GAAoB;AAAA,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AAK,MAAA,CAAO,OAAA;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA,EAKA,OAAA,GAAgB;AACd,IAAA,KAAA,MAAW,MAAA,IAAU,MAAA,CAAO,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,EAAG;AAChD,MAAA,IAAI,MAAA,IAAU,OAAO,MAAA,CAAO,OAAA,KAAY,UAAA,EAAY;AAClD,QAAA,IAAI;AACF,UAAA,MAAA,CAAO,OAAA,EAAQ;AAAA,QACjB,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AACA,IAAA,IAAA,CAAK,UAAU,EAAC;AAChB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAGA,IAAI,0BAAA,GAAwD,IAAA;AAKrD,SAAS,sBAAsB,MAAA,EAAgE;AACpG,EAAA,IAAI,CAAC,0BAAA,IAA+B,MAAA,IAAU,OAAO,OAAA,KAAY,0BAAA,CAA2B,YAAW,EAAI;AACzG,IAAA,0BAAA,GAA6B,IAAI,mBAAmB,MAAM,CAAA;AAAA,EAC5D;AACA,EAAA,OAAO,0BAAA;AACT;AAKO,SAAS,yBAAyB,MAAA,EAAgE;AACvG,EAAA,OAAO,IAAI,mBAAmB,MAAM,CAAA;AACtC","file":"index.js","sourcesContent":["// Contract addresses for Zubari ecosystem\nexport interface ContractAddresses {\n registry: string;\n nft: string;\n nft1155: string; // ERC-1155 multi-edition NFT\n marketplace: string;\n tips: string;\n subscriptions: string;\n payouts: string;\n entryPoint: string;\n paymaster: string;\n accountFactory: string;\n usdt: string;\n weth: string;\n}\n\n// Zero address for ETH payments and placeholder addresses\nexport const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';\n\nexport const ZUBARI_CONTRACTS: Record<'testnet' | 'mainnet', ContractAddresses> = {\n testnet: {\n // Ethereum Sepolia (11155111) - Deployed 2024-12-31\n registry: '0xe5CE1Eb986f58BE42EEDFe5C18ee5956803b2BDC',\n nft: '0xc165b8C6843e8f0B1489525D0f853d23f22c677B', // ZubariNFT ERC-721 with payment\n nft1155: '0x5e618B5bEaE1dc41369E7aa235Cc3b9245905192', // Zubari1155 ERC-1155 multi-edition\n marketplace: '0xfcEfDa6C73aC357b8695E5F8F8d17820750BF207',\n tips: '0x86a9A306C7fCC9e0B8cd6859f6f15498d0046BB7',\n subscriptions: '0xaB7F17A85F61d9ab9f96bCB4e73e910D019978F7',\n payouts: '0x8aaB23Fb2a83A259E965Aae8Ee0938b1400B7E6b',\n entryPoint: '0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789',\n paymaster: ZERO_ADDRESS, // Deploy with: npx hardhat run deploy/deploy.ts --network ethereum-sepolia\n accountFactory: ZERO_ADDRESS, // Not yet deployed\n usdt: '0xaA8E23Fb1079EA71e0a56F48a2aA51851D8433D0', // USDT on Sepolia\n weth: '0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14',\n },\n mainnet: {\n // Ethereum Mainnet (1)\n registry: ZERO_ADDRESS,\n nft: ZERO_ADDRESS,\n nft1155: ZERO_ADDRESS,\n marketplace: ZERO_ADDRESS,\n tips: ZERO_ADDRESS,\n subscriptions: ZERO_ADDRESS,\n payouts: ZERO_ADDRESS,\n entryPoint: '0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789',\n paymaster: ZERO_ADDRESS,\n accountFactory: ZERO_ADDRESS,\n usdt: '0xdAC17F958D2ee523a2206206994597C13D831ec7', // USDT on Ethereum\n weth: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n },\n};\n\n// Platform configuration\nexport const PLATFORM_CONFIG = {\n // Platform fee in basis points (1000 = 10%)\n // Zubari keeps 10%, Creator receives 90%\n platformFeeBps: 1000,\n tipFeeBps: 1000, // Alias for backward compatibility\n // Maximum royalty in basis points (1000 = 10%)\n maxRoyaltyBps: 1000,\n // Default slippage tolerance for swaps (50 = 0.5%)\n defaultSlippageBps: 50,\n // Voucher validity in seconds (30 days)\n voucherValiditySecs: 30 * 24 * 60 * 60,\n // Swap deadline in seconds (30 minutes)\n swapDeadlineSecs: 30 * 60,\n} as const;\n\n// EIP-712 Domain for lazy minting\nexport const NFT_VOUCHER_DOMAIN = {\n name: 'ZubariNFT',\n version: '1',\n} as const;\n\nexport const NFT_VOUCHER_TYPES = {\n NFTVoucher: [\n { name: 'tokenId', type: 'bytes32' },\n { name: 'uri', type: 'string' },\n { name: 'creator', type: 'address' },\n { name: 'royaltyBps', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n // Pricing fields\n { name: 'price', type: 'uint256' },\n { name: 'currency', type: 'address' },\n { name: 'nonce', type: 'uint256' },\n // Watermarking fields\n { name: 'contentHash', type: 'bytes32' },\n { name: 'userId', type: 'bytes32' },\n { name: 'watermarkTimestamp', type: 'uint256' },\n { name: 'sessionId', type: 'bytes32' },\n ],\n} as const;\n\n// EIP-712 Domain for ERC-1155 edition minting\nexport const EDITION_VOUCHER_DOMAIN = {\n name: 'Zubari1155',\n version: '1',\n} as const;\n\n// EIP-712 Types for EditionVoucher (ERC-1155)\nexport const EDITION_VOUCHER_TYPES = {\n EditionVoucher: [\n { name: 'tokenId', type: 'bytes32' },\n { name: 'uri', type: 'string' },\n { name: 'creator', type: 'address' },\n { name: 'maxSupply', type: 'uint256' },\n { name: 'royaltyBps', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n ],\n} as const;\n\n// Currency addresses per network\nexport const CURRENCY_ADDRESSES = {\n testnet: {\n ETH: ZERO_ADDRESS,\n USDT: '0xaA8E23Fb1079EA71e0a56F48a2aA51851D8433D0', // USDT on Sepolia\n },\n mainnet: {\n ETH: ZERO_ADDRESS,\n USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7', // USDT on Ethereum\n },\n} as const;\n\nexport function getContractAddresses(network: 'testnet' | 'mainnet'): ContractAddresses {\n return ZUBARI_CONTRACTS[network];\n}\n\n// Multi-chain Fee/Treasury Wallet Addresses\n// These wallets receive platform fees from transactions on their respective chains\nexport interface FeeWalletConfig {\n address: string;\n name: string;\n network: string;\n chainId?: number;\n}\n\nexport type SupportedFeeChain = 'ETH' | 'BTC' | 'SOLANA' | 'TON' | 'TRON';\n\n/**\n * Mainnet Fee Wallet Addresses\n * These are the production treasury wallets for collecting platform fees\n */\nexport const MAINNET_FEE_WALLETS: Record<SupportedFeeChain, FeeWalletConfig> = {\n // Ethereum (ETH, ERC-20 tokens like USDT)\n ETH: {\n address: '0x40Df60a57d02a7bB04B6624c65E2908Cc006badE',\n name: 'Zubari ETH Treasury',\n network: 'ethereum',\n chainId: 1,\n },\n // Bitcoin\n BTC: {\n address: 'bc1qh20fx23wk34pcm3zp0v9wctwprtl02uvh6q9qj',\n name: 'Zubari BTC Treasury',\n network: 'bitcoin',\n },\n // Solana (SOL, SPL tokens)\n SOLANA: {\n address: '2hXGumVRpD5KgdqNZUuYJ2YoyLR6jc8mvWbubciWjPuZ',\n name: 'Zubari Solana Treasury',\n network: 'solana',\n },\n // TON (The Open Network)\n TON: {\n address: 'UQB5hOrm9YGoKjrCVmvAUFgmApkvKWqVMROjieKs3z4kDz99',\n name: 'Zubari TON Treasury',\n network: 'ton',\n },\n // Tron (TRX, TRC-20 tokens like USDT)\n TRON: {\n address: 'TVBPjQFNe8JgVctDKWMxJNgjbPZoP6uu5h',\n name: 'Zubari Tron Treasury',\n network: 'tron',\n },\n} as const;\n\n/**\n * Testnet Fee Wallet Addresses\n * These are used for development and testing\n */\nexport const TESTNET_FEE_WALLETS: Record<SupportedFeeChain, FeeWalletConfig> = {\n // Ethereum Sepolia\n ETH: {\n address: ZERO_ADDRESS, // Configure via environment\n name: 'Zubari ETH Testnet Treasury',\n network: 'sepolia',\n chainId: 11155111,\n },\n // Bitcoin Testnet\n BTC: {\n address: '',\n name: 'Zubari BTC Testnet Treasury',\n network: 'bitcoin-testnet',\n },\n // Solana Devnet\n SOLANA: {\n address: '',\n name: 'Zubari Solana Devnet Treasury',\n network: 'solana-devnet',\n },\n // TON Testnet\n TON: {\n address: '',\n name: 'Zubari TON Testnet Treasury',\n network: 'ton-testnet',\n },\n // Tron Shasta Testnet\n TRON: {\n address: '',\n name: 'Zubari Tron Testnet Treasury',\n network: 'tron-shasta',\n },\n} as const;\n\n/**\n * Get fee wallet address for a specific chain\n * @param chain - The blockchain network\n * @param isMainnet - Whether to use mainnet addresses (default: false for testnet)\n */\nexport function getFeeWallet(chain: SupportedFeeChain, isMainnet: boolean = false): FeeWalletConfig {\n return isMainnet ? MAINNET_FEE_WALLETS[chain] : TESTNET_FEE_WALLETS[chain];\n}\n\n/**\n * Get all fee wallets for a network type\n * @param isMainnet - Whether to use mainnet addresses\n */\nexport function getAllFeeWallets(isMainnet: boolean = false): Record<SupportedFeeChain, FeeWalletConfig> {\n return isMainnet ? MAINNET_FEE_WALLETS : TESTNET_FEE_WALLETS;\n}\n","import type { SwapQuote, TxResult, TokenInfo } from '../types';\nimport { PLATFORM_CONFIG, getContractAddresses } from '../config/contracts';\n\n// Uniswap V3 contract addresses (Ethereum mainnet)\nconst UNISWAP_ADDRESSES = {\n mainnet: {\n swapRouter: '0xE592427A0AEce92De3Edee1F18E0157C05861564',\n quoter: '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6',\n factory: '0x1F98431c8aD98523631AE4a59f267346ea31F984',\n },\n sepolia: {\n swapRouter: '0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48E',\n quoter: '0xEd1f6473345F45b75F8179591dd5bA1888cf2FB3',\n factory: '0x0227628f3F023bb0B980b67D528571c95c6DaC1c',\n },\n};\n\n// Uniswap V3 function selectors\nconst UNISWAP_SELECTORS = {\n quoteExactInputSingle: '0xf7729d43', // quoteExactInputSingle(address,address,uint24,uint256,uint160)\n exactInputSingle: '0x414bf389', // exactInputSingle((address,address,uint24,address,uint256,uint256,uint256,uint160))\n};\n\n// Common token addresses\nconst TOKENS = {\n mainnet: {\n WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n USDC: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n },\n sepolia: {\n WETH: '0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14',\n USDT: '0x7169D38820dfd117C3FA1f22a697dBA58d90BA06',\n USDC: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',\n },\n};\n\n// Zero address for native ETH\nconst ETH_ADDRESS = '0x0000000000000000000000000000000000000000';\n\n/**\n * SwapService - DEX integration via Uniswap V3\n *\n * Handles token swaps with slippage protection,\n * quote fetching, and earnings conversion.\n */\nexport class SwapService {\n private readonly chainId: number;\n private readonly isTestnet: boolean;\n private readonly addresses: typeof UNISWAP_ADDRESSES.mainnet;\n private readonly tokens: typeof TOKENS.mainnet;\n\n constructor(chainId: number, isTestnet: boolean = false) {\n this.chainId = chainId;\n this.isTestnet = isTestnet;\n this.addresses = isTestnet ? UNISWAP_ADDRESSES.sepolia : UNISWAP_ADDRESSES.mainnet;\n this.tokens = isTestnet ? TOKENS.sepolia : TOKENS.mainnet;\n }\n\n /**\n * Get a swap quote from Uniswap V3 Quoter\n */\n async getQuote(\n tokenIn: string,\n tokenOut: string,\n amountIn: bigint,\n provider?: { call: (tx: object) => Promise<string> }\n ): Promise<SwapQuote> {\n if (amountIn <= 0n) {\n throw new Error('Amount must be greater than 0');\n }\n\n // Convert ETH address to WETH\n const actualTokenIn = tokenIn === ETH_ADDRESS ? this.tokens.WETH : tokenIn;\n const actualTokenOut = tokenOut === ETH_ADDRESS ? this.tokens.WETH : tokenOut;\n\n if (!provider) {\n // Return estimate without actual quote\n console.warn('No provider for quote, returning estimate');\n return {\n tokenIn,\n tokenOut,\n amountIn,\n amountOut: amountIn * BigInt(95) / BigInt(100), // Rough estimate\n priceImpact: 0.5,\n route: [tokenIn, tokenOut],\n estimatedGas: BigInt(150000),\n };\n }\n\n try {\n // Encode quoteExactInputSingle call\n // quoteExactInputSingle(address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96)\n const encodedTokenIn = actualTokenIn.toLowerCase().replace('0x', '').padStart(64, '0');\n const encodedTokenOut = actualTokenOut.toLowerCase().replace('0x', '').padStart(64, '0');\n const encodedFee = (3000).toString(16).padStart(64, '0'); // 0.3% fee tier\n const encodedAmountIn = amountIn.toString(16).padStart(64, '0');\n const encodedSqrtPriceLimit = '0'.padStart(64, '0'); // No price limit\n\n const data = `${UNISWAP_SELECTORS.quoteExactInputSingle}${encodedTokenIn}${encodedTokenOut}${encodedFee}${encodedAmountIn}${encodedSqrtPriceLimit}`;\n\n const result = await provider.call({\n to: this.addresses.quoter,\n data,\n });\n\n // Decode the result (uint256 amountOut)\n const amountOut = BigInt(result);\n\n // Calculate price impact\n const priceImpact = this.calculatePriceImpact(amountIn, amountOut, tokenIn, tokenOut);\n\n return {\n tokenIn,\n tokenOut,\n amountIn,\n amountOut,\n priceImpact,\n route: [tokenIn, tokenOut],\n estimatedGas: BigInt(150000),\n };\n } catch (error) {\n console.error('Failed to get quote:', error);\n throw new Error(`Quote failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n\n /**\n * Execute a swap with slippage protection via Uniswap V3 SwapRouter\n */\n async executeSwap(\n quote: SwapQuote,\n signer: { sendTransaction: (tx: object) => Promise<{ hash: string }> },\n recipient: string,\n slippageToleranceBps: number = PLATFORM_CONFIG.defaultSlippageBps\n ): Promise<TxResult> {\n // Calculate minimum output with slippage\n const minAmountOut = quote.amountOut - (quote.amountOut * BigInt(slippageToleranceBps)) / BigInt(10000);\n\n // Calculate deadline\n const deadline = Math.floor(Date.now() / 1000) + PLATFORM_CONFIG.swapDeadlineSecs;\n\n // Warn if price impact is high\n if (quote.priceImpact > 5) {\n console.warn(`High price impact: ${quote.priceImpact}%`);\n }\n\n // Convert ETH address to WETH for router\n const actualTokenIn = quote.tokenIn === ETH_ADDRESS ? this.tokens.WETH : quote.tokenIn;\n const actualTokenOut = quote.tokenOut === ETH_ADDRESS ? this.tokens.WETH : quote.tokenOut;\n const isETHIn = quote.tokenIn === ETH_ADDRESS;\n\n try {\n // Encode exactInputSingle call\n // struct ExactInputSingleParams {\n // address tokenIn;\n // address tokenOut;\n // uint24 fee;\n // address recipient;\n // uint256 deadline;\n // uint256 amountIn;\n // uint256 amountOutMinimum;\n // uint160 sqrtPriceLimitX96;\n // }\n const encodedTokenIn = actualTokenIn.toLowerCase().replace('0x', '').padStart(64, '0');\n const encodedTokenOut = actualTokenOut.toLowerCase().replace('0x', '').padStart(64, '0');\n const encodedFee = (3000).toString(16).padStart(64, '0');\n const encodedRecipient = recipient.toLowerCase().replace('0x', '').padStart(64, '0');\n const encodedDeadline = deadline.toString(16).padStart(64, '0');\n const encodedAmountIn = quote.amountIn.toString(16).padStart(64, '0');\n const encodedMinAmountOut = minAmountOut.toString(16).padStart(64, '0');\n const encodedSqrtPriceLimit = '0'.padStart(64, '0');\n\n const data = `${UNISWAP_SELECTORS.exactInputSingle}${encodedTokenIn}${encodedTokenOut}${encodedFee}${encodedRecipient}${encodedDeadline}${encodedAmountIn}${encodedMinAmountOut}${encodedSqrtPriceLimit}`;\n\n const tx = await signer.sendTransaction({\n to: this.addresses.swapRouter,\n data,\n value: isETHIn ? `0x${quote.amountIn.toString(16)}` : '0x0',\n });\n\n return {\n hash: tx.hash,\n network: 'ethereum',\n status: 'pending',\n metadata: {\n tokenIn: quote.tokenIn,\n tokenOut: quote.tokenOut,\n amountIn: quote.amountIn.toString(),\n minAmountOut: minAmountOut.toString(),\n deadline,\n },\n };\n } catch (error) {\n console.error('Failed to execute swap:', error);\n throw new Error(`Swap failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n\n /**\n * Convert earnings to USDT, keeping some ETH for gas\n */\n async convertEarningsToStable(\n ethBalance: bigint,\n signer: { sendTransaction: (tx: object) => Promise<{ hash: string }> },\n recipient: string,\n provider?: { call: (tx: object) => Promise<string> },\n reserveForGas: bigint = BigInt('10000000000000000') // 0.01 ETH\n ): Promise<TxResult> {\n const amountToSwap = ethBalance - reserveForGas;\n\n if (amountToSwap <= 0n) {\n throw new Error('Insufficient balance after gas reserve');\n }\n\n // Get quote for ETH -> USDT\n const quote = await this.getQuote(\n ETH_ADDRESS,\n this.tokens.USDT,\n amountToSwap,\n provider\n );\n\n return this.executeSwap(quote, signer, recipient);\n }\n\n /**\n * Check if a swap route exists\n */\n async hasRoute(\n tokenIn: string,\n tokenOut: string,\n provider?: { call: (tx: object) => Promise<string> }\n ): Promise<boolean> {\n try {\n const quote = await this.getQuote(tokenIn, tokenOut, BigInt(10 ** 18), provider);\n return quote.amountOut > 0n;\n } catch {\n return false;\n }\n }\n\n /**\n * Get supported tokens for swapping\n */\n async getSupportedTokens(): Promise<TokenInfo[]> {\n return [\n { address: ETH_ADDRESS, symbol: 'ETH', decimals: 18, name: 'Ether' },\n { address: this.tokens.WETH, symbol: 'WETH', decimals: 18, name: 'Wrapped Ether' },\n { address: this.tokens.USDT, symbol: 'USDT', decimals: 6, name: 'Tether USD' },\n { address: this.tokens.USDC, symbol: 'USDC', decimals: 6, name: 'USD Coin' },\n ];\n }\n\n /**\n * Get Uniswap router address for approvals\n */\n getRouterAddress(): string {\n return this.addresses.swapRouter;\n }\n\n /**\n * Calculate price impact (simplified)\n */\n private calculatePriceImpact(\n amountIn: bigint,\n amountOut: bigint,\n _tokenIn: string,\n _tokenOut: string\n ): number {\n // Simplified price impact calculation\n // In production, would compare to oracle price\n if (amountIn === 0n || amountOut === 0n) return 0;\n\n // Assume 1:1 ratio for ETH:stablecoin as baseline\n // Real implementation would use price feeds\n const expectedOut = amountIn; // Simplified\n const actualRatio = Number(amountOut) / Number(expectedOut);\n const impact = (1 - actualRatio) * 100;\n\n return Math.max(0, impact);\n }\n}\n","/**\n * WDK API Client\n *\n * Client for calling the backend WDK endpoints to derive addresses\n * using Tether WDK (which runs server-side in Node.js).\n */\n\nimport type { NetworkType } from '../types';\n\nexport interface WdkApiConfig {\n baseUrl: string;\n timeout?: number;\n}\n\nexport interface DeriveAddressResponse {\n success: boolean;\n address?: string;\n chain?: string;\n path?: string;\n network?: string;\n error?: string;\n}\n\nexport interface DeriveAllAddressesResponse {\n success: boolean;\n addresses?: {\n ethereum: string | null;\n bitcoin: string | null;\n ton: string | null;\n tron: string | null;\n solana: string | null;\n spark: string | null;\n };\n network?: string;\n error?: string;\n}\n\nexport interface ValidateSeedResponse {\n success: boolean;\n isValid?: boolean;\n wordCount?: number;\n error?: string;\n}\n\nexport interface GenerateSeedResponse {\n success: boolean;\n seed?: string;\n wordCount?: number;\n error?: string;\n}\n\nexport interface TransactionHistoryItem {\n hash: string;\n from: string;\n to: string;\n value: string;\n timestamp: number;\n status: 'confirmed' | 'pending' | 'failed';\n blockNumber?: number;\n}\n\nexport interface TransactionHistoryResponse {\n success: boolean;\n address?: string;\n transactions?: TransactionHistoryItem[];\n chain?: string;\n network?: string;\n error?: string;\n}\n\nexport interface SendTransactionResponse {\n success: boolean;\n txHash?: string;\n from?: string;\n to?: string;\n amount?: string;\n chain?: string;\n network?: string;\n error?: string;\n}\n\nexport interface TransactionStatusResponse {\n success: boolean;\n hash?: string;\n status?: 'confirmed' | 'pending' | 'failed';\n blockNumber?: number;\n confirmations?: number;\n timestamp?: number;\n from?: string;\n to?: string;\n value?: string;\n fee?: string;\n chain?: string;\n network?: string;\n error?: string;\n}\n\n/**\n * WDK API Client for server-side Tether WDK integration\n */\nexport class WdkApiClient {\n private config: Required<WdkApiConfig>;\n\n constructor(config: WdkApiConfig) {\n this.config = {\n baseUrl: config.baseUrl,\n timeout: config.timeout || 30000,\n };\n }\n\n /**\n * Generate a new BIP-39 seed phrase using Tether WDK\n */\n async generateSeed(): Promise<GenerateSeedResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/generate-seed`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to generate seed',\n };\n }\n }\n\n /**\n * Validate a BIP-39 seed phrase\n */\n async validateSeed(seed: string): Promise<ValidateSeedResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/validate-seed`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ seed }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to validate seed',\n };\n }\n }\n\n /**\n * Derive address for a specific chain using Tether WDK\n */\n async deriveAddress(\n seed: string,\n chain: NetworkType,\n network: 'mainnet' | 'testnet' = 'testnet'\n ): Promise<DeriveAddressResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-address`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ seed, chain, network }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to derive address',\n };\n }\n }\n\n /**\n * Derive addresses for all chains using Tether WDK\n */\n async deriveAllAddresses(\n seed: string,\n network: 'mainnet' | 'testnet' = 'testnet'\n ): Promise<DeriveAllAddressesResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/derive-all`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ seed, network }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to derive addresses',\n };\n }\n }\n\n /**\n * Send a transaction on a specific chain using Tether WDK\n */\n async sendTransaction(\n seed: string,\n chain: NetworkType,\n to: string,\n amount: string,\n network: 'mainnet' | 'testnet' = 'testnet'\n ): Promise<SendTransactionResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/send`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ seed, chain, to, amount, network }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to send transaction',\n };\n }\n }\n\n /**\n * Get transaction history for an address on a specific chain\n * Fetches from blockchain explorers (Etherscan, mempool.space, etc.)\n */\n async getTransactionHistory(\n seed: string,\n chain: NetworkType,\n network: 'mainnet' | 'testnet' = 'testnet',\n limit: number = 10\n ): Promise<TransactionHistoryResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/history`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ seed, chain, network, limit }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get transaction history',\n };\n }\n }\n\n /**\n * Get transaction status by hash\n * Fetches from blockchain explorers to check confirmation status\n */\n async getTransactionStatus(\n txHash: string,\n chain: NetworkType,\n network: 'mainnet' | 'testnet' = 'testnet'\n ): Promise<TransactionStatusResponse> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/wallets/wdk/tx-status`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ txHash, chain, network }),\n });\n\n return await response.json();\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get transaction status',\n };\n }\n }\n}\n\n// Default API URL (can be overridden)\n// Uses the Zubari production API which has Tether WDK integrated\nconst DEFAULT_API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://ckgwifsxka.us-east-2.awsapprunner.com';\n\n// Singleton instance\nlet wdkApiClient: WdkApiClient | null = null;\n\n/**\n * Get or create the WDK API client instance\n */\nexport function getWdkApiClient(baseUrl?: string): WdkApiClient {\n if (!wdkApiClient || (baseUrl && wdkApiClient['config'].baseUrl !== baseUrl)) {\n wdkApiClient = new WdkApiClient({\n baseUrl: baseUrl || DEFAULT_API_URL,\n });\n }\n return wdkApiClient;\n}\n","/**\n * Zubari API Client\n *\n * Comprehensive client for interacting with the Zubari backend API.\n * Includes NFT, Marketplace, Tips, and Subscription operations.\n */\n\nimport type { NetworkType, NFTCurrency } from '../types';\n\nexport interface ZubariApiConfig {\n baseUrl: string;\n timeout?: number;\n authToken?: string;\n}\n\n// ============ NFT Types ============\n\nexport interface NFTVoucher {\n tokenId: string;\n uri: string;\n creator: string;\n royaltyBps: number;\n deadline: number;\n signature: string;\n price: string;\n currency: string;\n nonce: number;\n contentHash?: string;\n userId?: string;\n watermarkTimestamp?: number;\n sessionId?: string;\n}\n\nexport interface CreateVoucherRequest {\n creatorAddress: string;\n price: string;\n currency: NFTCurrency;\n}\n\nexport interface CreateVoucherResponse {\n success: boolean;\n voucher?: NFTVoucher;\n signature?: string;\n nftId?: string;\n error?: string;\n}\n\nexport interface RedeemVoucherRequest {\n buyerAddress: string;\n paymentTxHash?: string;\n}\n\nexport interface RedeemVoucherResponse {\n success: boolean;\n transactionHash?: string;\n tokenId?: string;\n owner?: string;\n nftId?: string;\n error?: string;\n}\n\nexport interface VoucherStatusResponse {\n success: boolean;\n nftId?: string;\n hasVoucher?: boolean;\n isRedeemed?: boolean;\n voucher?: NFTVoucher;\n error?: string;\n}\n\nexport interface NFTResponse {\n id: string;\n tokenId?: string;\n contractAddress?: string;\n name: string;\n description?: string;\n imageUrl?: string;\n animationUrl?: string;\n externalUrl?: string;\n attributes?: Array<{\n trait_type: string;\n value: string | number;\n }>;\n creatorId: string;\n ownerId: string;\n price?: string;\n currency?: string;\n royaltyBps: number;\n isLazyMinted: boolean;\n isMinted: boolean;\n mintedAt?: string;\n transactionHash?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface CreateNFTRequest {\n name: string;\n description?: string;\n price: string;\n currency: NFTCurrency;\n royaltyBps?: number;\n attributes?: Array<{\n trait_type: string;\n value: string | number;\n }>;\n externalUrl?: string;\n}\n\nexport interface NFTListResponse {\n success: boolean;\n nfts?: NFTResponse[];\n pagination?: {\n page: number;\n limit: number;\n total: number;\n pages: number;\n };\n error?: string;\n}\n\n// ============ Marketplace Types ============\n\nexport interface MarketListing {\n id: string;\n nftId: string;\n nft?: NFTResponse;\n sellerId: string;\n sellerAddress: string;\n price: string;\n currency: string;\n expiresAt: string;\n status: 'ACTIVE' | 'SOLD' | 'CANCELLED' | 'EXPIRED';\n transactionHash?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ListItemRequest {\n nftId: string;\n price: string;\n currency: NFTCurrency;\n duration?: number; // Duration in seconds, default 7 days\n}\n\nexport interface ListItemResponse {\n success: boolean;\n listing?: MarketListing;\n transactionHash?: string;\n error?: string;\n}\n\nexport interface BuyItemRequest {\n listingId: string;\n buyerAddress: string;\n}\n\nexport interface BuyItemResponse {\n success: boolean;\n transactionHash?: string;\n tokenId?: string;\n newOwner?: string;\n error?: string;\n}\n\nexport interface CancelListingRequest {\n listingId: string;\n}\n\nexport interface CancelListingResponse {\n success: boolean;\n transactionHash?: string;\n error?: string;\n}\n\nexport interface UpdatePriceRequest {\n listingId: string;\n newPrice: string;\n}\n\nexport interface UpdatePriceResponse {\n success: boolean;\n listing?: MarketListing;\n transactionHash?: string;\n error?: string;\n}\n\nexport interface ListingsResponse {\n success: boolean;\n listings?: MarketListing[];\n pagination?: {\n page: number;\n limit: number;\n total: number;\n pages: number;\n };\n error?: string;\n}\n\nexport interface MarketStatsResponse {\n success: boolean;\n stats?: {\n totalListings: number;\n activeListings: number;\n totalVolume: string;\n totalSales: number;\n averagePrice: string;\n topSellers: Array<{\n address: string;\n sales: number;\n volume: string;\n }>;\n };\n error?: string;\n}\n\n// ============ Filter Types ============\n\nexport interface NFTFilters {\n creatorId?: string;\n ownerId?: string;\n isLazyMinted?: boolean;\n isMinted?: boolean;\n minPrice?: string;\n maxPrice?: string;\n currency?: NFTCurrency;\n page?: number;\n limit?: number;\n}\n\nexport interface ListingFilters {\n sellerId?: string;\n status?: 'ACTIVE' | 'SOLD' | 'CANCELLED' | 'EXPIRED';\n minPrice?: string;\n maxPrice?: string;\n currency?: NFTCurrency;\n sortBy?: 'price' | 'createdAt' | 'expiresAt';\n sortOrder?: 'asc' | 'desc';\n page?: number;\n limit?: number;\n}\n\n// ============ Tips Types ============\n\nexport interface TipUser {\n id: string;\n username?: string;\n displayName?: string;\n avatarUrl?: string;\n}\n\nexport interface Tip {\n id: string;\n senderId: string;\n recipientId?: string;\n senderAddress: string;\n recipientAddress: string;\n tokenAddress?: string;\n amount: string;\n amountUsd?: string;\n platformFee: string;\n message?: string;\n network: string;\n transactionHash?: string;\n status: 'PENDING' | 'CONFIRMED' | 'FAILED';\n createdAt: string;\n sender?: TipUser;\n recipient?: TipUser;\n}\n\nexport interface SendTipRequest {\n recipientAddress: string;\n recipientUsername?: string;\n amount: string;\n tokenAddress?: string;\n network?: string;\n message?: string;\n transactionHash?: string;\n}\n\nexport interface SendTipResponse {\n success: boolean;\n message?: string;\n tip?: Tip;\n platformFee?: string;\n platformFeeBps?: number;\n error?: string;\n}\n\nexport interface TipStatsResponse {\n success: boolean;\n sent?: {\n count: number;\n totalAmount: string;\n totalAmountUsd: string;\n };\n received?: {\n count: number;\n totalAmount: string;\n totalAmountUsd: string;\n platformFees: string;\n };\n error?: string;\n}\n\nexport interface TipsListResponse {\n success: boolean;\n tips?: Tip[];\n pagination?: {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n };\n totals?: {\n count: number;\n amount: string;\n amountUsd: string;\n };\n error?: string;\n}\n\nexport interface TipFilters {\n page?: number;\n limit?: number;\n status?: 'PENDING' | 'CONFIRMED' | 'FAILED';\n}\n\nexport interface UpdateTipStatusRequest {\n status: 'PENDING' | 'CONFIRMED' | 'FAILED';\n transactionHash?: string;\n}\n\n// ============ Subscription Types ============\n\nexport interface SubscriptionPlan {\n id: string;\n creatorId: string;\n name: string;\n description?: string;\n price: string;\n priceUsd?: string;\n paymentToken?: string;\n durationDays: number;\n perks: string[];\n nftBadge: boolean;\n maxSubscribers?: number;\n isActive: boolean;\n activeSubscribers?: number;\n createdAt: string;\n updatedAt: string;\n creator?: TipUser & { isVerified?: boolean };\n}\n\nexport interface Subscription {\n id: string;\n planId: string;\n subscriberId: string;\n creatorId: string;\n subscriberAddress?: string;\n creatorAddress?: string;\n transactionHash?: string;\n amount?: string;\n startDate: string;\n endDate: string;\n expiresAt: string;\n autoRenew: boolean;\n status: 'ACTIVE' | 'EXPIRED' | 'CANCELLED';\n createdAt: string;\n plan?: Partial<SubscriptionPlan>;\n creator?: TipUser & { isVerified?: boolean };\n subscriber?: TipUser;\n}\n\nexport interface CreatePlanRequest {\n name: string;\n description?: string;\n price: string;\n priceUsd?: number;\n paymentToken?: string;\n durationDays?: number;\n perks?: string[];\n nftBadge?: boolean;\n maxSubscribers?: number;\n}\n\nexport interface CreatePlanResponse {\n success: boolean;\n message?: string;\n plan?: SubscriptionPlan;\n error?: string;\n}\n\nexport interface SubscribeRequest {\n planId: string;\n transactionHash?: string;\n autoRenew?: boolean;\n}\n\nexport interface SubscribeResponse {\n success: boolean;\n message?: string;\n subscription?: Subscription;\n error?: string;\n}\n\nexport interface SubscriptionListResponse {\n success: boolean;\n subscriptions?: Subscription[];\n pagination?: {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n };\n stats?: {\n totalSubscribers: number;\n };\n error?: string;\n}\n\nexport interface SubscriptionFilters {\n page?: number;\n limit?: number;\n status?: 'ACTIVE' | 'EXPIRED' | 'CANCELLED';\n}\n\nexport interface ContractSubscribeRequest {\n planId: string;\n months?: number;\n seed: string;\n}\n\nexport interface ContractSubscribeResponse {\n success: boolean;\n transactionHash?: string;\n subscription?: Subscription;\n message?: string;\n error?: string;\n}\n\nexport interface ContractCreatePlanRequest {\n name: string;\n description?: string;\n price: string;\n paymentToken?: string;\n durationDays?: number;\n maxSubscribers?: number;\n seed: string;\n}\n\nexport interface ContractCreatePlanResponse {\n success: boolean;\n transactionHash?: string;\n plan?: SubscriptionPlan;\n message?: string;\n error?: string;\n}\n\nexport interface IsSubscribedResponse {\n subscriber: string;\n creator: string;\n isSubscribed: boolean;\n}\n\nexport interface PlatformFeeResponse {\n feeBps: number;\n feePercent: string;\n}\n\n// ============ Payouts Types ============\n\nexport interface EarningsResponse {\n success: boolean;\n address?: string;\n pendingEarnings?: string;\n totalEarnings?: string;\n earningsBreakdown?: {\n tips: string;\n subscriptions: string;\n nftSales: string;\n royalties: string;\n };\n recentPayouts?: Array<{\n id: string;\n amount: string;\n txHash: string;\n createdAt: string;\n }>;\n error?: string;\n}\n\nexport interface ClaimEarningsRequest {\n seed: string;\n}\n\nexport interface ClaimEarningsResponse {\n success: boolean;\n transactionHash?: string;\n amount?: string;\n message?: string;\n error?: string;\n}\n\nexport interface PayoutHistoryResponse {\n success: boolean;\n payouts?: Array<{\n id: string;\n amount: string;\n status: string;\n txHash: string;\n createdAt: string;\n confirmedAt?: string;\n }>;\n pagination?: {\n page: number;\n limit: number;\n total: number;\n pages: number;\n };\n error?: string;\n}\n\nexport interface EarningsBreakdownResponse {\n success: boolean;\n breakdown?: {\n tips: string;\n subscriptions: string;\n nftSales: string;\n royalties: string;\n total: string;\n };\n percentages?: {\n tips: string;\n subscriptions: string;\n nftSales: string;\n royalties: string;\n };\n error?: string;\n}\n\n/**\n * Zubari API Client for backend integration\n */\nexport class ZubariApiClient {\n private config: Required<Omit<ZubariApiConfig, 'authToken'>> & { authToken?: string };\n\n constructor(config: ZubariApiConfig) {\n this.config = {\n baseUrl: config.baseUrl.replace(/\\/$/, ''), // Remove trailing slash\n timeout: config.timeout || 30000,\n authToken: config.authToken,\n };\n }\n\n /**\n * Set the authentication token\n */\n setAuthToken(token: string): void {\n this.config.authToken = token;\n }\n\n /**\n * Clear the authentication token\n */\n clearAuthToken(): void {\n this.config.authToken = undefined;\n }\n\n /**\n * Make an authenticated request to the API\n */\n private async request<T>(\n method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE',\n path: string,\n body?: unknown\n ): Promise<T> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.config.authToken) {\n headers['Authorization'] = `Bearer ${this.config.authToken}`;\n }\n\n const response = await fetch(`${this.config.baseUrl}${path}`, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);\n }\n\n return response.json();\n }\n\n // ============ NFT Methods ============\n\n /**\n * Get all NFTs with optional filters\n */\n async getNFTs(filters?: NFTFilters): Promise<NFTListResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/nfts${queryString ? `?${queryString}` : ''}`;\n return await this.request<NFTListResponse>('GET', path);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get NFTs',\n };\n }\n }\n\n /**\n * Get a single NFT by ID\n */\n async getNFT(nftId: string): Promise<{ success: boolean; nft?: NFTResponse; error?: string }> {\n try {\n const nft = await this.request<NFTResponse>('GET', `/api/nfts/${nftId}`);\n return { success: true, nft };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get NFT',\n };\n }\n }\n\n /**\n * Create a new NFT (lazy minted)\n */\n async createNFT(\n data: CreateNFTRequest,\n image: File | Blob\n ): Promise<{ success: boolean; nft?: NFTResponse; error?: string }> {\n try {\n const formData = new FormData();\n formData.append('image', image);\n formData.append('name', data.name);\n if (data.description) formData.append('description', data.description);\n formData.append('price', data.price);\n formData.append('currency', data.currency);\n if (data.royaltyBps !== undefined) formData.append('royaltyBps', String(data.royaltyBps));\n if (data.attributes) formData.append('attributes', JSON.stringify(data.attributes));\n if (data.externalUrl) formData.append('externalUrl', data.externalUrl);\n\n const headers: Record<string, string> = {};\n if (this.config.authToken) {\n headers['Authorization'] = `Bearer ${this.config.authToken}`;\n }\n\n const response = await fetch(`${this.config.baseUrl}/api/nfts`, {\n method: 'POST',\n headers,\n body: formData,\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(errorData.error || `HTTP ${response.status}`);\n }\n\n const nft = await response.json();\n return { success: true, nft };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create NFT',\n };\n }\n }\n\n /**\n * Create a voucher for an NFT (EIP-712 signed)\n */\n async createVoucher(nftId: string, params: CreateVoucherRequest): Promise<CreateVoucherResponse> {\n try {\n return await this.request<CreateVoucherResponse>('POST', `/api/nfts/${nftId}/voucher`, params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create voucher',\n };\n }\n }\n\n /**\n * Redeem an NFT voucher (buy/mint)\n */\n async redeemVoucher(nftId: string, params: RedeemVoucherRequest): Promise<RedeemVoucherResponse> {\n try {\n return await this.request<RedeemVoucherResponse>('POST', `/api/nfts/${nftId}/redeem`, params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to redeem voucher',\n };\n }\n }\n\n /**\n * Get voucher status for an NFT\n */\n async getVoucherStatus(nftId: string): Promise<VoucherStatusResponse> {\n try {\n return await this.request<VoucherStatusResponse>('GET', `/api/nfts/${nftId}/voucher/status`);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get voucher status',\n };\n }\n }\n\n // ============ Marketplace Methods ============\n\n /**\n * Get all active listings\n */\n async getListings(filters?: ListingFilters): Promise<ListingsResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/market/listings${queryString ? `?${queryString}` : ''}`;\n return await this.request<ListingsResponse>('GET', path);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get listings',\n };\n }\n }\n\n /**\n * List an NFT for sale\n */\n async listItem(params: ListItemRequest): Promise<ListItemResponse> {\n try {\n return await this.request<ListItemResponse>('POST', '/api/market/list', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to list item',\n };\n }\n }\n\n /**\n * Buy a listed NFT\n */\n async buyItem(params: BuyItemRequest): Promise<BuyItemResponse> {\n try {\n return await this.request<BuyItemResponse>('POST', '/api/market/buy', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to buy item',\n };\n }\n }\n\n /**\n * Cancel a listing\n */\n async cancelListing(params: CancelListingRequest): Promise<CancelListingResponse> {\n try {\n return await this.request<CancelListingResponse>('POST', '/api/market/cancel', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to cancel listing',\n };\n }\n }\n\n /**\n * Update listing price\n */\n async updateListingPrice(params: UpdatePriceRequest): Promise<UpdatePriceResponse> {\n try {\n return await this.request<UpdatePriceResponse>('PATCH', '/api/market/price', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to update price',\n };\n }\n }\n\n /**\n * Get current user's listings\n */\n async getMyListings(filters?: Omit<ListingFilters, 'sellerId'>): Promise<ListingsResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/market/my/listings${queryString ? `?${queryString}` : ''}`;\n return await this.request<ListingsResponse>('GET', path);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get my listings',\n };\n }\n }\n\n /**\n * Get marketplace statistics\n */\n async getMarketStats(): Promise<MarketStatsResponse> {\n try {\n return await this.request<MarketStatsResponse>('GET', '/api/market/stats');\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get market stats',\n };\n }\n }\n\n // ============ Tips Methods ============\n\n /**\n * Send a tip to a creator\n */\n async sendTip(params: SendTipRequest): Promise<SendTipResponse> {\n try {\n return await this.request<SendTipResponse>('POST', '/api/tips', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to send tip',\n };\n }\n }\n\n /**\n * Get tip statistics for current user\n */\n async getTipStats(): Promise<TipStatsResponse> {\n try {\n const data = await this.request<{\n sent: { count: number; totalAmount: string; totalAmountUsd: string };\n received: { count: number; totalAmount: string; totalAmountUsd: string; platformFees: string };\n }>('GET', '/api/tips/my/stats');\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get tip stats',\n };\n }\n }\n\n /**\n * Get tips sent by current user\n */\n async getSentTips(filters?: TipFilters): Promise<TipsListResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/tips/sent${queryString ? `?${queryString}` : ''}`;\n const data = await this.request<{\n tips: Tip[];\n pagination: { page: number; limit: number; total: number; totalPages: number };\n totals: { count: number; amount: string; amountUsd: string };\n }>('GET', path);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get sent tips',\n };\n }\n }\n\n /**\n * Get tips received by current user\n */\n async getReceivedTips(filters?: TipFilters): Promise<TipsListResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/tips/received${queryString ? `?${queryString}` : ''}`;\n const data = await this.request<{\n tips: Tip[];\n pagination: { page: number; limit: number; total: number; totalPages: number };\n totals: { count: number; amount: string; amountUsd: string };\n }>('GET', path);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get received tips',\n };\n }\n }\n\n /**\n * Get a single tip by ID\n */\n async getTip(tipId: string): Promise<{ success: boolean; tip?: Tip; error?: string }> {\n try {\n const data = await this.request<{ tip: Tip }>('GET', `/api/tips/${tipId}`);\n return { success: true, tip: data.tip };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get tip',\n };\n }\n }\n\n /**\n * Update tip status (for transaction confirmation)\n */\n async updateTipStatus(\n tipId: string,\n params: UpdateTipStatusRequest\n ): Promise<{ success: boolean; tip?: Tip; message?: string; error?: string }> {\n try {\n const data = await this.request<{ message: string; tip: Tip }>(\n 'PATCH',\n `/api/tips/${tipId}/status`,\n params\n );\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to update tip status',\n };\n }\n }\n\n // ============ Subscription Methods ============\n\n /**\n * Create a new subscription plan (creator only)\n */\n async createSubscriptionPlan(params: CreatePlanRequest): Promise<CreatePlanResponse> {\n try {\n return await this.request<CreatePlanResponse>('POST', '/api/subscriptions/plans', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create subscription plan',\n };\n }\n }\n\n /**\n * Get current user's subscription plans\n */\n async getMySubscriptionPlans(): Promise<{ success: boolean; plans?: SubscriptionPlan[]; error?: string }> {\n try {\n const data = await this.request<{ plans: SubscriptionPlan[] }>('GET', '/api/subscriptions/plans');\n return { success: true, plans: data.plans };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get subscription plans',\n };\n }\n }\n\n /**\n * Get subscription plan by ID\n */\n async getSubscriptionPlan(\n planId: string\n ): Promise<{ success: boolean; plan?: SubscriptionPlan & { isSubscribed?: boolean }; error?: string }> {\n try {\n const plan = await this.request<SubscriptionPlan & { isSubscribed?: boolean }>(\n 'GET',\n `/api/subscriptions/plans/${planId}`\n );\n return { success: true, plan };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get subscription plan',\n };\n }\n }\n\n /**\n * Delete/deactivate subscription plan\n */\n async deleteSubscriptionPlan(\n planId: string\n ): Promise<{ success: boolean; message?: string; deactivated?: boolean; error?: string }> {\n try {\n const data = await this.request<{ message: string; deactivated?: boolean }>(\n 'DELETE',\n `/api/subscriptions/plans/${planId}`\n );\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to delete subscription plan',\n };\n }\n }\n\n /**\n * Subscribe to a plan\n */\n async subscribe(params: SubscribeRequest): Promise<SubscribeResponse> {\n try {\n return await this.request<SubscribeResponse>('POST', '/api/subscriptions/subscribe', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to subscribe',\n };\n }\n }\n\n /**\n * Get current user's subscriptions (as subscriber)\n */\n async getMySubscriptions(filters?: SubscriptionFilters): Promise<SubscriptionListResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/subscriptions${queryString ? `?${queryString}` : ''}`;\n const data = await this.request<{\n subscriptions: Subscription[];\n pagination: { page: number; limit: number; total: number; totalPages: number };\n }>('GET', path);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get subscriptions',\n };\n }\n }\n\n /**\n * Get subscribers to current user's plans (as creator)\n */\n async getMySubscribers(filters?: SubscriptionFilters): Promise<SubscriptionListResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/subscriptions/subscribers${queryString ? `?${queryString}` : ''}`;\n const data = await this.request<{\n subscriptions: Subscription[];\n pagination: { page: number; limit: number; total: number; totalPages: number };\n stats: { totalSubscribers: number };\n }>('GET', path);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get subscribers',\n };\n }\n }\n\n /**\n * Cancel subscription\n */\n async cancelSubscription(subscriptionId: string): Promise<{ success: boolean; message?: string; error?: string }> {\n try {\n const data = await this.request<{ message: string }>('DELETE', `/api/subscriptions/${subscriptionId}`);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to cancel subscription',\n };\n }\n }\n\n /**\n * Create a subscription plan on-chain\n */\n async createSubscriptionPlanOnChain(params: ContractCreatePlanRequest): Promise<ContractCreatePlanResponse> {\n try {\n return await this.request<ContractCreatePlanResponse>('POST', '/api/subscriptions/contract/plans', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to create plan on-chain',\n };\n }\n }\n\n /**\n * Subscribe to a plan on-chain\n */\n async subscribeOnChain(params: ContractSubscribeRequest): Promise<ContractSubscribeResponse> {\n try {\n return await this.request<ContractSubscribeResponse>('POST', '/api/subscriptions/contract/subscribe', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to subscribe on-chain',\n };\n }\n }\n\n /**\n * Cancel subscription on-chain\n */\n async cancelSubscriptionOnChain(\n subscriptionId: string,\n seed: string\n ): Promise<{ success: boolean; transactionHash?: string; message?: string; error?: string }> {\n try {\n return await this.request<{ success: boolean; transactionHash: string; message: string }>(\n 'POST',\n '/api/subscriptions/contract/cancel',\n { subscriptionId, seed }\n );\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to cancel subscription on-chain',\n };\n }\n }\n\n /**\n * Check if user is subscribed to a creator on-chain\n */\n async isSubscribed(subscriber: string, creator: string): Promise<IsSubscribedResponse> {\n try {\n return await this.request<IsSubscribedResponse>(\n 'GET',\n `/api/subscriptions/contract/is-subscribed?subscriber=${subscriber}&creator=${creator}`\n );\n } catch (error) {\n return {\n subscriber,\n creator,\n isSubscribed: false,\n };\n }\n }\n\n /**\n * Get subscription platform fee\n */\n async getSubscriptionPlatformFee(): Promise<PlatformFeeResponse> {\n try {\n return await this.request<PlatformFeeResponse>('GET', '/api/subscriptions/platform-fee');\n } catch (error) {\n return {\n feeBps: 0,\n feePercent: '0',\n };\n }\n }\n\n // ============ Payouts Methods ============\n\n /**\n * Get pending and claimed earnings for the authenticated user\n */\n async getEarnings(): Promise<EarningsResponse> {\n try {\n const data = await this.request<{\n address: string;\n pendingEarnings: string;\n totalEarnings: string;\n earningsBreakdown: { tips: string; subscriptions: string; nftSales: string; royalties: string };\n recentPayouts: Array<{ id: string; amount: string; txHash: string; createdAt: string }>;\n }>('GET', '/api/payouts/earnings');\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get earnings',\n };\n }\n }\n\n /**\n * Claim pending earnings\n */\n async claimEarnings(params: ClaimEarningsRequest): Promise<ClaimEarningsResponse> {\n try {\n return await this.request<ClaimEarningsResponse>('POST', '/api/payouts/claim', params);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to claim earnings',\n };\n }\n }\n\n /**\n * Get payout history for the authenticated user\n */\n async getPayoutHistory(filters?: { page?: number; limit?: number }): Promise<PayoutHistoryResponse> {\n try {\n const params = new URLSearchParams();\n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value !== undefined) {\n params.append(key, String(value));\n }\n });\n }\n const queryString = params.toString();\n const path = `/api/payouts/history${queryString ? `?${queryString}` : ''}`;\n const data = await this.request<{\n payouts: Array<{\n id: string;\n amount: string;\n status: string;\n txHash: string;\n createdAt: string;\n confirmedAt?: string;\n }>;\n pagination: { page: number; limit: number; total: number; pages: number };\n }>('GET', path);\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get payout history',\n };\n }\n }\n\n /**\n * Get earnings breakdown by source\n */\n async getEarningsBreakdown(): Promise<EarningsBreakdownResponse> {\n try {\n const data = await this.request<{\n breakdown: { tips: string; subscriptions: string; nftSales: string; royalties: string; total: string };\n percentages: { tips: string; subscriptions: string; nftSales: string; royalties: string };\n }>('GET', '/api/payouts/breakdown');\n return { success: true, ...data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Failed to get earnings breakdown',\n };\n }\n }\n\n /**\n * Get current platform fee for payouts\n */\n async getPayoutsPlatformFee(): Promise<PlatformFeeResponse> {\n try {\n return await this.request<PlatformFeeResponse>('GET', '/api/payouts/platform-fee');\n } catch (error) {\n return {\n feeBps: 0,\n feePercent: '0',\n };\n }\n }\n}\n\n// Default API URL (can be overridden)\nconst DEFAULT_API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://ckgwifsxka.us-east-2.awsapprunner.com';\n\n// Singleton instance\nlet zubariApiClient: ZubariApiClient | null = null;\n\n/**\n * Get or create the Zubari API client instance\n */\nexport function getZubariApiClient(config?: Partial<ZubariApiConfig>): ZubariApiClient {\n if (!zubariApiClient || (config?.baseUrl && zubariApiClient['config'].baseUrl !== config.baseUrl)) {\n zubariApiClient = new ZubariApiClient({\n baseUrl: config?.baseUrl || DEFAULT_API_URL,\n timeout: config?.timeout,\n authToken: config?.authToken,\n });\n } else if (config?.authToken) {\n zubariApiClient.setAuthToken(config.authToken);\n }\n return zubariApiClient;\n}\n\n/**\n * Create a new Zubari API client instance\n */\nexport function createZubariApiClient(config: ZubariApiConfig): ZubariApiClient {\n return new ZubariApiClient(config);\n}\n","/**\n * Browser-Compatible Address Derivation\n *\n * This module provides multi-chain address derivation that works in browser environments.\n * It uses the @scure libraries which are pure JS and don't require Node.js polyfills.\n *\n * Supported chains:\n * - Ethereum: ethers.js (BIP-44)\n * - Bitcoin: @scure/bip32 + @scure/base (BIP-84 native SegWit)\n * - Solana: ed25519-hd-key + tweetnacl (SLIP-0010)\n * - TON: ed25519 derivation with TON address format\n * - TRON: secp256k1 + base58check\n * - Spark: Bitcoin-based with custom derivation\n */\n\nimport { HDNodeWallet, keccak256, getBytes, sha256 as ethSha256 } from 'ethers';\nimport { mnemonicToSeedSync, validateMnemonic, generateMnemonic } from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english';\nimport { HDKey } from '@scure/bip32';\nimport { bech32, base58check } from '@scure/base';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\nimport type { NetworkType } from '../types';\n\nexport interface ChainAddress {\n chain: NetworkType;\n address: string;\n path: string;\n}\n\nexport interface BrowserMultiChainAddresses {\n ethereum: string | null;\n bitcoin: string | null;\n ton: string | null;\n tron: string | null;\n solana: string | null;\n spark: string | null;\n}\n\n// BIP-44/84 derivation paths\nconst DERIVATION_PATHS = {\n ethereum: \"m/44'/60'/0'/0/0\",\n bitcoin_mainnet: \"m/84'/0'/0'/0/0\",\n bitcoin_testnet: \"m/84'/1'/0'/0/0\",\n ton: \"m/44'/607'/0'/0'/0'\",\n tron: \"m/44'/195'/0'/0/0\",\n solana: \"m/44'/501'/0'/0'\",\n spark: \"m/44'/998'/0'/0/0\",\n};\n\n/**\n * Derive Ethereum address from seed phrase\n */\nexport function deriveEthereumAddress(seed: string): string {\n const hdNode = HDNodeWallet.fromPhrase(seed, undefined, DERIVATION_PATHS.ethereum);\n return hdNode.address;\n}\n\n/**\n * Derive Bitcoin address from seed phrase (BIP-84 native SegWit)\n * Uses @scure libraries for browser compatibility\n */\nexport function deriveBitcoinAddress(\n seed: string,\n network: 'mainnet' | 'testnet' = 'testnet'\n): string {\n try {\n // Convert mnemonic to seed using @scure/bip39\n const seedBytes = mnemonicToSeedSync(seed);\n\n // Derive HD key using @scure/bip32\n const hdKey = HDKey.fromMasterSeed(seedBytes);\n const path = network === 'testnet' ? DERIVATION_PATHS.bitcoin_testnet : DERIVATION_PATHS.bitcoin_mainnet;\n const child = hdKey.derive(path);\n\n if (!child.publicKey) {\n throw new Error('Failed to derive public key');\n }\n\n // Create P2WPKH address (native SegWit)\n // 1. Hash160 = RIPEMD160(SHA256(publicKey))\n const pubKeyHash = ripemd160(sha256(child.publicKey));\n\n // 2. Create witness program: version (0x00) + hash160\n // For bech32, we encode: witness version (0) + pubKeyHash as 5-bit words\n const witnessVersion = 0;\n const words = bech32.toWords(pubKeyHash);\n words.unshift(witnessVersion); // Prepend witness version\n\n // 3. Encode with bech32\n const hrp = network === 'testnet' ? 'tb' : 'bc';\n const address = bech32.encode(hrp, words);\n\n return address;\n } catch (error) {\n console.error('Bitcoin address derivation failed:', error);\n throw error;\n }\n}\n\n/**\n * Derive Solana address from seed phrase using SLIP-0010 (ed25519)\n */\nexport async function deriveSolanaAddress(seed: string): Promise<string> {\n try {\n const [ed25519, nacl, bs58Module] = await Promise.all([\n import('ed25519-hd-key'),\n import('tweetnacl'),\n import('bs58'),\n ]);\n\n // bs58 v6 uses default export\n const bs58 = bs58Module.default || bs58Module;\n\n // Use @scure/bip39 for seed generation (browser compatible)\n const seedBytes = mnemonicToSeedSync(seed);\n\n // SLIP-0010 derivation for ed25519\n const derived = ed25519.derivePath(DERIVATION_PATHS.solana, Buffer.from(seedBytes).toString('hex'));\n\n // Create keypair from derived seed\n const keypair = nacl.sign.keyPair.fromSeed(new Uint8Array(derived.key));\n\n // Solana address is the base58-encoded public key (32 bytes)\n return bs58.encode(keypair.publicKey);\n } catch (error) {\n console.error('Solana address derivation failed:', error);\n throw error;\n }\n}\n\n/**\n * Derive TON address from seed phrase\n * Uses proper BIP-44 derivation path m/44'/607'/0'/0'/0'\n */\nexport async function deriveTonAddress(seed: string): Promise<string> {\n try {\n const [ed25519, nacl] = await Promise.all([\n import('ed25519-hd-key'),\n import('tweetnacl'),\n ]);\n\n // Use @scure/bip39 for seed generation (browser compatible)\n const seedBytes = mnemonicToSeedSync(seed);\n\n // Use SLIP-0010 derivation for ed25519 with TON's coin type\n const derived = ed25519.derivePath(DERIVATION_PATHS.ton, Buffer.from(seedBytes).toString('hex'));\n\n // Create keypair\n const keypair = nacl.sign.keyPair.fromSeed(new Uint8Array(derived.key));\n\n // TON address is derived from public key using workchain + hash\n // Standard TON wallet v4r2 uses the public key to derive address\n const publicKey = keypair.publicKey;\n\n // Create TON bounceable address (EQ prefix for workchain 0)\n // Format: 1 byte flags + 1 byte workchain + 32 bytes hash + 2 bytes CRC16\n const workchain = 0;\n const flags = 0x11; // bounceable\n\n // For raw address, we use SHA256 of public key using @noble/hashes\n const hash = sha256(publicKey);\n\n // Build address bytes: flags + workchain + hash\n const addressData = new Uint8Array(34);\n addressData[0] = flags;\n addressData[1] = workchain;\n addressData.set(hash, 2);\n\n // Calculate CRC16\n const crc = crc16(addressData);\n\n // Full address with CRC\n const fullAddress = new Uint8Array(36);\n fullAddress.set(addressData);\n fullAddress[34] = (crc >> 8) & 0xff;\n fullAddress[35] = crc & 0xff;\n\n // Convert to base64url (TON standard format)\n const base64 = btoa(String.fromCharCode(...fullAddress))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n\n return base64;\n } catch (error) {\n console.error('TON address derivation failed:', error);\n throw error;\n }\n}\n\n/**\n * CRC16-CCITT for TON addresses\n */\nfunction crc16(data: Uint8Array): number {\n let crc = 0;\n for (const byte of data) {\n crc ^= byte << 8;\n for (let i = 0; i < 8; i++) {\n crc = (crc & 0x8000) ? ((crc << 1) ^ 0x1021) : (crc << 1);\n crc &= 0xffff;\n }\n }\n return crc;\n}\n\n/**\n * Derive TRON address from seed phrase\n * TRON uses secp256k1 like Ethereum but with base58check encoding\n * Uses @scure/base for browser compatibility\n */\nexport function deriveTronAddress(seed: string): string {\n try {\n // Derive using TRON's BIP-44 path\n const hdNode = HDNodeWallet.fromPhrase(seed, undefined, DERIVATION_PATHS.tron);\n\n // Get the Ethereum-style address (last 20 bytes of keccak256 of public key)\n // TRON uses same derivation but different encoding\n const ethAddressHex = hdNode.address.slice(2).toLowerCase();\n\n // TRON address: 0x41 prefix + 20 bytes address\n const addressBytes = new Uint8Array(21);\n addressBytes[0] = 0x41; // TRON mainnet prefix\n\n // Copy ETH address bytes\n for (let i = 0; i < 20; i++) {\n addressBytes[i + 1] = parseInt(ethAddressHex.slice(i * 2, i * 2 + 2), 16);\n }\n\n // Base58check encode using @scure/base (uses double SHA256 for checksum)\n const tronBase58check = base58check(sha256);\n return tronBase58check.encode(addressBytes);\n } catch (error) {\n console.error('TRON address derivation failed:', error);\n throw error;\n }\n}\n\n/**\n * Derive Spark address from seed phrase\n * Spark uses its own derivation path and bech32 format\n * Uses @scure libraries for browser compatibility\n */\nexport function deriveSparkAddress(\n seed: string,\n network: 'mainnet' | 'testnet' = 'testnet'\n): string {\n try {\n // Convert mnemonic to seed using @scure/bip39\n const seedBytes = mnemonicToSeedSync(seed);\n\n // Derive HD key using @scure/bip32\n const hdKey = HDKey.fromMasterSeed(seedBytes);\n const child = hdKey.derive(DERIVATION_PATHS.spark);\n\n if (!child.publicKey) {\n throw new Error('Failed to derive public key');\n }\n\n // Create P2WPKH-style address (same as Bitcoin but with Spark HRP)\n // 1. Hash160 = RIPEMD160(SHA256(publicKey))\n const pubKeyHash = ripemd160(sha256(child.publicKey));\n\n // 2. Create witness program with version 0\n const witnessVersion = 0;\n const words = bech32.toWords(pubKeyHash);\n words.unshift(witnessVersion);\n\n // 3. Encode with bech32 using Spark's HRP\n // Note: Spark uses 'sp' for mainnet and 'tsp' for testnet\n const hrp = network === 'testnet' ? 'tsp' : 'sp';\n const address = bech32.encode(hrp, words);\n\n return address;\n } catch (error) {\n console.error('Spark address derivation failed:', error);\n throw error;\n }\n}\n\n/**\n * Derive addresses for all supported chains\n */\nexport async function deriveAllAddresses(\n seed: string,\n network: 'mainnet' | 'testnet' = 'testnet'\n): Promise<BrowserMultiChainAddresses> {\n const addresses: BrowserMultiChainAddresses = {\n ethereum: null,\n bitcoin: null,\n ton: null,\n tron: null,\n solana: null,\n spark: null,\n };\n\n // Derive synchronous chains first (Ethereum, Bitcoin, Spark, TRON)\n try {\n addresses.ethereum = deriveEthereumAddress(seed);\n } catch (e) {\n console.error('ETH derivation failed:', e);\n }\n\n try {\n addresses.bitcoin = deriveBitcoinAddress(seed, network);\n } catch (e) {\n console.error('BTC derivation failed:', e);\n }\n\n try {\n addresses.spark = deriveSparkAddress(seed, network);\n } catch (e) {\n console.error('Spark derivation failed:', e);\n }\n\n try {\n addresses.tron = deriveTronAddress(seed);\n } catch (e) {\n console.error('TRON derivation failed:', e);\n }\n\n // Derive async chains in parallel (Solana, TON use ed25519 which requires async imports)\n const [solResult, tonResult] = await Promise.allSettled([\n deriveSolanaAddress(seed),\n deriveTonAddress(seed),\n ]);\n\n if (solResult.status === 'fulfilled') {\n addresses.solana = solResult.value;\n } else {\n console.error('SOL derivation failed:', solResult.reason);\n }\n\n if (tonResult.status === 'fulfilled') {\n addresses.ton = tonResult.value;\n } else {\n console.error('TON derivation failed:', tonResult.reason);\n }\n\n return addresses;\n}\n\n/**\n * Validate a BIP-39 seed phrase using @scure/bip39\n */\nexport function isValidSeed(seed: string): boolean {\n return validateMnemonic(seed, wordlist);\n}\n\n/**\n * Generate a random BIP-39 seed phrase using @scure/bip39\n */\nexport function generateSeedPhrase(): string {\n return generateMnemonic(wordlist);\n}\n","/**\n * Zubari WDK Service - Unified Multi-Chain Wallet Service\n *\n * This service provides a unified interface for multi-chain wallet operations\n * that works in both browser and Node.js environments.\n *\n * Strategy:\n * - Browser: Uses WdkApiClient to call the backend API (which has Tether WDK)\n * - Node.js: Uses WdkService natively (with Tether WDK modules)\n *\n * The Tether WDK (@tetherto/wdk-*) only works in Node.js environments due to\n * native dependencies (Electrum client, gRPC, etc.). For browser environments,\n * we route all operations through the backend API.\n *\n * @see https://docs.wallet.tether.io/\n */\n\nimport { WdkApiClient, getWdkApiClient } from './WdkApiClient';\nimport * as BrowserDerivation from './BrowserAddressDerivation';\nimport type { NetworkType } from '../types';\n\n// Default API URL for the Zubari backend with Tether WDK\nconst DEFAULT_API_URL = 'https://ckgwifsxka.us-east-2.awsapprunner.com';\n\nexport type SupportedChain = 'ethereum' | 'bitcoin' | 'ton' | 'tron' | 'solana' | 'spark';\n\nexport interface ChainAddress {\n chain: SupportedChain;\n address: string;\n path: string;\n}\n\nexport interface MultiChainAddresses {\n ethereum: string | null;\n bitcoin: string | null;\n ton: string | null;\n tron: string | null;\n solana: string | null;\n spark: string | null;\n}\n\nexport interface ChainBalance {\n chain: SupportedChain;\n address: string;\n balance: string;\n symbol: string;\n}\n\nexport interface FeeRates {\n slow: string;\n normal: string;\n fast: string;\n}\n\nexport interface TransactionResult {\n success: boolean;\n txHash?: string;\n from?: string;\n to?: string;\n amount?: string;\n chain?: string;\n network?: string;\n error?: string;\n}\n\nexport interface ZubariWdkServiceConfig {\n /** Network to use (mainnet or testnet) */\n network: 'mainnet' | 'testnet';\n /** API URL for the Zubari backend (required for browser environments) */\n apiUrl?: string;\n /** Force using API even in Node.js (useful for testing) */\n forceApi?: boolean;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\n/**\n * Check if we're running in a browser environment\n */\nfunction isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n}\n\n/**\n * Dynamic import helper that bypasses bundler analysis\n * This ensures the import is truly runtime and not analyzed at build time\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst dynamicImport = new Function('specifier', 'return import(specifier)') as (\n specifier: string\n) => Promise<any>;\n\n/**\n * Check if native WDK modules are available (Node.js only)\n */\nasync function canUseNativeWdk(): Promise<boolean> {\n // Never use native WDK in browser\n if (isBrowser()) {\n return false;\n }\n\n try {\n // Try to dynamically import WDK to check if it's available\n await dynamicImport('@tetherto/wdk');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * ZubariWdkService - Unified wallet service for browser and Node.js\n *\n * This service automatically routes operations to:\n * - API backend (browser) - using WdkApiClient\n * - Native WDK (Node.js) - using WdkService\n * - Browser derivation (fallback) - using BrowserAddressDerivation\n */\nexport class ZubariWdkService {\n private config: Required<ZubariWdkServiceConfig>;\n private apiClient: WdkApiClient;\n private nativeWdkService: unknown | null = null;\n private initialized = false;\n private useNativeWdk = false;\n\n constructor(config: Partial<ZubariWdkServiceConfig> = {}) {\n this.config = {\n network: config.network || 'testnet',\n apiUrl: config.apiUrl || process.env.NEXT_PUBLIC_API_URL || DEFAULT_API_URL,\n forceApi: config.forceApi ?? false,\n timeout: config.timeout || 30000,\n };\n\n this.apiClient = getWdkApiClient(this.config.apiUrl);\n }\n\n /**\n * Initialize the service and determine the best strategy\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n // In browser or if forceApi is set, always use API\n if (isBrowser() || this.config.forceApi) {\n this.useNativeWdk = false;\n this.initialized = true;\n return;\n }\n\n // In Node.js, try to use native WDK\n if (await canUseNativeWdk()) {\n try {\n // Use dynamic import helper to bypass bundler analysis\n // This ensures WdkService is never included in browser bundles\n const WdkServiceModule = await dynamicImport('./WdkService');\n const WdkService = WdkServiceModule.WdkService || WdkServiceModule.default;\n this.nativeWdkService = new WdkService({\n network: this.config.network,\n });\n this.useNativeWdk = true;\n } catch (error) {\n console.warn('Failed to initialize native WDK, falling back to API:', error);\n this.useNativeWdk = false;\n }\n }\n\n this.initialized = true;\n }\n\n /**\n * Get the current execution mode\n */\n getMode(): 'api' | 'native' | 'browser-fallback' {\n if (this.useNativeWdk) return 'native';\n if (isBrowser()) return 'api';\n return 'api';\n }\n\n /**\n * Check if running in browser\n */\n isBrowserEnvironment(): boolean {\n return isBrowser();\n }\n\n /**\n * Generate a new BIP-39 seed phrase (12 words)\n */\n async generateSeed(): Promise<string> {\n await this.initialize();\n\n // Try API first (most reliable, uses real WDK)\n try {\n const response = await this.apiClient.generateSeed();\n if (response.success && response.seed) {\n return response.seed;\n }\n } catch (error) {\n console.warn('API seed generation failed:', error);\n }\n\n // Try native WDK\n if (this.useNativeWdk && this.nativeWdkService) {\n try {\n const wdk = this.nativeWdkService as { generateSeedPhrase: () => Promise<string> };\n return await wdk.generateSeedPhrase();\n } catch (error) {\n console.warn('Native WDK seed generation failed:', error);\n }\n }\n\n // Fallback to browser-compatible generation\n return BrowserDerivation.generateSeedPhrase();\n }\n\n /**\n * Validate a BIP-39 seed phrase\n */\n async validateSeed(seed: string): Promise<boolean> {\n await this.initialize();\n\n // Try API first\n try {\n const response = await this.apiClient.validateSeed(seed);\n if (response.success) {\n return response.isValid ?? false;\n }\n } catch (error) {\n console.warn('API seed validation failed:', error);\n }\n\n // Try native WDK\n if (this.useNativeWdk && this.nativeWdkService) {\n try {\n const wdk = this.nativeWdkService as { isValidSeed: (seed: string) => Promise<boolean> };\n return await wdk.isValidSeed(seed);\n } catch (error) {\n console.warn('Native WDK seed validation failed:', error);\n }\n }\n\n // Fallback to browser-compatible validation\n return BrowserDerivation.isValidSeed(seed);\n }\n\n /**\n * Derive address for a specific chain using WDK API\n *\n * For Ethereum, falls back to local derivation if API fails.\n * For other chains, WDK API is required - no placeholder fallback.\n */\n async deriveAddress(seed: string, chain: SupportedChain): Promise<ChainAddress> {\n await this.initialize();\n\n const path = this.getDerivationPath(chain);\n\n // Try API first (uses real WDK on backend)\n try {\n const response = await this.apiClient.deriveAddress(seed, chain as NetworkType, this.config.network);\n if (response.success && response.address) {\n return {\n chain,\n address: response.address,\n path: response.path || path,\n };\n }\n } catch (error) {\n console.warn(`API address derivation failed for ${chain}:`, error);\n\n // For Ethereum only, fall back to local derivation\n if (chain === 'ethereum') {\n return this.deriveBrowserAddress(seed, chain);\n }\n }\n\n // Try native WDK (Node.js only)\n if (this.useNativeWdk && this.nativeWdkService) {\n try {\n const wdk = this.nativeWdkService as {\n initialize: (seed: string) => Promise<void>;\n deriveAddress: (chain: SupportedChain) => Promise<ChainAddress>;\n };\n await wdk.initialize(seed);\n return await wdk.deriveAddress(chain);\n } catch (error) {\n console.warn(`Native WDK address derivation failed for ${chain}:`, error);\n }\n }\n\n // For Ethereum, we can use browser derivation as final fallback\n if (chain === 'ethereum') {\n return this.deriveBrowserAddress(seed, chain);\n }\n\n // For other chains, throw error - no placeholder addresses\n throw new Error(\n `WDK API required for ${chain} address derivation. Ensure the backend is running.`\n );\n }\n\n /**\n * Derive addresses for all supported chains using WDK API\n *\n * Uses the backend WDK API for real cryptographically valid addresses.\n * No placeholder fallback - WDK API is required for multi-chain addresses.\n */\n async deriveAllAddresses(seed: string): Promise<MultiChainAddresses> {\n await this.initialize();\n\n // Try API first (uses real WDK on backend)\n try {\n const response = await this.apiClient.deriveAllAddresses(seed, this.config.network);\n if (response.success && response.addresses) {\n // Extract address strings from response - API may return objects or strings\n const extractAddress = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'string') return value;\n if (typeof value === 'object' && value !== null && 'address' in value) {\n return (value as { address: string }).address;\n }\n return null;\n };\n\n return {\n ethereum: extractAddress(response.addresses.ethereum),\n bitcoin: extractAddress(response.addresses.bitcoin),\n ton: extractAddress(response.addresses.ton),\n tron: extractAddress(response.addresses.tron),\n solana: extractAddress(response.addresses.solana),\n spark: extractAddress(response.addresses.spark),\n };\n }\n } catch (error) {\n console.warn('API address derivation failed:', error);\n }\n\n // Try native WDK (Node.js only)\n if (this.useNativeWdk && this.nativeWdkService) {\n try {\n const wdk = this.nativeWdkService as {\n initialize: (seed: string) => Promise<void>;\n deriveAllAddresses: () => Promise<MultiChainAddresses>;\n };\n await wdk.initialize(seed);\n return await wdk.deriveAllAddresses();\n } catch (error) {\n console.warn('Native WDK multi-chain derivation failed:', error);\n }\n }\n\n // No fallback - Tether WDK is required for multi-chain address derivation\n throw new Error(\n 'Tether WDK API required for multi-chain address derivation. Service temporarily unavailable.'\n );\n }\n\n /**\n * Get balances for all chains\n */\n async getAllBalances(seed: string): Promise<Record<string, ChainBalance | null>> {\n await this.initialize();\n\n // This always uses API as it requires blockchain RPC calls\n try {\n const response = await fetch(`${this.config.apiUrl}/api/wallets/wdk/balances`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ seed, network: this.config.network }),\n });\n\n if (response.ok) {\n const data = await response.json();\n if (data.success) {\n return data.balances;\n }\n }\n } catch (error) {\n console.warn('Failed to fetch balances:', error);\n }\n\n return {};\n }\n\n /**\n * Get fee rates for a chain\n */\n async getFeeRates(seed: string, chain: SupportedChain): Promise<FeeRates> {\n await this.initialize();\n\n try {\n const response = await fetch(`${this.config.apiUrl}/api/wallets/wdk/fee-rates`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ seed, chain, network: this.config.network }),\n });\n\n if (response.ok) {\n const data = await response.json();\n if (data.success && data.feeRates) {\n return data.feeRates;\n }\n }\n } catch (error) {\n console.warn(`Failed to fetch fee rates for ${chain}:`, error);\n }\n\n return { slow: '0', normal: '0', fast: '0' };\n }\n\n /**\n * Estimate transaction fee\n */\n async estimateFee(\n seed: string,\n chain: SupportedChain,\n to: string,\n amount: string\n ): Promise<{ fee: string; symbol: string }> {\n await this.initialize();\n\n try {\n const response = await fetch(`${this.config.apiUrl}/api/wallets/wdk/estimate-fee`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ seed, chain, to, amount, network: this.config.network }),\n });\n\n if (response.ok) {\n const data = await response.json();\n if (data.success) {\n return { fee: data.fee, symbol: data.symbol };\n }\n }\n } catch (error) {\n console.warn(`Failed to estimate fee for ${chain}:`, error);\n }\n\n return { fee: '0', symbol: this.getChainSymbol(chain) };\n }\n\n /**\n * Send a transaction\n */\n async sendTransaction(\n seed: string,\n chain: SupportedChain,\n to: string,\n amount: string\n ): Promise<TransactionResult> {\n await this.initialize();\n\n try {\n const response = await fetch(`${this.config.apiUrl}/api/wallets/wdk/send`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ seed, chain, to, amount, network: this.config.network }),\n });\n\n if (response.ok) {\n const data = await response.json();\n\n // Extract transaction hash from various possible properties\n let txHash = data.txHash || data.transactionHash || data.hash;\n\n // Handle case where txHash might be an object\n if (txHash && typeof txHash === 'object' && 'hash' in txHash) {\n txHash = txHash.hash;\n }\n\n // Validate Ethereum tx hash format (should be 66 chars: 0x + 64 hex)\n if (chain === 'ethereum' && txHash && (typeof txHash !== 'string' || !txHash.startsWith('0x') || txHash.length !== 66)) {\n console.warn(`Invalid Ethereum tx hash format: ${txHash} (length: ${txHash?.length}, expected: 66)`);\n }\n\n return {\n success: data.success,\n txHash,\n from: data.from,\n to: data.to,\n amount: data.amount,\n chain: data.chain,\n network: data.network,\n };\n }\n\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n error: errorData.error || `HTTP ${response.status}`,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Transaction failed',\n };\n }\n }\n\n /**\n * Get the network configuration\n */\n getNetwork(): 'mainnet' | 'testnet' {\n return this.config.network;\n }\n\n /**\n * Get API URL\n */\n getApiUrl(): string {\n return this.config.apiUrl;\n }\n\n // ==========================================\n // Private Helper Methods\n // ==========================================\n\n private getDerivationPath(chain: SupportedChain): string {\n const paths: Record<SupportedChain, string> = {\n bitcoin: this.config.network === 'testnet' ? \"m/84'/1'/0'/0/0\" : \"m/84'/0'/0'/0/0\",\n ethereum: \"m/44'/60'/0'/0/0\",\n ton: \"m/44'/607'/0'/0'/0'\",\n tron: \"m/44'/195'/0'/0/0\",\n solana: \"m/44'/501'/0'/0'\",\n spark: \"m/44'/998'/0'/0/0\",\n };\n return paths[chain];\n }\n\n private getChainSymbol(chain: SupportedChain): string {\n const symbols: Record<SupportedChain, string> = {\n ethereum: 'ETH',\n bitcoin: 'BTC',\n ton: 'TON',\n tron: 'TRX',\n solana: 'SOL',\n spark: 'SAT',\n };\n return symbols[chain];\n }\n\n /**\n * Derive address using browser-compatible libraries\n */\n private async deriveBrowserAddress(seed: string, chain: SupportedChain): Promise<ChainAddress> {\n const path = this.getDerivationPath(chain);\n\n try {\n let address: string;\n\n switch (chain) {\n case 'ethereum':\n address = BrowserDerivation.deriveEthereumAddress(seed);\n break;\n case 'bitcoin':\n address = BrowserDerivation.deriveBitcoinAddress(seed, this.config.network);\n break;\n case 'tron':\n address = BrowserDerivation.deriveTronAddress(seed);\n break;\n case 'spark':\n address = BrowserDerivation.deriveSparkAddress(seed, this.config.network);\n break;\n case 'solana':\n address = await BrowserDerivation.deriveSolanaAddress(seed);\n break;\n case 'ton':\n address = await BrowserDerivation.deriveTonAddress(seed);\n break;\n default:\n throw new Error(`Unsupported chain: ${chain}`);\n }\n\n return { chain, address, path };\n } catch (error) {\n console.error(`Browser derivation failed for ${chain}:`, error);\n throw error;\n }\n }\n\n /**\n * Derive all addresses using browser-compatible libraries\n */\n private async deriveAllBrowserAddresses(seed: string): Promise<MultiChainAddresses> {\n return BrowserDerivation.deriveAllAddresses(seed, this.config.network);\n }\n}\n\n// ==========================================\n// Factory Functions\n// ==========================================\n\nlet defaultService: ZubariWdkService | null = null;\n\n/**\n * Get or create the default ZubariWdkService instance\n */\nexport function getZubariWdkService(config?: Partial<ZubariWdkServiceConfig>): ZubariWdkService {\n if (!defaultService || (config && config.network !== defaultService.getNetwork())) {\n defaultService = new ZubariWdkService(config);\n }\n return defaultService;\n}\n\n/**\n * Create a new ZubariWdkService instance\n */\nexport function createZubariWdkService(config?: Partial<ZubariWdkServiceConfig>): ZubariWdkService {\n return new ZubariWdkService(config);\n}\n\n/**\n * Check if the current environment is a browser\n */\nexport { isBrowser };\n","/**\n * Transaction Service for Zubari SDK\n *\n * Provides multi-chain transaction capabilities using Tether WDK.\n * Supports Ethereum, Bitcoin, Solana, TON, TRON, and Spark (Lightning).\n *\n * @see https://docs.wallet.tether.io/\n */\n\nimport type { NetworkType, TxResult } from '../types';\n\n// Dynamic imports for ESM modules (WDK packages are ESM-only)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WdkManager: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerBtc: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerEvm: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerSolana: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerTon: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerTron: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet WalletManagerSpark: any;\n\nlet wdkLoaded = false;\nlet wdkLoadError: Error | null = null;\n\n/**\n * CoinGecko IDs for each supported chain\n */\nconst COINGECKO_IDS: Record<NetworkType, string> = {\n ethereum: 'ethereum',\n bitcoin: 'bitcoin',\n ton: 'the-open-network',\n tron: 'tron',\n solana: 'solana',\n spark: 'bitcoin', // Spark uses BTC\n};\n\n/**\n * Price cache to avoid excessive API calls\n */\ninterface PriceCache {\n prices: Record<string, number>;\n timestamp: number;\n}\n\nlet priceCache: PriceCache | null = null;\nconst PRICE_CACHE_TTL = 60000; // 1 minute cache\n\n/**\n * Fetch USD prices for all supported chains from CoinGecko\n */\nasync function fetchPrices(): Promise<Record<string, number>> {\n // Check cache\n if (priceCache && Date.now() - priceCache.timestamp < PRICE_CACHE_TTL) {\n return priceCache.prices;\n }\n\n const ids = Object.values(COINGECKO_IDS).filter((v, i, a) => a.indexOf(v) === i).join(',');\n\n try {\n const response = await fetch(\n `https://api.coingecko.com/api/v3/simple/price?ids=${ids}&vs_currencies=usd`,\n {\n headers: { 'Accept': 'application/json' },\n }\n );\n\n if (response.ok) {\n const data = await response.json();\n const prices: Record<string, number> = {};\n\n for (const [chain, geckoId] of Object.entries(COINGECKO_IDS)) {\n prices[chain] = data[geckoId]?.usd || 0;\n }\n\n // Update cache\n priceCache = { prices, timestamp: Date.now() };\n return prices;\n }\n } catch (error) {\n console.warn('Failed to fetch prices from CoinGecko:', error);\n }\n\n // Return cached prices if available, otherwise empty\n return priceCache?.prices || {};\n}\n\n/**\n * Get USD price for a specific chain\n */\nasync function getPriceForChain(chain: NetworkType): Promise<number> {\n const prices = await fetchPrices();\n return prices[chain] || 0;\n}\n\n/**\n * Dynamic import helper that bypasses TypeScript's CommonJS transformation\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst dynamicImport = new Function('specifier', 'return import(specifier)') as (\n specifier: string\n) => Promise<any>;\n\n/**\n * Dynamically load WDK modules (they are ESM-only)\n */\nasync function loadWdkModules(): Promise<void> {\n if (wdkLoaded) return;\n if (wdkLoadError) throw wdkLoadError;\n\n try {\n const [wdk, btc, evm, solana, ton, tron, spark] = await Promise.all([\n dynamicImport('@tetherto/wdk'),\n dynamicImport('@tetherto/wdk-wallet-btc'),\n dynamicImport('@tetherto/wdk-wallet-evm'),\n dynamicImport('@tetherto/wdk-wallet-solana'),\n dynamicImport('@tetherto/wdk-wallet-ton'),\n dynamicImport('@tetherto/wdk-wallet-tron'),\n dynamicImport('@tetherto/wdk-wallet-spark'),\n ]);\n\n WdkManager = wdk.default;\n WalletManagerBtc = btc.default;\n WalletManagerEvm = evm.default;\n WalletManagerSolana = solana.default;\n WalletManagerTon = ton.default;\n WalletManagerTron = tron.default;\n WalletManagerSpark = spark.default;\n wdkLoaded = true;\n } catch (error) {\n wdkLoadError = error instanceof Error ? error : new Error('Failed to load WDK modules');\n console.error('Failed to load WDK modules:', error);\n throw wdkLoadError;\n }\n}\n\n/**\n * Transaction parameters for sending\n */\nexport interface TransactionParams {\n /** Recipient address */\n to: string;\n /** Amount to send (in human-readable format, e.g., \"0.1\") */\n amount: string;\n /** Token address (optional, for ERC-20/SPL tokens) */\n token?: string;\n /** Transaction memo/message (for chains that support it) */\n memo?: string;\n /** Fee priority: 'slow' | 'medium' | 'fast' */\n feePriority?: 'slow' | 'medium' | 'fast';\n /** Custom gas limit (EVM chains) */\n gasLimit?: string;\n /** Custom gas price (EVM chains) */\n gasPrice?: string;\n}\n\n/**\n * Transaction result with detailed information\n */\nexport interface TransactionResult {\n /** Transaction hash */\n hash: string;\n /** Network/chain */\n network: NetworkType;\n /** Transaction status */\n status: 'pending' | 'confirmed' | 'failed';\n /** Block number (when confirmed) */\n blockNumber?: number;\n /** Gas used (EVM chains) */\n gasUsed?: string;\n /** Fee paid */\n fee?: string;\n /** Explorer URL */\n explorerUrl?: string;\n /** Error message if failed */\n error?: string;\n /** Timestamp */\n timestamp: number;\n}\n\n/**\n * Transaction history item\n */\nexport interface TransactionHistoryItem {\n hash: string;\n network: NetworkType;\n type: 'send' | 'receive' | 'swap' | 'contract';\n from: string;\n to: string;\n amount: string;\n token?: string;\n fee?: string;\n status: 'pending' | 'confirmed' | 'failed';\n timestamp: number;\n blockNumber?: number;\n}\n\n/**\n * Fee estimate for a transaction\n */\nexport interface FeeEstimate {\n slow: {\n fee: string;\n estimatedTime: string; // e.g., \"~30 min\"\n };\n medium: {\n fee: string;\n estimatedTime: string; // e.g., \"~5 min\"\n };\n fast: {\n fee: string;\n estimatedTime: string; // e.g., \"~1 min\"\n };\n}\n\n/**\n * Transaction Service configuration\n */\nexport interface TransactionServiceConfig {\n network: 'mainnet' | 'testnet';\n rpcUrls?: Partial<Record<NetworkType, string>>;\n}\n\n// Default RPC URLs\nconst DEFAULT_RPC_URLS = {\n mainnet: {\n ethereum: 'https://eth.llamarpc.com',\n bitcoin: '', // Uses Electrum\n solana: 'https://api.mainnet-beta.solana.com',\n ton: 'https://toncenter.com/api/v2/jsonRPC',\n tron: 'https://api.trongrid.io',\n spark: '', // Uses Spark network\n },\n testnet: {\n ethereum: 'https://ethereum-sepolia-rpc.publicnode.com',\n bitcoin: '', // Uses Electrum testnet\n solana: 'https://api.devnet.solana.com',\n ton: 'https://testnet.toncenter.com/api/v2/jsonRPC',\n tron: 'https://api.shasta.trongrid.io',\n spark: '', // Uses Spark testnet\n },\n};\n\n// Explorer URLs\nconst EXPLORER_URLS = {\n mainnet: {\n ethereum: 'https://etherscan.io/tx/',\n bitcoin: 'https://mempool.space/tx/',\n solana: 'https://solscan.io/tx/',\n ton: 'https://tonscan.org/tx/',\n tron: 'https://tronscan.org/#/transaction/',\n spark: 'https://spark.info/tx/',\n },\n testnet: {\n ethereum: 'https://sepolia.etherscan.io/tx/',\n bitcoin: 'https://mempool.space/testnet/tx/',\n solana: 'https://solscan.io/tx/?cluster=devnet&tx=',\n ton: 'https://testnet.tonscan.org/tx/',\n tron: 'https://shasta.tronscan.org/#/transaction/',\n spark: 'https://testnet.spark.info/tx/',\n },\n};\n\n/**\n * Transaction Service\n *\n * Provides multi-chain transaction capabilities:\n * - Send native tokens (ETH, BTC, SOL, TON, TRX)\n * - Send ERC-20/SPL tokens\n * - Fee estimation\n * - Transaction history\n */\nexport class TransactionService {\n private seed: string | null = null;\n private config: TransactionServiceConfig;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private wallets: Partial<Record<NetworkType, any>> = {};\n\n constructor(config: Partial<TransactionServiceConfig> = {}) {\n this.config = {\n network: config.network || 'testnet',\n rpcUrls: config.rpcUrls,\n };\n }\n\n /**\n * Ensure WDK modules are loaded\n */\n private async ensureLoaded(): Promise<void> {\n await loadWdkModules();\n }\n\n /**\n * Get RPC URL for a chain\n */\n private getRpcUrl(chain: NetworkType): string {\n const networkUrls = DEFAULT_RPC_URLS[this.config.network];\n\n if (this.config.rpcUrls?.[chain]) {\n return this.config.rpcUrls[chain]!;\n }\n\n return networkUrls[chain as keyof typeof networkUrls] || '';\n }\n\n /**\n * Get explorer URL for a transaction\n */\n getExplorerUrl(chain: NetworkType, txHash: string): string {\n const explorers = EXPLORER_URLS[this.config.network];\n const baseUrl = explorers[chain as keyof typeof explorers] || '';\n return `${baseUrl}${txHash}`;\n }\n\n /**\n * Initialize the service with a seed phrase\n */\n async initialize(seed: string): Promise<void> {\n await this.ensureLoaded();\n\n if (!WdkManager.isValidSeed(seed)) {\n throw new Error('Invalid seed phrase');\n }\n\n this.seed = seed;\n this.wallets = {};\n }\n\n /**\n * Check if service is initialized\n */\n isInitialized(): boolean {\n return this.seed !== null;\n }\n\n /**\n * Get or create wallet instance for a specific chain\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private async getWallet(chain: NetworkType): Promise<any> {\n if (!this.seed) {\n throw new Error('TransactionService not initialized. Call initialize() first.');\n }\n\n // Return cached wallet if exists\n if (this.wallets[chain]) {\n return this.wallets[chain];\n }\n\n const isTestnet = this.config.network === 'testnet';\n\n try {\n switch (chain) {\n case 'ethereum': {\n const rpcUrl = this.getRpcUrl('ethereum');\n const wallet = new WalletManagerEvm(this.seed, { provider: rpcUrl });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n case 'bitcoin': {\n const wallet = new WalletManagerBtc(this.seed, {\n network: isTestnet ? 'testnet' : 'bitcoin',\n });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n case 'solana': {\n const rpcUrl = this.getRpcUrl('solana');\n const wallet = new WalletManagerSolana(this.seed, {\n rpcUrl,\n });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n case 'ton': {\n const url = this.getRpcUrl('ton');\n const wallet = new WalletManagerTon(this.seed, {\n tonClient: { url },\n });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n case 'tron': {\n const fullHost = this.getRpcUrl('tron');\n const wallet = new WalletManagerTron(this.seed, {\n provider: fullHost,\n });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n case 'spark': {\n const wallet = new WalletManagerSpark(this.seed, {\n network: isTestnet ? 'TESTNET' : 'MAINNET',\n });\n this.wallets[chain] = wallet;\n return wallet;\n }\n\n default:\n throw new Error(`Unsupported chain: ${chain}`);\n }\n } catch (error) {\n console.error(`Failed to initialize ${chain} wallet:`, error);\n throw error;\n }\n }\n\n /**\n * Estimate transaction fee\n */\n async estimateFee(chain: NetworkType, params: TransactionParams): Promise<FeeEstimate> {\n const wallet = await this.getWallet(chain);\n\n try {\n // Get fee rates from the wallet\n const feeRates = await wallet.getFeeRates();\n\n // Format based on chain type\n if (chain === 'ethereum') {\n return {\n slow: {\n fee: `${feeRates.slow || '0'} Gwei`,\n estimatedTime: '~10 min',\n },\n medium: {\n fee: `${feeRates.medium || feeRates.standard || '0'} Gwei`,\n estimatedTime: '~3 min',\n },\n fast: {\n fee: `${feeRates.fast || feeRates.high || '0'} Gwei`,\n estimatedTime: '~30 sec',\n },\n };\n } else if (chain === 'bitcoin') {\n return {\n slow: {\n fee: `${feeRates.slow || feeRates.low || '0'} sat/vB`,\n estimatedTime: '~60 min',\n },\n medium: {\n fee: `${feeRates.medium || feeRates.normal || '0'} sat/vB`,\n estimatedTime: '~30 min',\n },\n fast: {\n fee: `${feeRates.fast || feeRates.high || '0'} sat/vB`,\n estimatedTime: '~10 min',\n },\n };\n } else {\n // Generic format for other chains\n return {\n slow: {\n fee: String(feeRates.slow || feeRates.low || '0'),\n estimatedTime: '~10 min',\n },\n medium: {\n fee: String(feeRates.medium || feeRates.standard || '0'),\n estimatedTime: '~3 min',\n },\n fast: {\n fee: String(feeRates.fast || feeRates.high || '0'),\n estimatedTime: '~1 min',\n },\n };\n }\n } catch (error) {\n console.error(`Error estimating fee for ${chain}:`, error);\n // Return default fees on error\n return {\n slow: { fee: '0', estimatedTime: 'Unknown' },\n medium: { fee: '0', estimatedTime: 'Unknown' },\n fast: { fee: '0', estimatedTime: 'Unknown' },\n };\n }\n }\n\n /**\n * Send a transaction\n */\n async send(chain: NetworkType, params: TransactionParams): Promise<TransactionResult> {\n const wallet = await this.getWallet(chain);\n const account = await wallet.getAccount(0);\n\n const timestamp = Date.now();\n\n try {\n // Build and send transaction based on chain\n let txHash: string;\n\n if (params.token) {\n // Token transfer (ERC-20, SPL, TRC-20, etc.)\n txHash = await account.sendToken(params.to, params.amount, params.token, {\n memo: params.memo,\n feePriority: params.feePriority || 'medium',\n });\n } else {\n // Native token transfer\n txHash = await account.send(params.to, params.amount, {\n memo: params.memo,\n feePriority: params.feePriority || 'medium',\n gasLimit: params.gasLimit,\n gasPrice: params.gasPrice,\n });\n }\n\n return {\n hash: txHash,\n network: chain,\n status: 'pending',\n explorerUrl: this.getExplorerUrl(chain, txHash),\n timestamp,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Transaction failed';\n console.error(`Transaction failed on ${chain}:`, error);\n\n return {\n hash: '',\n network: chain,\n status: 'failed',\n error: errorMessage,\n timestamp,\n };\n }\n }\n\n /**\n * Get transaction status\n */\n async getTransactionStatus(chain: NetworkType, txHash: string): Promise<TransactionResult> {\n const wallet = await this.getWallet(chain);\n\n try {\n const tx = await wallet.getTransaction(txHash);\n\n return {\n hash: txHash,\n network: chain,\n status: tx.confirmed ? 'confirmed' : 'pending',\n blockNumber: tx.blockNumber,\n gasUsed: tx.gasUsed?.toString(),\n fee: tx.fee?.toString(),\n explorerUrl: this.getExplorerUrl(chain, txHash),\n timestamp: tx.timestamp || Date.now(),\n };\n } catch (error) {\n console.error(`Error getting transaction status for ${txHash}:`, error);\n return {\n hash: txHash,\n network: chain,\n status: 'pending',\n explorerUrl: this.getExplorerUrl(chain, txHash),\n timestamp: Date.now(),\n };\n }\n }\n\n /**\n * Get transaction history for an address\n */\n async getTransactionHistory(\n chain: NetworkType,\n limit: number = 10\n ): Promise<TransactionHistoryItem[]> {\n const wallet = await this.getWallet(chain);\n const account = await wallet.getAccount(0);\n\n try {\n const history = await account.getTransactions({ limit });\n\n return history.map((tx: any) => ({\n hash: tx.hash || tx.txHash,\n network: chain,\n type: tx.type || (tx.from === account.address ? 'send' : 'receive'),\n from: tx.from,\n to: tx.to,\n amount: tx.amount || tx.value,\n token: tx.token,\n fee: tx.fee?.toString(),\n status: tx.confirmed ? 'confirmed' : 'pending',\n timestamp: tx.timestamp || Date.now(),\n blockNumber: tx.blockNumber,\n }));\n } catch (error) {\n console.error(`Error getting transaction history for ${chain}:`, error);\n return [];\n }\n }\n\n /**\n * Get balance for a specific chain\n */\n async getBalance(chain: NetworkType): Promise<{ balance: string; balanceUsd: number }> {\n const wallet = await this.getWallet(chain);\n const account = await wallet.getAccount(0);\n\n try {\n const balance = await account.getBalance();\n const balanceStr = balance.toString();\n\n // Fetch USD price for this chain\n const priceUsd = await getPriceForChain(chain);\n const balanceNum = parseFloat(balanceStr) || 0;\n const balanceUsd = balanceNum * priceUsd;\n\n return {\n balance: balanceStr,\n balanceUsd,\n };\n } catch (error) {\n console.error(`Error getting balance for ${chain}:`, error);\n return { balance: '0', balanceUsd: 0 };\n }\n }\n\n /**\n * Get the current network configuration\n */\n getNetwork(): 'mainnet' | 'testnet' {\n return this.config.network;\n }\n\n /**\n * Clean up and dispose of wallet instances\n */\n dispose(): void {\n for (const wallet of Object.values(this.wallets)) {\n if (wallet && typeof wallet.dispose === 'function') {\n try {\n wallet.dispose();\n } catch {\n // Ignore dispose errors\n }\n }\n }\n this.wallets = {};\n this.seed = null;\n }\n}\n\n// Singleton instance\nlet transactionServiceInstance: TransactionService | null = null;\n\n/**\n * Get or create the Transaction service singleton\n */\nexport function getTransactionService(config?: Partial<TransactionServiceConfig>): TransactionService {\n if (!transactionServiceInstance || (config && config.network !== transactionServiceInstance.getNetwork())) {\n transactionServiceInstance = new TransactionService(config);\n }\n return transactionServiceInstance;\n}\n\n/**\n * Create a new Transaction service instance (non-singleton)\n */\nexport function createTransactionService(config?: Partial<TransactionServiceConfig>): TransactionService {\n return new TransactionService(config);\n}\n"]}