{"version":3,"sources":["../src/utils/eip3009.ts","../src/index.ts","../src/utils/chains-constants.ts","../src/utils/stealth-address.ts","../src/utils/constants.ts","../src/utils/transaction-utils.ts","../src/utils/payment-utils.ts","../src/utils/safe-utils.ts","../src/utils/create-account.ts","../src/utils/modules-api.ts","../src/utils/module-generator.ts","../src/utils/payment-status.ts","../src/utils/registration-prep.ts","../src/get-required-data.ts","../src/utils/create-orchestration-data.ts","../src/utils/deposit.ts","../src/utils/orchestration-utils.ts","../src/utils/orchestration-workflow.ts","../src/utils/encode-module-data.ts","../src/utils/module-builder-api.ts"],"sourcesContent":["import { type WalletClient, type Address, type Hex, type PublicClient } from 'viem';\n\n/**\n * EIP-3009 Transfer Authorization Types\n */\nexport interface TransferAuthorizationMessage {\n  from: Address;\n  to: Address;\n  value: bigint;\n  validAfter: bigint;\n  validBefore: bigint;\n  nonce: Hex;\n}\n\nexport interface TransferAuthorizationSignature {\n  v: number;\n  r: Hex;\n  s: Hex;\n}\n\nexport interface SignedTransferAuthorization extends TransferAuthorizationMessage {\n  v: number;\n  r: Hex;\n  s: Hex;\n}\n\n/**\n * EIP-712 Domain for EIP-3009\n */\nexport interface EIP3009Domain {\n  name: string;\n  version: string;\n  chainId: number;\n  verifyingContract: Address;\n}\n\n/**\n * EIP-3009 Type Hash\n */\nexport const TRANSFER_WITH_AUTHORIZATION_TYPES = {\n  TransferWithAuthorization: [\n    { name: 'from', type: 'address' },\n    { name: 'to', type: 'address' },\n    { name: 'value', type: 'uint256' },\n    { name: 'validAfter', type: 'uint256' },\n    { name: 'validBefore', type: 'uint256' },\n    { name: 'nonce', type: 'bytes32' },\n  ],\n} as const;\n\n/**\n * ERC20 ABI for token name\n */\nconst ERC20_NAME_ABI = [\n  {\n    inputs: [],\n    name: 'name',\n    outputs: [{ name: '', type: 'string' }],\n    stateMutability: 'view',\n    type: 'function',\n  },\n] as const;\n\n/**\n * Generate a random nonce for EIP-3009 authorization\n */\nexport const generateNonce = (): Hex => {\n  const randomBytes = new Uint8Array(32);\n  crypto.getRandomValues(randomBytes);\n  return `0x${Array.from(randomBytes)\n    .map((b) => b.toString(16).padStart(2, '0'))\n    .join('')}` as Hex;\n};\n\n/**\n * Get EIP-712 domain for a token\n */\nexport const getEIP3009Domain = async (\n  tokenAddress: Address,\n  chainId: number,\n  publicClient: PublicClient,\n  version: string = '2',\n): Promise<EIP3009Domain> => {\n  // Get token name from contract\n  const tokenName = await publicClient.readContract({\n    address: tokenAddress,\n    abi: ERC20_NAME_ABI,\n    functionName: 'name',\n  });\n\n  return {\n    name: tokenName as string,\n    version,\n    chainId,\n    verifyingContract: tokenAddress,\n  };\n};\n\n/**\n * Sign an EIP-3009 transferWithAuthorization message\n */\nexport const signTransferAuthorization = async (\n  message: TransferAuthorizationMessage,\n  domain: EIP3009Domain,\n  walletClient: WalletClient,\n): Promise<SignedTransferAuthorization> => {\n  if (!walletClient.account) {\n    throw new Error('Wallet client must have an account');\n  }\n\n  // Sign the typed data\n  const signature = await walletClient.signTypedData({\n    account: walletClient.account,\n    domain,\n    types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n    primaryType: 'TransferWithAuthorization',\n    message: {\n      from: message.from,\n      to: message.to,\n      value: message.value,\n      validAfter: message.validAfter,\n      validBefore: message.validBefore,\n      nonce: message.nonce,\n    },\n  });\n\n  // Split signature into v, r, s\n  const r = signature.slice(0, 66) as Hex;\n  const s = `0x${signature.slice(66, 130)}` as Hex;\n  const v = parseInt(signature.slice(130, 132), 16);\n\n  return {\n    ...message,\n    v,\n    r,\n    s,\n  };\n};\n\n/**\n * Create a transfer authorization message with default validity window\n *\n * @param from - Address that owns the tokens\n * @param to - Address to transfer tokens to\n * @param value - Amount of tokens to transfer\n * @param validityWindow - Validity window in seconds (default: 1 hour)\n */\nexport const createTransferAuthorizationMessage = (\n  from: Address,\n  to: Address,\n  value: bigint,\n  validityWindow: number = 3600, // 1 hour default\n): TransferAuthorizationMessage => {\n  const now = Math.floor(Date.now() / 1000);\n\n  return {\n    from,\n    to,\n    value,\n    validAfter: 0n, // Valid immediately\n    validBefore: BigInt(now + validityWindow),\n    nonce: generateNonce(),\n  };\n};\n\n/**\n * Complete helper function to sign a transfer authorization\n *\n * @param from - Address that owns the tokens\n * @param to - Address to transfer tokens to\n * @param value - Amount of tokens to transfer\n * @param tokenAddress - Token contract address\n * @param chainId - Chain ID\n * @param walletClient - Wallet client to sign with\n * @param publicClient - Public client to read token info\n * @param validityWindow - Validity window in seconds (default: 1 hour)\n */\nexport const signTransferWithAuthorization = async (\n  from: Address,\n  to: Address,\n  value: bigint,\n  tokenAddress: Address,\n  chainId: number,\n  walletClient: WalletClient,\n  publicClient: PublicClient,\n  validityWindow: number = 3600,\n): Promise<SignedTransferAuthorization> => {\n  // Create message\n  const message = createTransferAuthorizationMessage(from, to, value, validityWindow);\n\n  // Get domain\n  const domain = await getEIP3009Domain(tokenAddress, chainId, publicClient);\n\n  // Sign\n  return signTransferAuthorization(message, domain, walletClient);\n};\n","import { CHAIN_MAPPING } from './utils/chains-constants';\nimport { type SupportedChain } from './types/supported-chains';\nimport {\n  type ModuleName,\n  type RequiredStateData,\n  type ConfigField,\n  type GetRequiredStateInput,\n  AVAILABLE_MODULES,\n  type ValidModuleName,\n} from './types/module-types';\nimport { getStealthAddress } from './utils/stealth-address';\nimport { getTransactions as fetchTransactions } from './utils/transaction-utils';\nimport { type TransactionResult } from './types/withdrawal-data';\nimport { PublicClient, WalletClient } from 'viem';\nimport { singlePayment, transferWithAuthorization } from './utils/payment-utils';\nimport {\n  signAccountConfig,\n  getApiKey,\n  getRecipientAccountData,\n  checkBalanceGreaterThan,\n  getBalance,\n} from './utils/create-account';\nimport { getModules } from './utils/modules-api';\nimport {\n  generateModulesForRegistration,\n  getAvailableModules,\n  validateModuleInputs,\n  type ModuleUserInput,\n  type ModuleGenerationResult,\n} from './utils/module-generator';\nimport {\n  type SinglePaymentResult,\n  type TransferWithAuthorizationResult,\n  type TransferWithAuthorizationData,\n} from './types/payments';\nimport { type StealthAddressResponse } from './types/stealth-address';\nimport {\n  type Module,\n  type Texts,\n  type EnsData,\n  type CommonData,\n  type RegisterRequest,\n  type AccountConfig,\n  type SignedAccountConfig,\n  type ModuleInfo,\n  type ModuleDeployment,\n  type ModulesResponse,\n  type RequiredField,\n  type TokenInfo,\n  type NetworkTokens,\n  type UserInputs,\n  type ModuleFormat,\n  type ExampleRequest,\n  type InstallationGuide,\n  type RegistrationModule,\n} from './types/account-types';\nimport {\n  checkPaymentStatus as checkPaymentStatusUtil,\n  pollPaymentStatus as pollPaymentStatusUtil,\n  type PaymentStatus,\n  type PaymentStatusData,\n  type PollingOptions,\n} from './utils/payment-status';\nimport {\n  generatePrivacyKeys,\n  buildEnsData,\n  buildRegistrationData,\n  signRegistrationData,\n  prepareRegisterRequest,\n  prettyPrintRegisterRequest,\n} from './utils/registration-prep';\nimport { getRequiredState } from './get-required-data';\nimport { getRequiredAvailableModules } from './utils/constants';\nimport { createOrchestrationData } from './utils/create-orchestration-data';\nimport {\n  deposit,\n  depositFromOrchestrationData,\n  depositGasless,\n  depositGaslessFromOrchestrationData,\n} from './utils/deposit';\nimport {\n  notifyDeposit,\n  notifyDepositGasless,\n  getOrchestrationStatus,\n  pollOrchestrationStatus,\n  TransferType,\n} from './utils/orchestration-utils';\nimport {\n  signTransferWithAuthorization,\n  createTransferAuthorizationMessage,\n  generateNonce,\n  getEIP3009Domain,\n} from './utils/eip3009';\nimport {\n  transferToOrchestrationAccount,\n} from './utils/orchestration-workflow';\nimport {\n  encodeAutoEarnModuleData,\n  createAutoEarnConfig,\n  type AutoEarnConfig,\n} from './utils/encode-module-data';\nimport {\n  buildAutoEarnModule,\n  buildAutoSwapModule,\n  buildAutoBridgeModule,\n  buildModulesBatch,\n  validateModule,\n  type AutoEarnParams,\n  type AutoSwapParams,\n  type AutoBridgeParams,\n  type BuiltModule,\n  type ModuleBuilderConfig,\n} from './utils/module-builder-api';\nimport type { OrchestrationData, CurrentState, RequiredState } from './types/orchestration-data';\nimport type { DepositResult, GaslessDepositResult } from './utils/deposit';\nimport type {\n  NotifyDepositParams,\n  NotifyDepositResponse,\n  OrchestrationStatus,\n  PollOrchestrationStatusOptions,\n  SignedTransferAuthorizationData,\n} from './utils/orchestration-utils';\nimport type {\n  TransferAuthorizationMessage,\n  TransferAuthorizationSignature,\n  SignedTransferAuthorization,\n  EIP3009Domain,\n} from './utils/eip3009';\n\nexport const createStealthAddress = async ({\n  username,\n  chainId,\n  tokenAddress,\n}: {\n  username: string;\n  chainId: SupportedChain;\n  tokenAddress?: string;\n}): Promise<StealthAddressResponse> => {\n  const chain = CHAIN_MAPPING[chainId];\n  if (!chain) {\n    throw new Error(`Chain ${chainId} not supported yet!`);\n  }\n\n  const address = await getStealthAddress(tokenAddress as string, username, chainId);\n  return address;\n};\n\nexport const getTransactions = async ({\n  username,\n  publicClient,\n}: {\n  username: string;\n  publicClient: PublicClient;\n}): Promise<TransactionResult> => {\n  return await fetchTransactions({ username, publicClient });\n};\n\nexport const processSinglePayment = async ({\n  walletClient,\n  publicClient,\n  chainId,\n  tokenAddress,\n  requestedAmount,\n  recipientAddress,\n}: {\n  walletClient: WalletClient;\n  publicClient: PublicClient;\n  chainId: SupportedChain;\n  tokenAddress: string;\n  requestedAmount: string;\n  recipientAddress: string;\n}): Promise<SinglePaymentResult> => {\n  const result = await singlePayment({\n    walletClient,\n    publicClient,\n    chainId,\n    tokenAddress,\n    requestedAmount,\n    recipientAddress,\n  });\n  return result;\n};\n\nexport const checkPaymentStatus = checkPaymentStatusUtil;\nexport const pollPaymentStatus = pollPaymentStatusUtil;\n\nexport const createTransferWithAuthorization = async ({\n  walletClient,\n  chainId,\n  tokenAddress,\n  recipientAddress,\n  amount,\n  validAfter,\n  validBefore,\n}: {\n  walletClient: WalletClient;\n  chainId: SupportedChain;\n  tokenAddress: string;\n  recipientAddress: string;\n  amount: string;\n  validAfter?: string;\n  validBefore?: string;\n}): Promise<TransferWithAuthorizationResult> => {\n  return await transferWithAuthorization({\n    walletClient,\n    chainId,\n    tokenAddress,\n    recipientAddress,\n    amount,\n    validAfter,\n    validBefore,\n  });\n};\n\nexport { CHAIN_MAPPING };\n\nexport {\n  signAccountConfig,\n  getApiKey,\n  getRecipientAccountData,\n  checkBalanceGreaterThan,\n  getBalance,\n  getModules,\n  generateModulesForRegistration,\n  getAvailableModules,\n  getRequiredAvailableModules,\n  validateModuleInputs,\n  getRequiredState,\n  createOrchestrationData,\n  deposit,\n  depositFromOrchestrationData,\n  depositGasless,\n  depositGaslessFromOrchestrationData,\n  notifyDeposit,\n  notifyDepositGasless,\n  getOrchestrationStatus,\n  pollOrchestrationStatus,\n  transferToOrchestrationAccount,\n  encodeAutoEarnModuleData,\n  createAutoEarnConfig,\n  buildAutoEarnModule,\n  buildAutoSwapModule,\n  buildAutoBridgeModule,\n  buildModulesBatch,\n  validateModule,\n  // EIP-3009 gasless transfer utilities\n  signTransferWithAuthorization,\n  createTransferAuthorizationMessage,\n  generateNonce,\n  getEIP3009Domain,\n  TransferType,\n  // Registration prep (no network)\n  generatePrivacyKeys,\n  buildEnsData,\n  buildRegistrationData,\n  signRegistrationData,\n  prepareRegisterRequest,\n  prettyPrintRegisterRequest,\n};\n\nexport type {\n  PaymentStatus,\n  PaymentStatusData,\n  PollingOptions,\n  StealthAddressResponse,\n  SupportedChain,\n  TransferWithAuthorizationResult,\n  TransferWithAuthorizationData,\n  Module,\n  Texts,\n  EnsData,\n  CommonData,\n  RegisterRequest,\n  AccountConfig,\n  SignedAccountConfig,\n  ModuleInfo,\n  ModuleDeployment,\n  ModulesResponse,\n  RequiredField,\n  TokenInfo,\n  NetworkTokens,\n  UserInputs,\n  ModuleFormat,\n  ExampleRequest,\n  InstallationGuide,\n  RegistrationModule,\n  ModuleUserInput,\n  ModuleGenerationResult,\n  OrchestrationData,\n  CurrentState,\n  RequiredState,\n  DepositResult,\n  GaslessDepositResult,\n  NotifyDepositParams,\n  NotifyDepositResponse,\n  OrchestrationStatus,\n  PollOrchestrationStatusOptions,\n  SignedTransferAuthorizationData,\n  TransferAuthorizationMessage,\n  TransferAuthorizationSignature,\n  SignedTransferAuthorization,\n  EIP3009Domain,\n  AutoEarnConfig,\n  AutoEarnParams,\n  AutoSwapParams,\n  AutoBridgeParams,\n  BuiltModule,\n  ModuleBuilderConfig,\n  // Module types\n  ModuleName,\n  RequiredStateData,\n  ConfigField,\n  GetRequiredStateInput,\n  AVAILABLE_MODULES,\n  ValidModuleName,\n};\n","import { arbitrumSepolia, baseSepolia, Chain } from 'viem/chains';\nimport { type SupportedChain } from '../types/supported-chains';\nimport { createPublicClient, http, PublicClient } from 'viem';\n\nexport const BASE_SEPOLIA = {\n  name: 'Base Sepolia',\n  chainId: baseSepolia.id,\n  network: baseSepolia.name,\n  explorerUrl: 'https://sepolia.basescan.org',\n  logo: '/chains/base-logo.png',\n  rpcUrl: baseSepolia.rpcUrls.default.http[0],\n  // fallbackRpcUrls: RPC_CONFIG.BASE_SEPOLIA.fallbacks,\n  nativeCurrency: {\n    name: 'Ether',\n    symbol: 'ETH',\n    decimals: 18,\n  },\n  blockExplorer: {\n    name: 'Base Sepolia Explorer',\n    url: 'https://sepolia.basescan.org/',\n  },\n  tokens: [\n    {\n      enabled: true,\n      symbol: 'USDC',\n      name: 'USDC',\n      address: '0x036cbd53842c5426634e7929541ec2318f3dcf7e',\n      iconUri: '/tokens/usdc.png',\n    },\n  ],\n  testnet: true,\n};\n\nexport const ARBITRUM_SEPOLIA = {\n  name: 'Arbitrum Sepolia',\n  chainId: arbitrumSepolia.id,\n  network: 'arbitrum-sepolia',\n  explorerUrl: 'https://sepolia.arbiscan.io',\n  logo: '/chains/base-logo.png', // TODO: change to arbitrum logo\n  rpcUrl: arbitrumSepolia.rpcUrls.default.http[0],\n  // fallbackRpcUrls: RPC_CONFIG.ARB_SEPOLIA.fallbacks,\n  nativeCurrency: {\n    name: 'Ether',\n    symbol: 'ETH',\n    decimals: 18,\n  },\n  blockExplorer: {\n    name: 'Arbitrum Sepolia Explorer',\n    url: 'https://sepolia.arbiscan.io/',\n  },\n  tokens: [\n    {\n      enabled: true,\n      symbol: 'USDC',\n      name: 'USDC',\n      address: '0x75faf114eafb1bdbe2f0316df893fd58ce46aa4d',\n      iconUri: '/tokens/usdc.png',\n    },\n  ],\n  testnet: true,\n};\n\nexport const CHAIN_MAPPING = {\n  84532: BASE_SEPOLIA,\n  421614: ARBITRUM_SEPOLIA,\n};\n\nexport const RPC_CONFIG = {\n  // SEI_TESTNET: {\n  //   primary:\n  //     'https://quiet-crimson-ensemble.sei-atlantic.quiknode.pro/69718db72dcf9d1828053e82dbeeeb283319782e/',\n  //   fallbacks: [\n  //     'https://sei-testnet.drpc.org',\n  //     'https://rpc.sei-testnet.seinetwork.io',\n  //     'https://testnet-rpc.sei.io',\n  //   ],\n  // },\n  [baseSepolia.id]: {\n    primary: 'https://sepolia.base.org',\n    fallbacks: [\n      'https://base-sepolia.api.onfinality.io/public',\n      'https://base-sepolia-public.nodies.app',\n    ],\n  },\n  [arbitrumSepolia.id]: {\n    primary: 'https://arbitrum-sepolia.drpc.org',\n    fallbacks: [\n      'https://arbitrum-sepolia.therpc.io',\n      'https://arbitrum-sepolia-rpc.publicnode.com',\n    ],\n  },\n} as const;\n\nexport const getRpcUrlById = (chainId: SupportedChain): string => {\n  const chainConfig = CHAIN_MAPPING[chainId];\n  return chainConfig?.rpcUrl;\n};\n\nexport const getRpcUrlsById = (chainId: SupportedChain): string[] => {\n  const rpcConfig = RPC_CONFIG[chainId as keyof typeof RPC_CONFIG];\n\n  if (!rpcConfig) {\n    throw new Error(`RPC configuration not found for chain ID: ${chainId}`);\n  }\n\n  return [rpcConfig.primary, ...rpcConfig.fallbacks];\n};\n\nexport const getViemChainById = (chainId: SupportedChain): Chain | undefined => {\n  const chainConfig = CHAIN_MAPPING[chainId];\n\n  if (!chainConfig) {\n    return undefined;\n  }\n\n  return {\n    id: chainConfig.chainId,\n    name: chainConfig.name,\n    network: chainConfig.network,\n    nativeCurrency: chainConfig.nativeCurrency,\n    rpcUrls: {\n      default: {\n        http: [chainConfig.rpcUrl],\n      },\n      public: {\n        http: [chainConfig.rpcUrl],\n      },\n    },\n    blockExplorers: {\n      default: {\n        name: chainConfig.blockExplorer.name,\n        url: chainConfig.blockExplorer.url,\n      },\n    },\n    testnet: chainConfig.testnet,\n  } as Chain;\n};\n\nexport const publicClintByChainId = (chainId: SupportedChain): PublicClient => {\n  const chainConfig = getViemChainById(chainId);\n  const rpcUrl = chainConfig?.rpcUrls.default.http[0];\n  if (!rpcUrl) {\n    throw new Error(`RPC URL not found for chain ${chainId}`);\n  }\n  return createPublicClient({\n    chain: chainConfig,\n    transport: http(rpcUrl),\n  });\n};\n","import axios from 'axios';\nimport { type SupportedChain } from '../types/supported-chains';\nimport { CHAIN_MAPPING } from './chains-constants';\nimport { BACKEND_URL, getStealthAddressGenerationMessage } from './constants';\nimport { type StealthAddressResponse } from '../types/stealth-address';\nimport {\n  generateEphemeralPrivateKey,\n  extractViewingPrivateKeyNode,\n  generateKeysFromSignature,\n  generateStealthPrivateKey,\n} from '@fluidkey/stealth-account-kit';\nimport { type Account, type WalletClient } from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\n\nexport const getStealthAddress = async (\n  tokenAddress: string,\n  username: string,\n  chainId: SupportedChain,\n): Promise<StealthAddressResponse> => {\n  const stealthAddresses: string[] = [];\n  const safeAddresses: string[] = [];\n\n  const chain = CHAIN_MAPPING[chainId];\n  const usernameStr = username as string;\n\n  let res: StealthAddressResponse = {} as StealthAddressResponse;\n\n  try {\n    // Headers to match the curl request exactly\n    const headers = {\n      accept: '*/*',\n      'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8,hi;q=0.7',\n      'content-type': 'application/json',\n      dnt: '1',\n    };\n\n    const stealthResponse = await axios.post(\n      `${BACKEND_URL}/api/user/${username}/stealth`,\n      {\n        chainId: chain?.chainId,\n        tokenAddress: tokenAddress,\n        tokenAmount: (50 * 5).toString(),\n      },\n      { headers },\n    );\n\n    const stealthResponseData = stealthResponse.data;\n\n    const stealthData = stealthResponseData.data;\n    stealthAddresses.push(stealthData.address);\n\n    // Only use safeAddress if it exists in the response\n    if (stealthData.safeAddress && stealthData.safeAddress.address) {\n      safeAddresses.push(stealthData.safeAddress.address);\n    } else {\n      throw new Error('No safeAddress in response');\n    }\n\n    const nonceResponse = await axios.get(`${BACKEND_URL}/api/user/${usernameStr}/nonce`, {\n      headers: { 'Content-Type': 'application/json' },\n    });\n\n    const nonceResponseData = nonceResponse.data;\n    const currentNonce = nonceResponseData.data.currentNonce;\n    const usedNonce = currentNonce - 1;\n\n    res = {\n      success: stealthResponseData.success,\n      timestamp: stealthResponseData.timestamp,\n      data: {\n        address: stealthData.address,\n        chainId: stealthData.chainId,\n        chainName: stealthData.chainName,\n        tokenAddress: stealthData.tokenAddress,\n        tokenAmount: stealthData.tokenAmount,\n        paymentId: stealthData.paymentId,\n        safeAddress: stealthData.safeAddress,\n        eventListener: stealthData.eventListener,\n        usedNonce: usedNonce,\n        currentNonce: currentNonce,\n      },\n      message: stealthResponseData.message,\n    };\n  } catch (error) {\n    console.error(\n      `    ❌ Failed to generate stealth address:`,\n      error instanceof Error ? error.message : String(error),\n    );\n\n    // Additional debugging for network errors\n    if (error instanceof TypeError && error.message === 'Failed to fetch') {\n      console.error('🌐 Network Error Details:');\n      console.error('- Check if the server is running');\n      console.error('- Check CORS settings');\n      console.error('- Check network connectivity');\n      console.error('- Server URL:', `${BACKEND_URL}/api/user/${usernameStr}/stealth`);\n    }\n\n    throw error;\n  }\n\n  return res;\n};\n\n// TODO: fetch sign message from contract\nexport const generateInitialKeysOnClient = async ({\n  uniqueNonces,\n  walletClient,\n  chainId,\n  msgToSign,\n}: {\n  uniqueNonces: number[];\n  walletClient: WalletClient;\n  chainId: SupportedChain;\n  msgToSign?: string;\n}): Promise<{\n  spendingKeys: string[];\n  viewingPrivateKey: string;\n}> => {\n  if (!walletClient) {\n    throw new Error('Wallet client not available');\n  }\n\n  // STEP 1: Create a deterministic message for signing\n  const message = msgToSign || getStealthAddressGenerationMessage(chainId);\n\n  const signature = await walletClient.signMessage({\n    message,\n    account: walletClient.account as Account,\n  });\n\n  const keys = generateKeysFromSignature(signature);\n\n  // STEP 5: Extract the viewing key node (used for address generation)\n  const viewKeyNodeNumber = 0; // Use the first node\n  const viewingPrivateKeyNode = extractViewingPrivateKeyNode(\n    keys.viewingPrivateKey,\n    viewKeyNodeNumber,\n  );\n\n  const processedKeys = uniqueNonces.map((nonce) => {\n    const ephemeralPrivateKey = generateEphemeralPrivateKey({\n      viewingPrivateKeyNode: viewingPrivateKeyNode,\n      nonce: BigInt(nonce.toString()), // convert to bigint\n      chainId: chainId,\n    });\n\n    const ephemeralPrivateKeyRaw = ephemeralPrivateKey;\n    console.log('ephemeralPrivateKeyRaw', ephemeralPrivateKeyRaw);\n\n    const ephemeralPrivateKeyHex = ephemeralPrivateKey.ephemeralPrivateKey;\n\n    console.log('ephemeralPrivateKeyHex', ephemeralPrivateKeyHex);\n\n    // Ensure it's in the correct format (0x prefixed hex string)\n    const formattedEphemeralPrivateKey = `${ephemeralPrivateKeyHex}` as `0x${string}`;\n\n    console.log('formattedEphemeralPrivateKey', formattedEphemeralPrivateKey);\n\n    // Generate the ephemeral public key\n    const ephemeralPublicKey = privateKeyToAccount(formattedEphemeralPrivateKey).publicKey;\n\n    console.log('ephemeralPublicKey', ephemeralPublicKey);\n\n    // Generate spending private key for this nonce\n    const spendingPrivateKey = generateStealthPrivateKey({\n      spendingPrivateKey: keys.spendingPrivateKey,\n      ephemeralPublicKey: ephemeralPublicKey,\n    });\n\n    // Handle the case where spendingPrivateKey might be an object, Uint8Array, or string\n    const spendingPrivateKeyRaw =\n      (spendingPrivateKey as { stealthPrivateKey?: string }).stealthPrivateKey ||\n      (spendingPrivateKey as { privateKey?: string }).privateKey ||\n      (spendingPrivateKey as { spendingPrivateKey?: string }).spendingPrivateKey ||\n      (spendingPrivateKey as { key?: string }).key ||\n      (spendingPrivateKey as { value?: string }).value ||\n      spendingPrivateKey;\n\n    let formattedSpendingPrivateKey;\n    if (\n      (typeof spendingPrivateKeyRaw === 'object' && 'byteLength' in spendingPrivateKeyRaw) ||\n      (typeof Buffer !== 'undefined' && Buffer.isBuffer(spendingPrivateKeyRaw))\n    ) {\n      const spendingPrivateKeyHex = Array.from(spendingPrivateKeyRaw as Uint8Array)\n        .map((b) => b.toString(16).padStart(2, '0'))\n        .join('');\n      formattedSpendingPrivateKey = `0x${spendingPrivateKeyHex}` as `0x${string}`;\n    } else if (typeof spendingPrivateKeyRaw === 'string') {\n      const cleanHex = spendingPrivateKeyRaw.replace('0x', '');\n      formattedSpendingPrivateKey = `0x${cleanHex}` as `0x${string}`;\n    } else {\n      // If we still have an object, try to find the actual key\n      console.error('Unable to extract private key from:', spendingPrivateKeyRaw);\n      throw new Error('Cannot extract private key from spendingPrivateKey object');\n    }\n\n    return formattedSpendingPrivateKey;\n  });\n\n  return {\n    spendingKeys: processedKeys,\n    viewingPrivateKey: keys.viewingPrivateKey,\n  };\n};\n\n// Backward compatibility wrapper - returns just the spending keys array\nexport const generateInitialKeysOnClientLegacy = async (params: {\n  uniqueNonces: number[];\n  walletClient: WalletClient;\n  chainId: SupportedChain;\n  msgToSign?: string;\n}): Promise<string[]> => {\n  const result = await generateInitialKeysOnClient(params);\n  return result.spendingKeys;\n};\n","import { arbitrumSepolia, baseSepolia } from 'viem/chains';\nimport { SupportedChain } from '../types/supported-chains';\nimport { type Address, type Abi } from 'viem';\n\nexport const BACKEND_URL = 'https://unwallet-production.up.railway.app';\n\nexport const FACILITATOR_URL = 'https://arbsep.facilitator.unwallet.me';\n\nexport const SERVER_URL_ENS = 'https://tee.wall8.xyz';\n// export const SERVER_URL_ENS = 'http://localhost:3000';\n\n// AAVE Pool Addresses (vault addresses for all modules)\nexport const AAVE_POOL_ADDRESSES = {\n  [baseSepolia.id]: '0x07eA79F68B2B3df564D0A34F8e19D9B1e339814b',\n  [arbitrumSepolia.id]: '0xBfC91D59fdAA134A4ED45f7B584cAf96D7792Eff',\n} as const;\n\ntype ModuleConfig = {\n  abi: Abi; // or unknown[] or readonly unknown[]\n  bondContractAddress: Address;\n  autoEarnContractAddress: Address;\n  autoSwapContractAddress: Address;\n  autoBridgeContractAddress: Address;\n};\n\nexport const BOND_ABI = [\n  {\n    name: 'getConfigInputTypeData',\n    type: 'function',\n    stateMutability: 'pure',\n    inputs: [],\n    outputs: [\n      {\n        name: 'configInputTypeData',\n        type: 'string',\n      },\n    ],\n  },\n];\n\nexport const MODULE_DATA = {\n  [baseSepolia.id as SupportedChain]: {\n    abi: BOND_ABI,\n    bondContractAddress: '0x6e1fAc6e36f01615ef0c0898Bf6c5F260Bf2609a', // autoEarn on Base Sepolia\n    autoEarnContractAddress: '0x6e1fAc6e36f01615ef0c0898Bf6c5F260Bf2609a',\n    autoSwapContractAddress: '0x564B1354Af4D3EA51eE3a9eFaD608E9aa78d3905',\n    autoBridgeContractAddress: '0xe8Da54c7056680FF1b7FF6E9dfD0721dDcAd3F14',\n    investInVerifiableAgentsContractAddress: '0xVerifiableAgentsContractAddress',\n    investInAaveContractAddress: '0xAaveContractAddress',\n  },\n  [arbitrumSepolia.id as SupportedChain]: {\n    abi: BOND_ABI,\n    bondContractAddress: '0x748Cb019ffF904482e8518124F2BbFF0Ea7Ec7d6',\n    autoEarnContractAddress: '0x42CF1b746F96D6cc59e84F87d26Ea64D3fbCa3a0', // Correct AutoEarn module address\n    autoSwapContractAddress: '0x537a0aB5A0172E69EC824cD1048A57eca95c696B',\n    autoBridgeContractAddress: '0xDdAd6d1084fF9e8CaBf579358A95666Bf5515F51',\n    investInVerifiableAgentsContractAddress: '0xVerifiableAgentsContractAddress',\n    investInAaveContractAddress: '0xAaveContractAddress',\n  },\n} as const satisfies Partial<Record<SupportedChain, ModuleConfig>>;\n\nexport const AVAILABLE_MODULES = [\n  'AUTOEARN',\n  'AUTOSWAP',\n  'AUTOBRIDGE',\n  'BOND',\n  'INVEST_IN_VERIFIABLE_AGENTS',\n  'INVEST_IN_AAVE',\n] as const;\n\nexport const getRequiredAvailableModules = (): readonly string[] => {\n  return AVAILABLE_MODULES;\n};\n\nexport const getModuleAddress = (moduleName: string, chainId: SupportedChain) => {\n  const upperModuleName = moduleName.toUpperCase();\n\n  switch (upperModuleName) {\n    case 'AUTOEARN':\n      return MODULE_DATA[chainId].autoEarnContractAddress;\n    case 'AUTOSWAP':\n      return MODULE_DATA[chainId].autoSwapContractAddress;\n    case 'AUTOBRIDGE':\n      return MODULE_DATA[chainId].autoBridgeContractAddress;\n    case 'BOND':\n      return MODULE_DATA[chainId].bondContractAddress;\n    case 'INVEST_IN_VERIFIABLE_AGENTS':\n      return MODULE_DATA[chainId].investInVerifiableAgentsContractAddress;\n    case 'INVEST_IN_AAVE':\n      return MODULE_DATA[chainId].investInAaveContractAddress;\n    default:\n      throw new Error(`Invalid module name: ${moduleName}`);\n  }\n};\n\nexport const getStealthAddressGenerationMessage = (chainId: SupportedChain) => {\n  switch (chainId) {\n    case baseSepolia.id:\n      return 'STEALTH_ADDRESS_GENERATION_ZZZZZ_BASE_SEPOLIA';\n    case arbitrumSepolia.id:\n      return 'STEALTH_ADDRESS_GENERATION_ZZZZZ_ARB_SEPOLIA';\n    default:\n      throw new Error(`Unsupported chain ID: ${chainId}`);\n  }\n};\n\nexport const SAFE_ABI = [\n  {\n    inputs: [\n      { name: 'to', type: 'address' },\n      { name: 'value', type: 'uint256' },\n      { name: 'data', type: 'bytes' },\n      { name: 'operation', type: 'uint8' },\n      { name: 'safeTxGas', type: 'uint256' },\n      { name: 'baseGas', type: 'uint256' },\n      { name: 'gasPrice', type: 'uint256' },\n      { name: 'gasToken', type: 'address' },\n      { name: 'refundReceiver', type: 'address' },\n      { name: 'signatures', type: 'bytes' },\n    ],\n    name: 'execTransaction',\n    outputs: [{ name: 'success', type: 'bool' }],\n    stateMutability: 'nonpayable',\n    type: 'function',\n  },\n];\n\nexport const USDC_ABI = [\n  {\n    inputs: [\n      { name: 'to', type: 'address' },\n      { name: 'amount', type: 'uint256' },\n    ],\n    name: 'mint',\n    outputs: [],\n    stateMutability: 'nonpayable',\n    type: 'function',\n  },\n  {\n    inputs: [\n      { name: 'to', type: 'address' },\n      { name: 'amount', type: 'uint256' },\n    ],\n    name: 'transfer',\n    outputs: [{ name: '', type: 'bool' }],\n    stateMutability: 'nonpayable',\n    type: 'function',\n  },\n  {\n    inputs: [{ name: 'account', type: 'address' }],\n    name: 'balanceOf',\n    outputs: [{ name: '', type: 'uint256' }],\n    stateMutability: 'view',\n    type: 'function',\n  },\n];\n","import axios from 'axios';\nimport { formatUnits, parseAbi, PublicClient } from 'viem';\nimport { BACKEND_URL } from './constants';\nimport {\n  type TransactionResult,\n  type BalanceData,\n  type FundedAddress,\n} from '../types/withdrawal-data';\n\n// ERC20 ABI for the functions we need\nconst erc20Abi = parseAbi([\n  'function balanceOf(address owner) view returns (uint256)',\n  'function decimals() view returns (uint8)',\n  'function symbol() view returns (string)',\n]);\n\n// Common Multicall3 address\nconst MULTICALL3_ADDRESS = '0xcA11bde05977b3631167028862bE2a173976CA11';\n\nexport const getTransactions = async ({\n  username,\n  publicClient,\n}: {\n  username: string;\n  publicClient: PublicClient;\n}): Promise<TransactionResult> => {\n  try {\n    console.log(`🔍 Fetching withdrawals for username: ${username}`);\n\n    // Fetch funding stats from backend\n    const response = await axios.get(`${BACKEND_URL}/api/user/${username}/funding-stats`);\n\n    const data = response.data;\n    console.log('Funding stats response:', data);\n\n    const fundedAddresses: FundedAddress[] = data.data.fundedAddresses || [];\n\n    if (fundedAddresses.length === 0) {\n      console.log('No funded addresses found.');\n      return {\n        balanceData: [],\n        success: true,\n      };\n    }\n\n    // Collect all address-token pairs that need to be checked\n    const addressTokenPairs: Array<{\n      walletAddress: string;\n      tokenAddress: string;\n      index: number;\n      originalData: FundedAddress;\n      isFunded: boolean;\n    }> = [];\n\n    fundedAddresses.forEach((funded, index) => {\n      const fromAddress = funded.fromAddress;\n      const safeAddress = funded.safeAddress;\n      const tokenAddress = funded.tokenAddress;\n\n      // Add fromAddress if it exists (funded addresses)\n      if (fromAddress) {\n        addressTokenPairs.push({\n          walletAddress: safeAddress, // Check balance at safe address\n          tokenAddress: tokenAddress,\n          index: index,\n          originalData: funded,\n          isFunded: true,\n        });\n      }\n\n      // Also add safeAddress for unfunded addresses\n      if (!fromAddress && safeAddress) {\n        addressTokenPairs.push({\n          walletAddress: safeAddress,\n          tokenAddress: tokenAddress,\n          index: index,\n          originalData: funded,\n          isFunded: false,\n        });\n      }\n    });\n\n    console.log(`Checking ${addressTokenPairs.length} address-token pairs...`);\n\n    // Use multicall to fetch all token data\n    const contracts = addressTokenPairs.flatMap((pair) => [\n      {\n        address: pair.tokenAddress as `0x${string}`,\n        abi: erc20Abi,\n        functionName: 'balanceOf',\n        args: [pair.walletAddress as `0x${string}`],\n      },\n      {\n        address: pair.tokenAddress as `0x${string}`,\n        abi: erc20Abi,\n        functionName: 'decimals',\n      },\n      {\n        address: pair.tokenAddress as `0x${string}`,\n        abi: erc20Abi,\n        functionName: 'symbol',\n      },\n    ]);\n\n    const results = await publicClient.multicall({\n      contracts,\n      allowFailure: true,\n      multicallAddress: MULTICALL3_ADDRESS as `0x${string}`,\n    });\n\n    console.log('✅ Multicall successful');\n\n    // Process multicall results\n    const finalBalanceData: BalanceData[] = [];\n\n    for (let i = 0; i < addressTokenPairs.length; i++) {\n      const balanceResult = results[i * 3];\n      const decimalsResult = results[i * 3 + 1];\n      const symbolResult = results[i * 3 + 2];\n      const originalPair = addressTokenPairs[i];\n\n      if (\n        balanceResult?.status === 'success' &&\n        decimalsResult?.status === 'success' &&\n        symbolResult?.status === 'success'\n      ) {\n        const rawBalance = BigInt(balanceResult.result as string | number);\n        const decimals = decimalsResult.result as number;\n        const symbol = symbolResult.result as string;\n\n        const formattedBalance = formatUnits(rawBalance, decimals);\n\n        if (rawBalance > BigInt(0)) {\n          finalBalanceData.push({\n            address: originalPair.isFunded\n              ? originalPair.originalData.fromAddress || originalPair.walletAddress\n              : originalPair.walletAddress,\n            balance: formattedBalance,\n            symbol: symbol,\n            rawBalance: rawBalance.toString(),\n            nonce: originalPair.originalData.nonce || 0,\n            decimals: decimals,\n            tokenAddress: originalPair.tokenAddress,\n            transactionHash: originalPair.originalData.transactionHash,\n            stealthAddress: originalPair.originalData.stealthAddress,\n            safeAddress: originalPair.originalData.safeAddress,\n            isFunded: originalPair.isFunded,\n          });\n\n          console.log(`💰 Found funds:`, {\n            address: originalPair.walletAddress,\n            balance: formattedBalance,\n            symbol: symbol,\n            isFunded: originalPair.isFunded,\n          });\n        }\n      }\n    }\n\n    console.log(\n      `✅ Balance check complete. Found ${finalBalanceData.length} addresses with balances.`,\n    );\n\n    return {\n      balanceData: finalBalanceData,\n      success: true,\n    };\n  } catch (error) {\n    console.error('Error fetching withdrawals:', error);\n    const errorMessage = error instanceof Error ? error.message : 'Failed to fetch withdrawals';\n\n    return {\n      balanceData: [],\n      success: false,\n      error: errorMessage,\n    };\n  }\n};\n","import {\n  createWalletClient,\n  encodeFunctionData,\n  http,\n  parseUnits,\n  PublicClient,\n  WalletClient,\n} from 'viem';\nimport { SupportedChain } from '../types/supported-chains';\nimport { generateInitialKeysOnClientLegacy } from './stealth-address';\nimport { privateKeyToAccount } from 'viem/accounts';\nimport {\n  buildSafeTransaction,\n  executeTransactionWithGasSponsorship,\n  predictSafeAddress,\n  safeSignTypedData,\n} from './safe-utils';\nimport { getRpcUrlById, getViemChainById, publicClintByChainId } from './chains-constants';\nimport Safe from '@safe-global/protocol-kit';\nimport { BACKEND_URL, SAFE_ABI, USDC_ABI } from './constants';\nimport {\n  type SinglePaymentResult,\n  type TransferWithAuthorizationData,\n  type TransferWithAuthorizationResult,\n} from '../types/payments';\nimport { getTransactions } from './transaction-utils';\nimport axios from 'axios';\nimport crypto from 'crypto';\n\nexport const singlePayment = async ({\n  walletClient,\n  chainId,\n  tokenAddress,\n  requestedAmount,\n  recipientAddress,\n  publicClient,\n}: {\n  walletClient: WalletClient;\n  chainId: SupportedChain;\n  tokenAddress: string;\n  requestedAmount: string;\n  recipientAddress: string;\n  publicClient: PublicClient;\n}): Promise<SinglePaymentResult> => {\n  try {\n    const userAddress = walletClient.account?.address;\n    if (!userAddress) {\n      throw new Error('User address not found');\n    }\n\n    const { data } = await axios.post(`${BACKEND_URL}/api/user/resolve-username-by-eoa`, {\n      eoaaddress: userAddress,\n    });\n\n    if (!data.success) {\n      throw new Error('Failed to resolve username');\n    }\n\n    const username = data.data.username;\n\n    const txnsResult = await getTransactions({\n      username,\n      publicClient: publicClintByChainId(chainId),\n    });\n\n    if (!txnsResult.success || !txnsResult.balanceData) {\n      throw new Error('Failed to fetch transactions');\n    }\n\n    const txns = txnsResult.balanceData;\n\n    console.log('🚀 Starting multicall payment process...');\n    console.log('📋 Available transactions:', txns.length);\n    console.log('🎯 Requested amount:', requestedAmount);\n    console.log('💰 Recipient address:', recipientAddress);\n\n    // Filter transactions for the specific token and sort by balance (highest first)\n    const relevantTxns = txns\n      .filter((txn) => txn.tokenAddress.toLowerCase() === tokenAddress.toLowerCase())\n      .sort((a, b) => parseFloat(b.balance) - parseFloat(a.balance));\n\n    console.log('🔍 Relevant transactions for token:', relevantTxns.length);\n\n    // Select transactions to fulfill the requested amount\n    const selectedTxns = [];\n    let remainingAmount = parseFloat(requestedAmount);\n    const requestedAmountFloat = parseFloat(requestedAmount);\n\n    for (const txn of relevantTxns) {\n      if (remainingAmount <= 0) break;\n\n      const txnBalance = parseFloat(txn.balance);\n      const amountToTransfer = Math.min(remainingAmount, txnBalance);\n\n      selectedTxns.push({\n        ...txn,\n        amountToTransfer: amountToTransfer.toString(),\n      });\n\n      remainingAmount -= amountToTransfer;\n    }\n\n    if (remainingAmount > 0) {\n      const availableAmount = requestedAmountFloat - remainingAmount;\n      throw new Error(\n        `Insufficient balance. Available: ${availableAmount}, Requested: ${requestedAmount}`,\n      );\n    }\n\n    console.log('✅ Selected transactions:', selectedTxns.length);\n    console.log('💰 Requested amount to transfer:', requestedAmount);\n\n    // Generate stealth keys for all selected transactions\n    const nonces = selectedTxns.map((txn) => txn.nonce);\n    const keys = await generateInitialKeysOnClientLegacy({\n      walletClient,\n      uniqueNonces: nonces,\n      chainId,\n    });\n\n    console.log(`🔐 Generated ${keys.length} stealth keys`);\n\n    // Prepare multicall data for all transactions\n    const allMulticallData = [];\n    const batchMetadata = [];\n\n    for (let i = 0; i < selectedTxns.length; i++) {\n      const txn = selectedTxns[i];\n      const spendingPrivateKey = keys[i];\n      const stealthAddress = privateKeyToAccount(spendingPrivateKey as `0x${string}`).address;\n\n      console.log(`\\n🔍 Processing transaction ${i + 1}/${selectedTxns.length}:`);\n      console.log(`   - Nonce: ${txn.nonce}`);\n      console.log(`   - Stealth Address: ${stealthAddress}`);\n      console.log(\n        `   - Amount: ${txn.balance} ${txn.symbol} (transferring: ${txn.amountToTransfer})`,\n      );\n\n      // Predict Safe address\n      const predictedSafeAddress = await predictSafeAddress(stealthAddress, chainId);\n      console.log(`   - Predicted Safe: ${predictedSafeAddress}`);\n\n      // Initialize Safe Protocol Kit\n      const predictedSafe = {\n        safeAccountConfig: {\n          owners: [stealthAddress],\n          threshold: 1,\n        },\n        safeDeploymentConfig: {\n          saltNonce: '0',\n        },\n      };\n\n      const RPC_URL = getRpcUrlById(chainId);\n      const protocolKit = await Safe.init({\n        provider: RPC_URL,\n        signer: stealthAddress,\n        predictedSafe,\n      });\n\n      // Check if Safe is deployed\n      const isSafeDeployed = await protocolKit.isSafeDeployed();\n      console.log(`   - Safe deployed: ${isSafeDeployed}`);\n\n      let deploymentTransaction;\n      let safeNonce = 0;\n\n      if (!isSafeDeployed) {\n        console.log('   - Creating Safe deployment transaction...');\n        deploymentTransaction = await protocolKit.createSafeDeploymentTransaction();\n      } else {\n        console.log('   - Getting Safe nonce...');\n        if (!publicClient) {\n          throw new Error('Public client not available');\n        }\n\n        const safeNonceData = encodeFunctionData({\n          abi: [\n            {\n              inputs: [],\n              name: 'nonce',\n              outputs: [{ name: '', type: 'uint256' }],\n              stateMutability: 'view',\n              type: 'function',\n            },\n          ],\n          functionName: 'nonce',\n        });\n\n        const safeNonceResult = await publicClient.call({\n          to: predictedSafeAddress as `0x${string}`,\n          data: safeNonceData,\n        });\n\n        safeNonce = Number(BigInt(safeNonceResult.data || '0x0'));\n        console.log(`   - Safe nonce: ${safeNonce}`);\n      }\n\n      // Create wallet client and transfer data\n      const spendingWalletClient = createWalletClient({\n        account: privateKeyToAccount(spendingPrivateKey as `0x${string}`),\n        chain: getViemChainById(chainId),\n        transport: http(RPC_URL),\n      });\n\n      const transferData = encodeFunctionData({\n        abi: [\n          {\n            inputs: [\n              { name: 'to', type: 'address' },\n              { name: 'amount', type: 'uint256' },\n            ],\n            name: 'transfer',\n            outputs: [{ name: '', type: 'bool' }],\n            stateMutability: 'nonpayable',\n            type: 'function',\n          },\n        ],\n        functionName: 'transfer',\n        args: [recipientAddress as `0x${string}`, parseUnits(txn.amountToTransfer, txn.decimals)],\n      });\n\n      // Build and sign Safe transaction\n      const safeTransaction = buildSafeTransaction({\n        to: txn.tokenAddress,\n        value: '0',\n        data: transferData,\n        operation: 0,\n        safeTxGas: '0',\n        nonce: safeNonce,\n      });\n\n      const account = privateKeyToAccount(spendingPrivateKey as `0x${string}`);\n      const signature = await safeSignTypedData(\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        spendingWalletClient as any,\n        account,\n        predictedSafeAddress as `0x${string}`,\n        safeTransaction,\n        chainId,\n      );\n\n      // Encode execTransaction call\n      const execTransactionData = encodeFunctionData({\n        abi: SAFE_ABI,\n        functionName: 'execTransaction',\n        args: [\n          safeTransaction.to as `0x${string}`,\n          BigInt(safeTransaction.value || '0'),\n          safeTransaction.data as `0x${string}`,\n          safeTransaction.operation,\n          BigInt(safeTransaction.safeTxGas || '0'),\n          BigInt(safeTransaction.baseGas || '0'),\n          BigInt(safeTransaction.gasPrice || '0'),\n          (safeTransaction.gasToken ||\n            '0x0000000000000000000000000000000000000000') as `0x${string}`,\n          (safeTransaction.refundReceiver ||\n            '0x0000000000000000000000000000000000000000') as `0x${string}`,\n          signature as `0x${string}`,\n        ],\n      });\n\n      // Add transactions to multicall data\n      if (!isSafeDeployed && deploymentTransaction) {\n        allMulticallData.push({\n          target: deploymentTransaction.to,\n          allowFailure: false,\n          callData: deploymentTransaction.data,\n        });\n        console.log(`   - Added Safe deployment for transaction ${i + 1}`);\n      }\n\n      allMulticallData.push({\n        target: predictedSafeAddress,\n        allowFailure: false,\n        callData: execTransactionData,\n      });\n      console.log(`   - Added transfer for transaction ${i + 1}`);\n\n      // Store metadata for this transaction\n      batchMetadata.push({\n        nonce: txn.nonce,\n        stealthAddress,\n        predictedSafeAddress,\n        amount: txn.amountToTransfer,\n        symbol: txn.symbol,\n        isSafeDeployed,\n      });\n    }\n\n    console.log('\\n📋 Batch multicall data prepared:', {\n      totalTransactions: selectedTxns.length,\n      totalCalls: allMulticallData.length,\n      calls: allMulticallData.map((call, i) => ({\n        index: i + 1,\n        target: call.target,\n        allowFailure: call.allowFailure,\n        dataLength: call.callData.length,\n      })),\n    });\n\n    // Execute batch transaction with gas sponsorship\n    console.log('🌟 Executing batch transaction with gas sponsorship...');\n\n    const metadata = {\n      operationType: 'batch_redemption',\n      paymentCount: selectedTxns.length,\n      nonces: nonces,\n      recipientAddress: recipientAddress,\n      tokenAddress: tokenAddress,\n      symbol: selectedTxns[0].symbol,\n      batchMetadata: batchMetadata,\n    };\n\n    const sponsorshipResult = await executeTransactionWithGasSponsorship(\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      allMulticallData as any,\n      metadata,\n      username,\n      chainId,\n    );\n\n    console.log('✅ Batch redemption completed successfully!');\n\n    // Verify the transfer worked\n    console.log('🔍 Verifying transfer results...');\n\n    let recipientBalanceFormatted = '0.00';\n\n    try {\n      // Check recipient balance\n      const recipientBalanceData = encodeFunctionData({\n        abi: USDC_ABI,\n        functionName: 'balanceOf',\n        args: [recipientAddress as `0x${string}`],\n      });\n\n      if (!publicClient) {\n        throw new Error('Public client not available');\n      }\n\n      console.log('🔍 Checking recipient balance at:', {\n        recipientAddress,\n        tokenAddress: tokenAddress,\n      });\n\n      const recipientBalanceResult = await publicClient.call({\n        to: tokenAddress as `0x${string}`,\n        data: recipientBalanceData,\n      });\n\n      const recipientBalance = BigInt(recipientBalanceResult.data || '0x0');\n      recipientBalanceFormatted = (Number(recipientBalance) / Math.pow(10, 6)).toFixed(2);\n\n      console.log('✅ Balance check successful:', {\n        recipientBalance: recipientBalance.toString(),\n        recipientBalanceFormatted,\n      });\n    } catch (balanceError) {\n      console.warn('⚠️ Balance verification failed, but transaction was successful:', balanceError);\n    }\n\n    console.log('✅ Gas sponsored transfer verification:', {\n      recipient: recipientAddress,\n      receivedAmount: `${recipientBalanceFormatted} USDC`,\n      transactionHash: sponsorshipResult.txHash,\n      explorerUrl: sponsorshipResult.explorerUrl,\n      sponsorAddress: sponsorshipResult.sponsorDetails.sponsorAddress,\n      gasUsed: sponsorshipResult.gasUsed,\n      gasCost: sponsorshipResult.gasCost,\n    });\n\n    // Return success response with sponsorship details\n    return {\n      success: true,\n      deploymentTransaction: undefined, // Not applicable for batch\n      safeTransaction: {\n        to: tokenAddress,\n        value: '0',\n        data: '',\n        operation: 0,\n        safeTxGas: '0',\n        baseGas: '0',\n        gasPrice: '0',\n        gasToken: '0x0000000000000000000000000000000000000000',\n        refundReceiver: '0x0000000000000000000000000000000000000000',\n        nonce: 0,\n      },\n      signature: '',\n      txHash: sponsorshipResult.txHash,\n      gasUsed: sponsorshipResult.gasUsed,\n      gasCost: sponsorshipResult.gasCost,\n      explorerUrl: sponsorshipResult.explorerUrl,\n      sponsorDetails: sponsorshipResult.sponsorDetails,\n      summary: {\n        stealthAddress: batchMetadata[0]?.stealthAddress || '',\n        safeAddress: batchMetadata[0]?.predictedSafeAddress || '',\n        recipient: recipientAddress,\n        multicallCalls: allMulticallData.length,\n        executed: true,\n        txHash: sponsorshipResult.txHash,\n        recipientBalance: `${recipientBalanceFormatted} USDC`,\n        sponsoredBy: sponsorshipResult.sponsorDetails.sponsorAddress,\n        gasUsed: sponsorshipResult.gasUsed,\n        explorerUrl: sponsorshipResult.explorerUrl,\n      },\n    };\n  } catch (error) {\n    console.error('❌ Sponsored redemption failed:', error);\n\n    // Log detailed error information\n    if (error instanceof Error) {\n      console.error('Error details:', {\n        message: error.message,\n        stack: error.stack,\n        name: error.name,\n      });\n    } else {\n      console.error('Unknown error type:', typeof error, error);\n    }\n\n    // Re-throw with more context\n    const errorMessage = error instanceof Error ? error.message : String(error);\n    throw new Error(`Withdrawal failed: ${errorMessage}`);\n  }\n};\n\nexport const transferWithAuthorization = async ({\n  walletClient,\n  chainId,\n  tokenAddress,\n  recipientAddress,\n  amount,\n  validAfter = '0',\n  validBefore,\n}: {\n  walletClient: WalletClient;\n  chainId: SupportedChain;\n  tokenAddress: string;\n  recipientAddress: string;\n  amount: string;\n  validAfter?: string;\n  validBefore?: string;\n}): Promise<TransferWithAuthorizationResult> => {\n  try {\n    const userAddress = walletClient.account?.address;\n    if (!userAddress) {\n      throw new Error('User address not found');\n    }\n\n    console.log('🚀 Starting transferWithAuthorization...');\n    console.log('📋 Transfer details:', {\n      from: userAddress,\n      to: recipientAddress,\n      amount,\n      tokenAddress,\n      chainId,\n    });\n\n    // Generate random nonce\n    const nonce = '0x' + crypto.randomBytes(32).toString('hex');\n\n    // Set validBefore to 1 hour from now if not provided\n    const validBeforeTimestamp = validBefore || Math.floor(Date.now() / 1000 + 3600).toString();\n\n    // Create authorization data\n    const authorization: TransferWithAuthorizationData = {\n      from: userAddress,\n      to: recipientAddress,\n      value: amount,\n      validAfter,\n      validBefore: validBeforeTimestamp,\n      nonce,\n    };\n\n    console.log('✅ Authorization created:', authorization);\n\n    // Create EIP-712 domain and types for USDC TransferWithAuthorization\n    const domain = {\n      name: 'USD Coin',\n      version: '2',\n      chainId: chainId,\n      verifyingContract: tokenAddress,\n    };\n\n    const types = {\n      TransferWithAuthorization: [\n        { name: 'from', type: 'address' },\n        { name: 'to', type: 'address' },\n        { name: 'value', type: 'uint256' },\n        { name: 'validAfter', type: 'uint256' },\n        { name: 'validBefore', type: 'uint256' },\n        { name: 'nonce', type: 'bytes32' },\n      ],\n    };\n\n    const message = {\n      from: authorization.from,\n      to: authorization.to,\n      value: BigInt(authorization.value),\n      validAfter: BigInt(authorization.validAfter),\n      validBefore: BigInt(authorization.validBefore),\n      nonce: authorization.nonce,\n    };\n\n    console.log('✍️ Signing authorization...');\n\n    // Sign the typed data\n    const signature = await walletClient.signTypedData({\n      account: walletClient.account!,\n      domain,\n      types,\n      primaryType: 'TransferWithAuthorization',\n      message,\n    });\n\n    console.log('✅ Signature created:', signature);\n\n    // Get chain configuration for explorer URL\n    const chainConfig = getViemChainById(chainId);\n    const explorerUrl = chainConfig?.blockExplorers?.default?.url;\n\n    console.log('🎉 TransferWithAuthorization completed successfully!');\n\n    return {\n      success: true,\n      signature,\n      authorization,\n      explorerUrl: explorerUrl ? `${explorerUrl}/address/${tokenAddress}` : undefined,\n    };\n  } catch (error) {\n    console.error('❌ TransferWithAuthorization failed:', error);\n\n    const errorMessage = error instanceof Error ? error.message : String(error);\n\n    return {\n      success: false,\n      signature: '',\n      authorization: {\n        from: '',\n        to: '',\n        value: '',\n        validAfter: '',\n        validBefore: '',\n        nonce: '',\n      },\n      error: errorMessage,\n    };\n  }\n};\n","import Safe from '@safe-global/protocol-kit';\nimport { getRpcUrlsById, getViemChainById } from './chains-constants';\nimport { BACKEND_URL } from './constants';\nimport { SupportedChain } from '../types/supported-chains';\n\n// Helper function to build Safe transaction\nexport const buildSafeTransaction = (txData: {\n  to: string;\n  value?: string;\n  data?: string;\n  operation?: number;\n  safeTxGas?: string;\n  baseGas?: string;\n  gasPrice?: string;\n  gasToken?: string;\n  refundReceiver?: string;\n  nonce?: number;\n}) => {\n  return {\n    to: txData.to,\n    value: txData.value || '0',\n    data: txData.data || '0x',\n    operation: txData.operation || 0,\n    safeTxGas: txData.safeTxGas || '0',\n    baseGas: txData.baseGas || '0',\n    gasPrice: txData.gasPrice || '0',\n    gasToken: txData.gasToken || '0x0000000000000000000000000000000000000000',\n    refundReceiver: txData.refundReceiver || '0x0000000000000000000000000000000000000000',\n    nonce: txData.nonce || 0,\n  };\n};\n\n// Helper function to sign typed data\nexport const safeSignTypedData = async (\n  walletClient: {\n    signTypedData: (params: {\n      account: { address: string };\n      domain: { chainId: number; verifyingContract: string };\n      types: Record<string, Array<{ type: string; name: string }>>;\n      primaryType: string;\n      message: Record<string, string | number>;\n    }) => Promise<string>;\n  },\n  account: { address: string },\n  safeAddress: string,\n  safeTx: {\n    to: string;\n    value: string;\n    data: string;\n    operation: number;\n    safeTxGas: string;\n    baseGas: string;\n    gasPrice: string;\n    gasToken: string;\n    refundReceiver: string;\n    nonce: number;\n  },\n  chainId: number,\n) => {\n  const domain = {\n    chainId: chainId,\n    verifyingContract: safeAddress,\n  };\n\n  const types = {\n    SafeTx: [\n      { type: 'address', name: 'to' },\n      { type: 'uint256', name: 'value' },\n      { type: 'bytes', name: 'data' },\n      { type: 'uint8', name: 'operation' },\n      { type: 'uint256', name: 'safeTxGas' },\n      { type: 'uint256', name: 'baseGas' },\n      { type: 'uint256', name: 'gasPrice' },\n      { type: 'address', name: 'gasToken' },\n      { type: 'address', name: 'refundReceiver' },\n      { type: 'uint256', name: 'nonce' },\n    ],\n  };\n\n  const message = {\n    to: safeTx.to,\n    value: safeTx.value.toString(),\n    data: safeTx.data,\n    operation: safeTx.operation,\n    safeTxGas: safeTx.safeTxGas.toString(),\n    baseGas: safeTx.baseGas.toString(),\n    gasPrice: safeTx.gasPrice.toString(),\n    gasToken: safeTx.gasToken,\n    refundReceiver: safeTx.refundReceiver,\n    nonce: Number(safeTx.nonce),\n  };\n\n  return await walletClient.signTypedData({\n    account,\n    domain,\n    types,\n    primaryType: 'SafeTx',\n    message,\n  });\n};\n\n// Predict safe address based on stealth address\nexport async function predictSafeAddress(stealthAddress: string, chainId: SupportedChain) {\n  // Use centralized RPC configuration with QuickNode as primary\n  const rpcEndpoints = getRpcUrlsById(chainId);\n\n  try {\n    console.log('🔍 Predicting Safe address using Protocol Kit for:', stealthAddress);\n\n    // Use Safe Protocol Kit's built-in prediction with custom contract addresses for Sei Testnet\n    const predictedSafe = {\n      safeAccountConfig: {\n        owners: [stealthAddress],\n        threshold: 1,\n      },\n      safeDeploymentConfig: {\n        saltNonce: '0',\n      },\n    };\n\n    // For Base Sepolia we rely on RPC URI only; do not use contractNetworks\n\n    // Try multiple RPC endpoints\n    for (let i = 0; i < rpcEndpoints.length; i++) {\n      const currentRpcUrl = rpcEndpoints[i];\n      console.log(`🔄 Trying RPC endpoint ${i + 1}/${rpcEndpoints.length}: ${currentRpcUrl}`);\n\n      try {\n        const protocolKit = await Safe.init({\n          provider: currentRpcUrl,\n          predictedSafe,\n        });\n\n        const predictedAddress = await protocolKit.getAddress();\n        console.log(`✅ Safe address predicted successfully with RPC ${i + 1}:`, predictedAddress);\n        return predictedAddress;\n      } catch (rpcError) {\n        console.warn(`❌ RPC endpoint ${i + 1} failed:`, rpcError);\n        if (i === rpcEndpoints.length - 1) {\n          // This was the last RPC endpoint, throw the error\n          throw rpcError;\n        }\n        // Continue to next RPC endpoint\n        continue;\n      }\n    }\n  } catch (error) {\n    console.error('❌ Error predicting safe address:', error);\n\n    // Final fallback: Calculate Safe address manually if Protocol Kit fails\n    console.log('🔄 Attempting manual Safe address calculation...');\n    // Final rethrow with helpful message; removing unused manual variables\n    throw new Error(\n      `Safe address prediction failed. Please check RPC connectivity and contract addresses. Original error: ${error}`,\n    );\n  }\n}\n\nexport const executeTransactionWithGasSponsorship = async (\n  multicallData: Array<{\n    target: string;\n    allowFailure: boolean;\n    callData: string;\n  }>,\n  metadata: Record<string, unknown> = {},\n  username: string,\n  chainId: SupportedChain,\n) => {\n  try {\n    console.log('🌟 Requesting gas sponsorship for transaction...');\n\n    // Make request to gas sponsorship endpoint\n    const response = await fetch(`${BACKEND_URL}/api/user/${username}/gas-sponsorship`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n      },\n      body: JSON.stringify({\n        multicallData,\n        metadata: {\n          ...metadata,\n          userAgent: navigator.userAgent,\n          timestamp: new Date().toISOString(),\n          requestId: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n        },\n        chainId: chainId,\n      }),\n    });\n\n    const result = await response.json();\n    console.log('📄 Backend response:', result);\n\n    if (!response.ok) {\n      throw new Error(result.message || result.error || 'Gas sponsorship request failed');\n    }\n\n    if (!result.success) {\n      throw new Error(result.message || 'Gas sponsorship service returned failure');\n    }\n\n    console.log('✅ Gas sponsored transaction completed successfully!');\n    console.log('📊 Transaction details:', result);\n\n    const currentNetwork = getViemChainById(chainId);\n    const explorer = currentNetwork?.blockExplorers?.default?.url;\n    const txHash = result.data?.transactionHash || 'pending';\n    const explorerUrl = `${explorer}/tx/${txHash}`;\n\n    return {\n      success: true,\n      txHash: txHash,\n      blockNumber: result.data?.blockNumber || 0,\n      gasUsed: result.data?.gasUsed || 'N/A',\n      gasCost: result.data?.gasCost || 'N/A',\n      explorerUrl: explorerUrl,\n      receipt: {\n        status: 'success',\n        transactionHash: txHash,\n        blockNumber: BigInt(result.data?.blockNumber || 0),\n        gasUsed: BigInt(result.data?.gasUsed || 0),\n      },\n      sponsorDetails: {\n        sponsorAddress: result.data?.sponsorAddress || 'Unknown',\n        chainName: result.data?.executionDetails?.chainName,\n      },\n    };\n  } catch (error) {\n    console.error('❌ Gas sponsorship request failed:', error);\n    const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n    throw new Error(`Gas sponsorship failed: ${errorMessage}`);\n  }\n};\n","import type { Address, Account, Hex } from 'viem';\n// import { parseUnits } from 'viem';\nimport type { SupportedChain } from '../types/supported-chains';\nimport type {\n  EnsData,\n  RegisterRequest,\n  AccountConfig,\n  SignedAccountConfig,\n} from '../types/account-types';\nimport { publicClintByChainId } from './chains-constants';\nimport { generateInitialKeysOnClient } from './stealth-address';\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { SERVER_URL_ENS } from './constants';\nimport { generateModulesForRegistration, type ModuleUserInput } from './module-generator';\n\nexport const signAccountConfig = async (config: AccountConfig): Promise<SignedAccountConfig> => {\n  const configMessage = {\n    chainId: config.chainId,\n    ens: config.ens,\n    modules: config.modules,\n    defaultToken: config.defaultToken,\n    needPrivacy: config.needPrivacy ?? false,\n    eigenAiEnabled: config.eigenAiEnabled ?? false,\n  };\n\n  const messageToSign = JSON.stringify(configMessage);\n\n  const signature = await config.walletClient.signMessage({\n    account: config.walletClient.account!,\n    message: messageToSign,\n  });\n\n  // For configHash, we'll use a simple hash of the message\n  const configHash = `0x${Buffer.from(messageToSign).toString('hex')}` as `0x${string}`;\n\n  return {\n    ...config,\n    signature,\n    configHash,\n  };\n};\n\nexport const getApiKey = async (\n  config: AccountConfig | SignedAccountConfig,\n  {\n    agentDetails,\n    moduleUserInputs,\n  }: {\n    agentDetails: {\n      email: string;\n      website: string;\n      description: string;\n      twitter: string;\n      github: string;\n      telegram: string;\n      discord: string;\n    };\n    moduleUserInputs?: ModuleUserInput[];\n  },\n) => {\n  // const isSufficentBalance = await checkBalanceGreaterThan(config, parseUnits('0.001', 6));\n  // if (!isSufficentBalance) {\n  //   throw new Error('Insufficient balance');\n  // }\n\n  const signedConfig = 'signature' in config ? config : await signAccountConfig(config);\n\n  let stealthKeys: string[] = [];\n  let spendingPublicKey: string | undefined;\n  let viewingPrivateKey: string | undefined;\n\n  //if privacy is enabled, generate stealth keys\n  if (config.needPrivacy) {\n    const msgToSign = 'CREATE_ACCOUNT';\n\n    const keyResult = await generateInitialKeysOnClient({\n      walletClient: config.walletClient || signedConfig.walletClient,\n      chainId: config.chainId || signedConfig.chainId,\n      uniqueNonces: [1],\n      msgToSign,\n    });\n\n    stealthKeys = keyResult.spendingKeys;\n    const spendingPrivateKey = stealthKeys[0];\n    const spendingPrivateKeyAccount = privateKeyToAccount(spendingPrivateKey as `0x${string}`);\n\n    spendingPublicKey = spendingPrivateKeyAccount.publicKey;\n    viewingPrivateKey = keyResult.viewingPrivateKey;\n    console.log('spendingPublicKey', spendingPublicKey);\n  }\n\n  // Generate modules for registration if provided\n  let generatedModules: Array<{ address: string; chainId: string; data: string }> = [];\n  if (moduleUserInputs && moduleUserInputs.length > 0) {\n    try {\n      console.log('Generating modules for registration...');\n      const moduleResult = await generateModulesForRegistration(moduleUserInputs);\n      generatedModules = moduleResult.modules;\n\n      if (moduleResult.errors.length > 0) {\n        console.warn('Module generation warnings:', moduleResult.errors);\n      }\n\n      console.log(`Successfully generated ${generatedModules.length} modules for registration`);\n    } catch (error) {\n      console.error('Error generating modules:', error);\n      throw new Error(\n        `Failed to generate modules: ${error instanceof Error ? error.message : 'Unknown error'}`,\n      );\n    }\n  }\n\n  //ens sign\n  const nameData: EnsData = {\n    ensUsername: config.ens,\n    eoaAddress: config.walletClient.account?.address as Address,\n    addresses: {\n      '60': config.walletClient.account?.address as Address, // Ethereum address (default for all chains)\n    },\n    texts: {\n      url: agentDetails.website || '',\n      avatar: agentDetails.website + '/avatar' || '',\n      email: agentDetails.email || '',\n      website: agentDetails.website || '',\n      description: agentDetails.description || '',\n      encryptionPublicKey: (spendingPublicKey as Hex) || '0x',\n      'com.twitter': agentDetails.twitter || '',\n      'com.github': agentDetails.github || '',\n      'com.discord': agentDetails.discord || '',\n    },\n    contenthash: '0x', // Empty content hash\n  };\n\n  const expiration = Date.now() + 365 * 24 * 60 * 60 * 1000;\n\n  // Create the complete registration data that matches what the server expects\n  const registrationData = {\n    ensData: nameData,\n    supportedChains: [config.chainId.toString()],\n    modules: generatedModules.length > 0 ? (generatedModules as any) : config.modules,\n    privacyEnabled: config.needPrivacy ?? false,\n    privacyData:\n      (config.needPrivacy ?? false)\n        ? {\n            spendingPublicKey: (spendingPublicKey as Hex) || '0x',\n            viewingPrivateKey: (viewingPrivateKey as Hex) || '0x',\n          }\n        : undefined,\n    eigenAiEnabled: config.eigenAiEnabled ?? false,\n  };\n\n  const messageToSign = JSON.stringify(registrationData);\n\n  const signature = await config.walletClient.signMessage({\n    message: messageToSign,\n    account: config.walletClient.account as Account,\n  });\n\n  const requestBodyPartial: Omit<RegisterRequest, 'privacyData'> & {\n    privacyData?: RegisterRequest['privacyData'];\n  } = {\n    ensData: nameData,\n    supportedChains: [config.chainId.toString()] as unknown as RegisterRequest['supportedChains'],\n    modules: generatedModules.length > 0 ? (generatedModules as any) : config.modules,\n    privacyEnabled: config.needPrivacy ?? false,\n    eigenAiEnabled: config.eigenAiEnabled ?? false,\n    signature: {\n      hash: signature,\n      message: messageToSign,\n      expiration: expiration,\n      signature: signature,\n    },\n  };\n\n  if (config.needPrivacy) {\n    requestBodyPartial.privacyData = {\n      spendingPublicKey: (spendingPublicKey as Hex) || '0x',\n      viewingPrivateKey: (viewingPrivateKey as Hex) || '0x',\n    };\n  }\n\n  const requestBody = requestBodyPartial as RegisterRequest;\n\n  console.log('Request body being sent:', JSON.stringify(requestBody, null, 2));\n\n  const response = await fetch(`${SERVER_URL_ENS}/set`, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n    },\n    body: JSON.stringify(requestBody),\n  });\n\n  const result = await response.json();\n\n  console.log('result', result);\n\n  // Log detailed validation errors\n  if (result.details && Array.isArray(result.details)) {\n    console.log('Validation error details:');\n    result.details.forEach((detail: unknown, index: number) => {\n      const d = detail as {\n        code: string;\n        expected?: unknown;\n        received?: unknown;\n        path?: unknown;\n        message: string;\n      };\n      console.log(`Error ${index + 1}:`, {\n        code: d.code,\n        expected: d.expected,\n        received: d.received,\n        path: d.path,\n        message: d.message,\n      });\n    });\n  }\n\n  return {\n    apiKey: result.apiKey,\n    ensCall: result,\n\n    signature: signedConfig.signature,\n    configHash: signedConfig.configHash,\n  };\n};\n\nexport const getRecipientAccountData = async ({\n  ens,\n  chainId,\n}: {\n  ens: string;\n  chainId: SupportedChain;\n}) => {\n  const address = await publicClintByChainId(chainId).getEnsAddress({\n    name: ens,\n  });\n\n  return {\n    address,\n  };\n};\n\nexport const checkBalanceGreaterThan = async (config: AccountConfig, amount: bigint) => {\n  const balance = await getBalance(config);\n  return balance > amount;\n};\n\nexport const getBalance = async (config: AccountConfig) => {\n  const publicClient = publicClintByChainId(config.chainId);\n\n  const balance = await publicClient.getBalance({\n    address: config.walletClient.account?.address as Address,\n  });\n\n  return balance;\n};\n","import { SERVER_URL_ENS } from './constants';\nimport { type ModulesResponse } from '../types/account-types';\n\n/**\n * Fetches all available smart contract modules from the API\n * @returns Promise<ModulesResponse> - The modules data including deployments and supported networks\n * @throws Error if the API request fails\n */\nexport const getModules = async (): Promise<ModulesResponse> => {\n  try {\n    const response = await fetch(`${SERVER_URL_ENS}/modules`, {\n      method: 'GET',\n      headers: {\n        Accept: 'application/json',\n        'Content-Type': 'application/json',\n      },\n    });\n\n    if (!response.ok) {\n      throw new Error(`Failed to fetch modules: ${response.status} ${response.statusText}`);\n    }\n\n    const data: ModulesResponse = await response.json();\n\n    if (!data.success) {\n      throw new Error('API returned unsuccessful response');\n    }\n\n    return data;\n  } catch (error) {\n    if (error instanceof Error) {\n      throw new Error(`Error fetching modules: ${error.message}`);\n    }\n    throw new Error('Unknown error occurred while fetching modules');\n  }\n};\n","import { getModules } from './modules-api';\nimport {\n  type ModuleInfo,\n  type RegistrationModule,\n  type ModulesResponse,\n} from '../types/account-types';\n\nexport interface ModuleUserInput {\n  moduleId: string;\n  chainId: number;\n  inputs: Record<string, string | number>;\n}\n\nexport interface ModuleGenerationResult {\n  modules: RegistrationModule[];\n  errors: string[];\n}\n\n/**\n * Generates module JSON format for registration from user inputs\n * @param userModuleInputs - Array of user module inputs\n * @returns Promise<ModuleGenerationResult> - Generated modules and any errors\n */\nexport const generateModulesForRegistration = async (\n  userModuleInputs: ModuleUserInput[],\n): Promise<ModuleGenerationResult> => {\n  try {\n    // Fetch available modules from API\n    const modulesResponse: ModulesResponse = await getModules();\n\n    if (!modulesResponse.success) {\n      throw new Error('Failed to fetch modules from API');\n    }\n\n    const modules: RegistrationModule[] = [];\n    const errors: string[] = [];\n\n    for (const userInput of userModuleInputs) {\n      try {\n        const module = await generateSingleModule(userInput, modulesResponse);\n        if (module) {\n          modules.push(module);\n        }\n      } catch (error) {\n        errors.push(\n          `Module ${userInput.moduleId}: ${error instanceof Error ? error.message : 'Unknown error'}`,\n        );\n      }\n    }\n\n    return { modules, errors };\n  } catch (error) {\n    throw new Error(\n      `Failed to generate modules: ${error instanceof Error ? error.message : 'Unknown error'}`,\n    );\n  }\n};\n\n/**\n * Generates a single module from user input\n * @param userInput - User module input\n * @param modulesResponse - Available modules from API\n * @returns Module or null if not found\n */\nconst generateSingleModule = async (\n  userInput: ModuleUserInput,\n  modulesResponse: ModulesResponse,\n): Promise<RegistrationModule | null> => {\n  // Find the module by ID\n  const moduleInfo = modulesResponse.modules.find((m) => m.id === userInput.moduleId);\n\n  if (!moduleInfo) {\n    throw new Error(`Module '${userInput.moduleId}' not found`);\n  }\n\n  // Find deployment for the specified chain\n  const deployment = moduleInfo.deployments.find((d) => d.chainId === userInput.chainId);\n\n  if (!deployment) {\n    throw new Error(`Module '${userInput.moduleId}' not deployed on chain ${userInput.chainId}`);\n  }\n\n  // Validate required fields\n  const missingFields = moduleInfo.userInputs.requiredFields.filter(\n    (field) => !(field.name in userInput.inputs),\n  );\n\n  if (missingFields.length > 0) {\n    throw new Error(`Missing required fields: ${missingFields.map((f) => f.name).join(', ')}`);\n  }\n\n  // Get example request format from installation guide\n  const exampleRequest = modulesResponse.installationGuide.exampleRequests[userInput.moduleId];\n\n  if (!exampleRequest) {\n    throw new Error(`No example request format found for module '${userInput.moduleId}'`);\n  }\n\n  // Generate encoded data from user inputs\n  // Note: This is a simplified version. In production, you would need to:\n  // 1. Encode the user inputs according to the module's ABI\n  // 2. Use proper encoding libraries like viem's encodeFunctionData\n  const encodedData = generateEncodedData(userInput, moduleInfo, exampleRequest);\n\n  const module: RegistrationModule = {\n    address: deployment.address,\n    chainId: userInput.chainId.toString(),\n    data: encodedData,\n  };\n\n  return module;\n};\n\n/**\n * Generates encoded data from user inputs\n * This is a simplified implementation. In production, you would use proper ABI encoding\n * @param userInput - User module input\n * @param moduleInfo - Module information\n * @param exampleRequest - Example request format\n * @returns Encoded hex string\n */\nconst generateEncodedData = (\n  userInput: ModuleUserInput,\n  moduleInfo: ModuleInfo,\n  exampleRequest: { registerRequestFormat: { data: string } },\n): string => {\n  // For now, we'll use a simplified approach that maps user inputs to the example format\n  // In production, this should use proper ABI encoding based on the module's contract\n\n  const requiredFields = moduleInfo.userInputs.requiredFields;\n\n  // Create a mapping of field names to their values\n  const fieldValues: Record<string, string | number> = {};\n\n  for (const field of requiredFields) {\n    if (field.name in userInput.inputs) {\n      fieldValues[field.name] = userInput.inputs[field.name];\n    }\n  }\n\n  // For demonstration, we'll return the example data\n  // In production, you would:\n  // 1. Get the module's ABI from the API or a registry\n  // 2. Use encodeFunctionData to encode the user inputs\n  // 3. Return the properly encoded hex string\n\n  console.warn(\n    `⚠️  Using example encoded data for module ${userInput.moduleId}. In production, implement proper ABI encoding.`,\n  );\n  console.warn(`User inputs:`, fieldValues);\n\n  return exampleRequest.registerRequestFormat.data;\n};\n\n/**\n * Gets available modules with their required fields for easy reference\n * @returns Promise<ModuleInfo[]> - Available modules with their requirements\n */\nexport const getAvailableModules = async (): Promise<ModuleInfo[]> => {\n  const modulesResponse = await getModules();\n\n  if (!modulesResponse.success) {\n    throw new Error('Failed to fetch modules from API');\n  }\n\n  return modulesResponse.modules;\n};\n\n/**\n * Validates user input against module requirements\n * @param moduleId - Module ID to validate against\n * @param userInputs - User inputs to validate\n * @returns Promise<{valid: boolean, errors: string[]}> - Validation result\n */\nexport const validateModuleInputs = async (\n  moduleId: string,\n  userInputs: Record<string, string | number>,\n): Promise<{ valid: boolean; errors: string[] }> => {\n  try {\n    const modules = await getAvailableModules();\n    const module = modules.find((m) => m.id === moduleId);\n\n    if (!module) {\n      return { valid: false, errors: [`Module '${moduleId}' not found`] };\n    }\n\n    const errors: string[] = [];\n\n    // Check required fields\n    for (const requiredField of module.userInputs.requiredFields) {\n      if (!(requiredField.name in userInputs)) {\n        errors.push(`Missing required field: ${requiredField.name}`);\n      }\n    }\n\n    // Check if chainId is supported\n    const supportedChainIds = module.deployments.map((d) => d.chainId);\n    if (userInputs.chainId && !supportedChainIds.includes(Number(userInputs.chainId))) {\n      errors.push(\n        `Chain ID ${userInputs.chainId} not supported. Supported chains: ${supportedChainIds.join(', ')}`,\n      );\n    }\n\n    return { valid: errors.length === 0, errors };\n  } catch (error) {\n    return { valid: false, errors: [error instanceof Error ? error.message : 'Unknown error'] };\n  }\n};\n","import axios from 'axios';\nimport { BACKEND_URL } from './constants';\n\nexport interface PaymentStatusData {\n  paymentId: string;\n  stealthAddress: string;\n  status: 'listening' | 'completed' | 'failed' | 'expired';\n  chainId: number;\n  tokenAddress: string;\n  tokenAmount: string;\n  isActive: boolean;\n  expiresAt: string;\n  completedAt: string | null;\n  transactionHash: string | null;\n  fromAddress: string | null;\n  actualAmount: string | null;\n  createdAt: string;\n  eventListener?: {\n    listenerId: string;\n    isActive: boolean;\n    startTime: string;\n    timeRemaining: number;\n    timeoutMinutes: number;\n  };\n}\n\nexport interface PaymentStatus {\n  success: boolean;\n  timestamp: string;\n  data: PaymentStatusData;\n  message: string;\n}\n\nexport interface PollingOptions {\n  interval?: number; // milliseconds, default 2000\n  maxAttempts?: number; // default 30 (1 minute with 2s interval)\n  onStatusUpdate?: (status: PaymentStatus) => void;\n  onComplete?: (status: PaymentStatus) => void;\n  onError?: (error: Error) => void;\n}\n\nexport const checkPaymentStatus = async (paymentId: string): Promise<PaymentStatus> => {\n  try {\n    const response = await axios.get(`${BACKEND_URL}/api/user/payment/${paymentId}/status`, {\n      headers: {\n        'Content-Type': 'application/json',\n      },\n    });\n\n    const data = response.data;\n    console.log('📊 Payment Status:', data);\n\n    if (data.success && data.data) {\n      return data as PaymentStatus;\n    } else {\n      return {\n        success: false,\n        timestamp: new Date().toISOString(),\n        data: {} as PaymentStatusData,\n        message: data.message || 'Failed to fetch payment status',\n      };\n    }\n  } catch (error) {\n    console.error('❌ Error checking payment status:', error);\n    return {\n      success: false,\n      timestamp: new Date().toISOString(),\n      data: {} as PaymentStatusData,\n      message: error instanceof Error ? error.message : 'Unknown error occurred',\n    };\n  }\n};\n\nexport const pollPaymentStatus = async (\n  paymentId: string,\n  options: PollingOptions = {},\n): Promise<PaymentStatus> => {\n  const { interval = 2000, maxAttempts = 30, onStatusUpdate, onComplete, onError } = options;\n\n  let attempts = 0;\n  let pollingInterval: NodeJS.Timeout | null = null;\n\n  return new Promise((resolve, reject) => {\n    const poll = async () => {\n      attempts++;\n      console.log(`🔄 Polling attempt ${attempts}/${maxAttempts} for payment ${paymentId}`);\n\n      try {\n        const status = await checkPaymentStatus(paymentId);\n\n        // Call status update callback\n        if (onStatusUpdate) {\n          onStatusUpdate(status);\n        }\n\n        // Check if payment is completed, failed, or expired\n        if (status.success && status.data) {\n          const paymentStatus = status.data.status;\n\n          if (\n            paymentStatus === 'completed' ||\n            paymentStatus === 'failed' ||\n            paymentStatus === 'expired'\n          ) {\n            console.log(`🛑 Payment ${paymentId} status: ${paymentStatus}`);\n\n            // Clear interval\n            if (pollingInterval) {\n              clearInterval(pollingInterval);\n            }\n\n            // Call completion callback\n            if (onComplete) {\n              onComplete(status);\n            }\n\n            resolve(status);\n            return;\n          }\n        }\n\n        // Check if we've exceeded max attempts\n        if (attempts >= maxAttempts) {\n          console.log(`⏰ Polling timeout reached for payment ${paymentId}`);\n\n          if (pollingInterval) {\n            clearInterval(pollingInterval);\n          }\n\n          const timeoutError = new Error(\n            `Payment status polling timeout after ${maxAttempts} attempts`,\n          );\n          if (onError) {\n            onError(timeoutError);\n          }\n          reject(timeoutError);\n          return;\n        }\n      } catch (error) {\n        console.error(`❌ Error during polling attempt ${attempts}:`, error);\n\n        if (onError) {\n          onError(error instanceof Error ? error : new Error('Unknown polling error'));\n        }\n\n        // Continue polling unless we've exceeded max attempts\n        if (attempts >= maxAttempts) {\n          if (pollingInterval) {\n            clearInterval(pollingInterval);\n          }\n          reject(error);\n        }\n      }\n    };\n\n    // Start polling\n    poll(); // Initial call\n    pollingInterval = setInterval(poll, interval);\n  });\n};\n","import type { Address, Account, Hex } from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { generateInitialKeysOnClient } from './stealth-address';\nimport type { AccountConfig, EnsData, RegisterRequest } from '../types/account-types';\n\nexport type AgentDetails = {\n  email: string;\n  website: string;\n  description: string;\n  twitter: string;\n  github: string;\n  telegram: string;\n  discord: string;\n};\n\nexport type GeneratedPrivacyKeys = {\n  spendingPrivateKey: Hex;\n  spendingPublicKey: Hex;\n  viewingPrivateKey: Hex;\n};\n\nexport const generatePrivacyKeys = async (config: AccountConfig): Promise<GeneratedPrivacyKeys> => {\n  const msgToSign = 'CREATE_ACCOUNT';\n  const keyResult = await generateInitialKeysOnClient({\n    walletClient: config.walletClient,\n    chainId: config.chainId,\n    uniqueNonces: [1],\n    msgToSign,\n  });\n\n  const spendingPrivateKey = keyResult.spendingKeys[0] as Hex;\n  const spendingAccount = privateKeyToAccount(spendingPrivateKey as `0x${string}`);\n  const spendingPublicKey = spendingAccount.publicKey as Hex;\n\n  return {\n    spendingPrivateKey,\n    spendingPublicKey,\n    viewingPrivateKey: keyResult.viewingPrivateKey as Hex,\n  };\n};\n\nexport const buildEnsData = (\n  config: AccountConfig,\n  agentDetails: AgentDetails,\n  spendingPublicKey?: Hex,\n): EnsData => {\n  return {\n    ensUsername: config.ens,\n    eoaAddress: config.walletClient.account?.address as Address,\n    addresses: {\n      '60': config.walletClient.account?.address as Address,\n    },\n    texts: {\n      url: agentDetails.website || '',\n      avatar: `${agentDetails.website || ''}/avatar`,\n      email: agentDetails.email || '',\n      website: agentDetails.website || '',\n      description: agentDetails.description || '',\n      encryptionPublicKey: (spendingPublicKey as string) || '0x',\n      'com.twitter': agentDetails.twitter || '',\n      'com.github': agentDetails.github || '',\n      'com.discord': agentDetails.discord || '',\n    },\n    contenthash: '0x',\n  };\n};\n\nexport const buildRegistrationData = (\n  config: AccountConfig,\n  ensData: EnsData,\n  privacyKeys?: GeneratedPrivacyKeys,\n) => {\n  return {\n    ensData,\n    supportedChains: [config.chainId.toString()],\n    modules: config.modules,\n    privacyEnabled: config.needPrivacy ?? false,\n    privacyData:\n      (config.needPrivacy ?? false)\n        ? {\n            spendingPublicKey: (privacyKeys?.spendingPublicKey as Hex) || '0x',\n            viewingPrivateKey: (privacyKeys?.viewingPrivateKey as Hex) || '0x',\n          }\n        : undefined,\n    eigenAiEnabled: config.eigenAiEnabled ?? false,\n  };\n};\n\nexport const signRegistrationData = async (\n  config: AccountConfig,\n  registrationData: ReturnType<typeof buildRegistrationData>,\n) => {\n  const messageToSign = JSON.stringify(registrationData);\n  const signature = await config.walletClient.signMessage({\n    account: config.walletClient.account as Account,\n    message: messageToSign,\n  });\n  return { messageToSign, signature } as const;\n};\n\nexport const prepareRegisterRequest = async (\n  config: AccountConfig,\n  agentDetails: AgentDetails,\n): Promise<RegisterRequest> => {\n  const privacyKeys = config.needPrivacy ? await generatePrivacyKeys(config) : undefined;\n  const ensData = buildEnsData(config, agentDetails, privacyKeys?.spendingPublicKey);\n  const registrationData = buildRegistrationData(config, ensData, privacyKeys);\n  const { messageToSign, signature } = await signRegistrationData(config, registrationData);\n\n  const expiration = Date.now() + 365 * 24 * 60 * 60 * 1000;\n\n  const req: Omit<RegisterRequest, 'privacyData'> & {\n    privacyData?: RegisterRequest['privacyData'];\n  } = {\n    ensData,\n    supportedChains:\n      registrationData.supportedChains as unknown as RegisterRequest['supportedChains'],\n    modules: registrationData.modules,\n    privacyEnabled: registrationData.privacyEnabled,\n    eigenAiEnabled: registrationData.eigenAiEnabled,\n    signature: {\n      hash: signature as Hex,\n      message: messageToSign,\n      expiration,\n      signature: signature as Hex,\n    },\n  };\n  if (registrationData.privacyData !== undefined) {\n    req.privacyData = registrationData.privacyData;\n  }\n\n  return req as RegisterRequest;\n};\n\nexport const prettyPrintRegisterRequest = (request: RegisterRequest): string => {\n  return JSON.stringify(request, null, 2);\n};\n","import {\n  type RequiredStateData,\n  type ConfigField,\n  type GetRequiredStateInput,\n} from './types/module-types';\nimport { publicClintByChainId } from './utils/chains-constants';\nimport { getModuleAddress, MODULE_DATA, AAVE_POOL_ADDRESSES } from './utils/constants';\n\nexport const getRequiredState = async ({\n  sourceChainId,\n  moduleName,\n  publicClient,\n}: GetRequiredStateInput): Promise<RequiredStateData> => {\n  try {\n    // Handle fixed fields for INVEST_IN_VERIFIABLE_AGENTS and INVEST_IN_AAVE modules\n    if (moduleName === 'INVEST_IN_VERIFIABLE_AGENTS' || moduleName === 'INVEST_IN_AAVE') {\n      // Get token address based on chain ID\n      const getTokenAddress = (chainId: number) => {\n        switch (chainId) {\n          case 84532: // Base Sepolia\n            return '0x036cbd53842c5426634e7929541ec2318f3dcf7e';\n          case 421614: // Arbitrum Sepolia\n            return '0x75faf114eafb1bdbe2f0316df893fd58ce46aa4d';\n          default:\n            return '0x0000000000000000000000000000000000000000'; // Default placeholder\n        }\n      };\n\n      const tokenAddress = getTokenAddress(sourceChainId);\n\n      const fixedFields: ConfigField[] = [\n        { type: 'uint256', name: 'chainId' },\n        { type: 'address', name: 'tokenAddress' },\n      ];\n\n      const fixedConfigTemplate = {\n        chainId: sourceChainId.toString(),\n        tokenAddress: tokenAddress,\n      };\n\n      return {\n        chainId: sourceChainId.toString(),\n        moduleName: moduleName,\n        moduleAddress: getModuleAddress(moduleName, sourceChainId),\n        configInputType: 'tuple[](uint256 chainId, address tokenAddress)',\n        requiredFields: fixedFields,\n        configTemplate: fixedConfigTemplate,\n      };\n    }\n\n    const client = publicClient ?? publicClintByChainId(sourceChainId);\n\n    // Check if ABI is available and has the required function\n    const moduleConfig = MODULE_DATA[sourceChainId];\n\n    const configInputTypeData = await client.readContract({\n      address: getModuleAddress(moduleName, sourceChainId),\n      abi: moduleConfig.abi,\n      functionName: 'getConfigInputTypeData',\n    });\n\n    console.log('configInputTypeData', configInputTypeData);\n\n    // Parse the config input type to extract field names and types\n    const parseConfigInputType = (configType: string) => {\n      // Extract the tuple content from \"tuple[](field1,field2,field3)\"\n      const tupleMatch = configType.match(/tuple\\[\\]\\(([^)]+)\\)/);\n      if (!tupleMatch) {\n        return { fields: [], readableFormat: {} };\n      }\n\n      const fieldsString = tupleMatch[1];\n      const fields: ConfigField[] = fieldsString.split(',').map((field) => {\n        const parts = field.trim().split(' ');\n        return {\n          type: parts[0] as ConfigField['type'],\n          name: parts[1] || 'unknown',\n        };\n      });\n\n      // Create readable format with actual values where possible\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      const readableFormat: Record<string, any> = {};\n      fields.forEach((field) => {\n        switch (field.type) {\n          case 'uint256':\n            if (field.name === 'sourceChainId') {\n              readableFormat[field.name] = sourceChainId.toString();\n            } else {\n              readableFormat[field.name] = '0'; // Placeholder for other uint256\n            }\n            break;\n          case 'address':\n            if (field.name === 'vaultAddress') {\n              // Use the actual AAVE pool address as the vault address for all modules\n              readableFormat[field.name] = AAVE_POOL_ADDRESSES[sourceChainId];\n            } else {\n              readableFormat[field.name] = '0x0000000000000000000000000000000000000000'; // Placeholder for other addresses\n            }\n            break;\n          case 'uint24':\n            readableFormat[field.name] = '0'; // Placeholder for uint24\n            break;\n          default:\n            readableFormat[field.name] = null; // Unknown type\n        }\n      });\n\n      return { fields, readableFormat };\n    };\n\n    const { fields, readableFormat } = parseConfigInputType(configInputTypeData as string);\n\n    const requiredData: RequiredStateData = {\n      chainId: sourceChainId.toString(),\n      moduleName: moduleName,\n      moduleAddress: getModuleAddress(moduleName, sourceChainId),\n      configInputType: configInputTypeData as string,\n      requiredFields: fields,\n      configTemplate: readableFormat,\n    };\n    return requiredData;\n  } catch (error) {\n    console.error('Error fetching module data:', error);\n    throw error;\n  }\n};\n","import {\n  type OrchestrationData,\n  type CurrentState,\n  type RequiredState,\n} from '../types/orchestration-data';\nimport { type RequiredStateData } from '../types/module-types';\nimport { type Address, type Hex } from 'viem';\nimport { SERVER_URL_ENS } from './constants';\n\nexport interface OrchestrationApiResponse {\n  success: boolean;\n  error?: string;\n  data?: {\n    requestId: string;\n    sourceChainOwner: string;\n    destinationChainOwner: string;\n    sourceChainId: number;\n    destinationChainId: number;\n    sourceTokenAddress: string;\n    sourceTokenAmount: string;\n    destinationTokenAddress: string;\n    destinationTokenAmount: string;\n    accountAddressOnSourceChain: string;\n    sourceChainAccountModules: string[];\n    accountAddressOnDestinationChain: string;\n    destinationChainAccountModules: string[];\n    sourceInitData?: string;\n    sourceSalt?: string;\n    destinationInitData?: string;\n    destinationSalt?: string;\n  };\n}\n\nexport const createOrchestrationData = async (\n  currentState: CurrentState,\n  requiredState: RequiredState | RequiredStateData,\n  ownerAddress: Address,\n  apiKey: string,\n  encodedData?: Hex,\n): Promise<OrchestrationData> => {\n  try {\n    // Extract moduleAddress - it can be a direct property (RequiredStateData) or in configTemplate (RequiredState)\n    // RequiredStateData has moduleAddress as a direct property, RequiredState has it in configTemplate\n    let moduleAddress: string;\n    if ('moduleAddress' in requiredState && typeof requiredState.moduleAddress === 'string') {\n      // RequiredStateData case - moduleAddress is a direct property\n      moduleAddress = requiredState.moduleAddress;\n    } else {\n      // RequiredState case - moduleAddress might be in configTemplate\n      const configModuleAddress = requiredState.configTemplate.moduleAddress;\n      moduleAddress =\n        typeof configModuleAddress === 'string'\n          ? configModuleAddress\n          : '0x0000000000000000000000000000000000000000';\n    }\n\n    // Convert chainId to number - currentState.chainId can be string or number\n    // but API expects number for consistency\n    const sourceChainId = typeof currentState.chainId === 'string' \n      ? parseInt(currentState.chainId) \n      : currentState.chainId;\n    const destChainId = parseInt(requiredState.chainId);\n    \n    // Prepare the API request payload\n    const apiRequestPayload = {\n      currentState: [\n        {\n          chainId: sourceChainId, // Ensure it's a number\n          tokenAddress: currentState.tokenAddress,\n          amount: currentState.tokenAmount,\n        },\n      ],\n      requiredStateData: [\n        {\n          moduleAddress,\n          chainId: destChainId, // Already a number\n          encodedData: encodedData || '0x',\n        },\n      ],\n      userAddress: ownerAddress,\n      apiKey: apiKey,\n    };\n\n    console.log(\n      'Making API call to orchestration endpoint with payload:',\n      JSON.stringify(apiRequestPayload, null, 2),\n    );\n\n    // Make the API call to the orchestration endpoint\n    const response = await fetch(`${SERVER_URL_ENS}/api/v1/orchestration/create`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n      },\n      body: JSON.stringify(apiRequestPayload),\n    });\n\n    if (!response.ok) {\n      const errorText = await response.text();\n      throw new Error(`API call failed with status: ${response.status} - ${response.statusText}\\n${errorText}`);\n    }\n\n    const apiResult = (await response.json()) as OrchestrationApiResponse;\n    console.log('API Response:', JSON.stringify(apiResult, null, 2));\n\n    if (!apiResult.success || !apiResult.data) {\n      throw new Error(`Orchestration failed: ${apiResult.error || 'Unknown error'}`);\n    }\n\n    const data = apiResult.data;\n\n    // Extract token decimals from addresses (heuristic: 6 for USDC, 18 for others)\n    // In production, you'd fetch this from the token contract using ERC20 decimals() function\n    const isSourceUSDC = \n      currentState.tokenAddress.toLowerCase().includes('usdc') ||\n      currentState.tokenAddress.toLowerCase() === '0x036cbd53842c5426634e7929541ec2318f3dcf7e' ||\n      currentState.tokenAddress.toLowerCase() === '0x75faf114eafb1bdbe2f0316df893fd58ce46aa4d';\n    \n    const isDestUSDC = \n      data.destinationTokenAddress.toLowerCase().includes('usdc') ||\n      data.destinationTokenAddress.toLowerCase() === '0x036cbd53842c5426634e7929541ec2318f3dcf7e' ||\n      data.destinationTokenAddress.toLowerCase() === '0x75faf114eafb1bdbe2f0316df893fd58ce46aa4d';\n\n    const sourceTokenDecimals = isSourceUSDC ? 6 : 18;\n    const destinationTokenDecimals = isDestUSDC ? 6 : 18;\n\n    // Parse token amounts to bigint\n    // Server returns amounts as strings in smallest unit (wei-equivalent), so we just convert to bigint\n    const sourceTokenAmount = BigInt(data.sourceTokenAmount);\n    const destinationTokenAmount = BigInt(data.destinationTokenAmount);\n\n    // Create orchestration data structure from server response\n    const orchestrationData: OrchestrationData = {\n      requestId: data.requestId as Hex,\n      sourceChainOwner: data.sourceChainOwner as Address,\n      destinationChainOwner: data.destinationChainOwner as Address,\n      sourceChainId: data.sourceChainId,\n      destinationChainId: data.destinationChainId,\n      sourceTokenAddress: data.sourceTokenAddress as Address,\n      sourceTokenAmount,\n      destinationTokenAddress: data.destinationTokenAddress as Address,\n      destinationTokenAmount,\n      accountAddressOnSourceChain: data.accountAddressOnSourceChain as Address,\n      sourceChainAccountModules: data.sourceChainAccountModules as Address[],\n      accountAddressOnDestinationChain: data.accountAddressOnDestinationChain as Address,\n      destinationChainAccountModules: data.destinationChainAccountModules as Address[],\n    };\n\n    return orchestrationData;\n  } catch (error) {\n    console.error('Error creating orchestration data:', error);\n    throw error;\n  }\n};\n","import { type WalletClient, type PublicClient, type Address } from 'viem';\nimport { type OrchestrationData } from '../types/orchestration-data';\nimport { type SignedTransferAuthorization } from './eip3009';\n\nexport interface DepositResult {\n  success: boolean;\n  txHash?: string;\n  gasUsed?: string;\n  gasCost?: string;\n  explorerUrl?: string;\n  error?: string;\n}\n\nexport interface GaslessDepositResult {\n  success: boolean;\n  signedAuthorization?: SignedTransferAuthorization;\n  error?: string;\n}\n\nexport const deposit = async (\n  accountAddress: Address,\n  tokenAddress: Address,\n  tokenAmount: bigint,\n  walletClient: WalletClient,\n  publicClient: PublicClient,\n): Promise<DepositResult> => {\n  try {\n    console.log('Initiating deposit transfer...');\n    console.log('Account Address:', accountAddress);\n    console.log('Token Address:', tokenAddress);\n    console.log('Token Amount:', tokenAmount.toString());\n\n    // Check if it's a native token (ETH) or ERC20 token\n    const isNativeToken =\n      tokenAddress === '0x0000000000000000000000000000000000000000' ||\n      tokenAddress === '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';\n\n    let txHash: string;\n\n    if (isNativeToken) {\n      // Native token transfer (ETH)\n      console.log('Processing native token transfer...');\n\n      const hash = await walletClient.sendTransaction({\n        to: accountAddress,\n        value: tokenAmount,\n        account: walletClient.account!,\n        chain: walletClient.chain,\n      });\n\n      txHash = hash;\n    } else {\n      // ERC20 token transfer\n      console.log('Processing ERC20 token transfer...');\n\n      // ERC20 transfer function ABI\n      const erc20TransferAbi = [\n        {\n          inputs: [\n            { name: 'to', type: 'address' },\n            { name: 'amount', type: 'uint256' },\n          ],\n          name: 'transfer',\n          outputs: [{ name: '', type: 'bool' }],\n          stateMutability: 'nonpayable',\n          type: 'function',\n        },\n      ] as const;\n\n      const hash = await walletClient.writeContract({\n        address: tokenAddress,\n        abi: erc20TransferAbi,\n        functionName: 'transfer',\n        args: [accountAddress, tokenAmount],\n        account: walletClient.account!,\n        chain: walletClient.chain,\n      });\n\n      txHash = hash;\n    }\n\n    console.log('Transfer transaction hash:', txHash);\n\n    // Wait for transaction confirmation\n    const receipt = await publicClient.waitForTransactionReceipt({\n      hash: txHash as `0x${string}`,\n    });\n\n    console.log('Transaction confirmed:', {\n      blockNumber: receipt.blockNumber,\n      gasUsed: receipt.gasUsed.toString(),\n    });\n\n    // Get chain info for explorer URL\n    const chain = walletClient.chain;\n    const explorerUrl = chain?.blockExplorers?.default?.url\n      ? `${chain.blockExplorers.default.url}/tx/${txHash}`\n      : undefined;\n\n    const result: DepositResult = {\n      success: true,\n      txHash,\n      gasUsed: receipt.gasUsed.toString(),\n      gasCost: '0', // Would need gas price to calculate actual cost\n      explorerUrl,\n    };\n\n    console.log('✅ Deposit completed successfully:', result);\n    return result;\n  } catch (error) {\n    console.error('❌ Deposit failed:', error);\n\n    const result: DepositResult = {\n      success: false,\n      error: error instanceof Error ? error.message : 'Unknown error occurred',\n    };\n\n    return result;\n  }\n};\n\n// Convenience function that takes orchestration data\nexport const depositFromOrchestrationData = async (\n  od: OrchestrationData,\n  walletClient: WalletClient,\n  publicClient: PublicClient,\n): Promise<DepositResult> => {\n  return deposit(\n    od.accountAddressOnSourceChain,\n    od.sourceTokenAddress,\n    od.sourceTokenAmount,\n    walletClient,\n    publicClient,\n  );\n};\n\n/**\n * Gasless deposit using EIP-3009 transferWithAuthorization\n * Signs an authorization for the server to move tokens from the user's wallet to the smart account (gasless).\n *\n * Flow:\n * 1. User signs EIP-3009 authorization with their wallet (OFF-CHAIN - NO GAS!)\n * 2. User sends signed authorization to server\n * 3. Server executes transferWithAuthorization in Multicall3 batch (server pays gas)\n *\n * @param fromAddress - User's wallet address that owns the tokens\n * @param smartAccountAddress - Smart account address to receive tokens\n * @param tokenAddress - Token contract address (must support EIP-3009)\n * @param tokenAmount - Amount of tokens to transfer\n * @param walletClient - User's wallet client (signs authorization, NO ETH needed for signing!)\n * @param publicClient - Public client for reading token info\n * @param validityWindow - Validity window in seconds (default: 1 hour)\n */\nexport const depositGasless = async (\n  fromAddress: Address,\n  smartAccountAddress: Address,\n  tokenAddress: Address,\n  tokenAmount: bigint,\n  walletClient: WalletClient,\n  publicClient: PublicClient,\n  validityWindow: number = 3600,\n): Promise<GaslessDepositResult> => {\n  try {\n    console.log('Initiating gasless deposit with EIP-3009...');\n    console.log('From Address:', fromAddress);\n    console.log('Smart Account Address:', smartAccountAddress);\n    console.log('Token Address:', tokenAddress);\n    console.log('Token Amount:', tokenAmount.toString());\n\n    // Sign EIP-3009 authorization (OFF-CHAIN - NO GAS!)\n    console.log('Signing EIP-3009 authorization (gasless)...');\n\n    const { signTransferWithAuthorization } = await import('./eip3009');\n\n    const signedAuthorization = await signTransferWithAuthorization(\n      fromAddress, // from - user's wallet\n      smartAccountAddress, // to - smart account\n      tokenAmount, // value\n      tokenAddress, // token\n      walletClient.chain!.id, // chainId\n      walletClient, // signer (NO ETH needed for signing!)\n      publicClient, // for reading token info\n      validityWindow,\n    );\n\n    console.log('✅ EIP-3009 authorization signed (gasless)!');\n    console.log('   From:', signedAuthorization.from);\n    console.log('   To:', signedAuthorization.to);\n    console.log('   Value:', signedAuthorization.value.toString());\n    console.log('   Nonce:', signedAuthorization.nonce);\n\n    const result: GaslessDepositResult = {\n      success: true,\n      signedAuthorization,\n    };\n\n    console.log('✅ Gasless deposit prepared successfully');\n    return result;\n  } catch (error) {\n    console.error('❌ Gasless deposit failed:', error);\n\n    const result: GaslessDepositResult = {\n      success: false,\n      error: error instanceof Error ? error.message : 'Unknown error occurred',\n    };\n\n    return result;\n  }\n};\n\n/**\n * Convenience function for gasless deposit that takes orchestration data\n */\nexport const depositGaslessFromOrchestrationData = async (\n  od: OrchestrationData,\n  fromAddress: Address,\n  walletClient: WalletClient,\n  publicClient: PublicClient,\n  validityWindow: number = 3600,\n): Promise<GaslessDepositResult> => {\n  return depositGasless(\n    fromAddress,\n    od.accountAddressOnSourceChain,\n    od.sourceTokenAddress,\n    od.sourceTokenAmount,\n    walletClient,\n    publicClient,\n    validityWindow,\n  );\n};\n","import { type Hex, type Address } from 'viem';\nimport { SERVER_URL_ENS } from './constants';\n\nexport enum TransferType {\n  NORMAL = 0,\n  TRANSFER_WITH_AUTHORIZATION = 1,\n}\n\nexport interface SignedTransferAuthorizationData {\n  from: Address;\n  to: Address;\n  value: string; // BigInt as string for JSON\n  validAfter: string; // BigInt as string for JSON\n  validBefore: string; // BigInt as string for JSON\n  nonce: Hex;\n  v: number;\n  r: Hex;\n  s: Hex;\n}\n\nexport interface NotifyDepositParams {\n  requestId: Hex;\n  transactionHash: Hex;\n  blockNumber: string | bigint;\n  transferType?: TransferType;\n  signedData?: SignedTransferAuthorizationData;\n}\n\nexport interface NotifyDepositResponse {\n  success: boolean;\n  error?: string;\n  message?: string;\n}\n\nexport interface OrchestrationStatus {\n  requestId: Hex;\n  status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'FAILED';\n  created_at?: string;\n  updated_at?: string;\n  error_message?: string;\n  sourceChainId?: number;\n  destinationChainId?: number;\n}\n\nexport interface OrchestrationStatusResponse {\n  success: boolean;\n  error?: string;\n  data?: OrchestrationStatus;\n}\n\n/**\n * Notify the server about a deposit to trigger orchestration\n */\nexport const notifyDeposit = async (\n  params: NotifyDepositParams,\n): Promise<NotifyDepositResponse> => {\n  try {\n    const payload: any = {\n      requestId: params.requestId,\n      transactionHash: params.transactionHash,\n      blockNumber: typeof params.blockNumber === 'bigint'\n        ? params.blockNumber.toString()\n        : params.blockNumber,\n    };\n\n    // Add optional fields if present\n    if (params.transferType !== undefined) {\n      payload.transferType = params.transferType;\n    }\n\n    if (params.signedData) {\n      payload.signedData = params.signedData;\n    }\n\n    console.log('Notifying server of deposit:', payload);\n\n    const response = await fetch(`${SERVER_URL_ENS}/api/v1/notifications/deposit`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n      },\n      body: JSON.stringify(payload),\n    });\n\n    if (!response.ok) {\n      const errorText = await response.text();\n      throw new Error(`Failed to notify server: ${response.status} - ${response.statusText}\\n${errorText}`);\n    }\n\n    const result = (await response.json()) as NotifyDepositResponse;\n    return result;\n  } catch (error) {\n    console.error('Error notifying deposit:', error);\n    throw error;\n  }\n};\n\n/**\n * Get the status of an orchestration request\n */\nexport const getOrchestrationStatus = async (\n  requestId: Hex,\n): Promise<OrchestrationStatus> => {\n  try {\n    console.log(`Checking orchestration status for requestId: ${requestId}`);\n\n    const response = await fetch(`${SERVER_URL_ENS}/api/v1/orchestration/status/${requestId}`, {\n      method: 'GET',\n      headers: {\n        'Content-Type': 'application/json',\n      },\n    });\n\n    if (!response.ok) {\n      const errorText = await response.text();\n      throw new Error(`Failed to get orchestration status: ${response.status} - ${response.statusText}\\n${errorText}`);\n    }\n\n    const result = (await response.json()) as OrchestrationStatusResponse;\n\n    if (!result.success || !result.data) {\n      throw new Error(`Failed to get orchestration status: ${result.error || 'Unknown error'}`);\n    }\n\n    return result.data;\n  } catch (error) {\n    console.error('Error getting orchestration status:', error);\n    throw error;\n  }\n};\n\n/**\n * Poll orchestration status until completion or failure\n */\nexport interface PollOrchestrationStatusOptions {\n  requestId: Hex;\n  interval?: number; // milliseconds between polls\n  maxAttempts?: number; // maximum number of polls\n  onStatusUpdate?: (status: OrchestrationStatus) => void;\n  onComplete?: (status: OrchestrationStatus) => void;\n  onError?: (error: Error) => void;\n}\n\nexport const pollOrchestrationStatus = async (\n  options: PollOrchestrationStatusOptions,\n): Promise<OrchestrationStatus> => {\n  const {\n    requestId,\n    interval = 3000,\n    maxAttempts = 20,\n    onStatusUpdate,\n    onComplete,\n    onError,\n  } = options;\n\n  let attempts = 0;\n\n  while (attempts < maxAttempts) {\n    try {\n      const status = await getOrchestrationStatus(requestId);\n\n      if (onStatusUpdate) {\n        onStatusUpdate(status);\n      }\n\n      if (status.status === 'COMPLETED') {\n        if (onComplete) {\n          onComplete(status);\n        }\n        return status;\n      }\n\n      if (status.status === 'FAILED') {\n        const error = new Error(`Orchestration failed: ${status.error_message || 'Unknown error'}`);\n        if (onError) {\n          onError(error);\n        }\n        throw error;\n      }\n\n      // Wait before next poll\n      await new Promise((resolve) => setTimeout(resolve, interval));\n      attempts++;\n    } catch (error) {\n      if (error instanceof Error && error.message.includes('Orchestration failed')) {\n        throw error;\n      }\n      if (onError) {\n        onError(error instanceof Error ? error : new Error('Unknown error'));\n      }\n      attempts++;\n    }\n  }\n\n  throw new Error(`Orchestration status polling timed out after ${maxAttempts} attempts`);\n};\n\n/**\n * Helper function to notify deposit with EIP-3009 signed authorization\n */\nexport const notifyDepositGasless = async (\n  requestId: Hex,\n  transactionHash: Hex,\n  blockNumber: string | bigint,\n  signedAuthorization: {\n    from: Address;\n    to: Address;\n    value: bigint;\n    validAfter: bigint;\n    validBefore: bigint;\n    nonce: Hex;\n    v: number;\n    r: Hex;\n    s: Hex;\n  },\n): Promise<NotifyDepositResponse> => {\n  return notifyDeposit({\n    requestId,\n    transactionHash,\n    blockNumber,\n    transferType: TransferType.TRANSFER_WITH_AUTHORIZATION,\n    signedData: {\n      from: signedAuthorization.from,\n      to: signedAuthorization.to,\n      value: signedAuthorization.value.toString(),\n      validAfter: signedAuthorization.validAfter.toString(),\n      validBefore: signedAuthorization.validBefore.toString(),\n      nonce: signedAuthorization.nonce,\n      v: signedAuthorization.v,\n      r: signedAuthorization.r,\n      s: signedAuthorization.s,\n    },\n  });\n};\n\n","import type { WalletClient, PublicClient } from 'viem';\nimport type { OrchestrationData } from '../types/orchestration-data';\nimport { depositFromOrchestrationData, type DepositResult } from './deposit';\n\n/**\n * Transfer ERC20 tokens to the orchestration source account\n * This is a convenience wrapper around depositFromOrchestrationData\n */\nexport const transferToOrchestrationAccount = async (\n  orchestrationData: OrchestrationData,\n  walletClient: WalletClient,\n  publicClient: PublicClient,\n): Promise<DepositResult> => {\n  return depositFromOrchestrationData(orchestrationData, walletClient, publicClient);\n};\n\n","import { encodeAbiParameters, keccak256, type Hex, type Address } from 'viem';\n\n/**\n * AutoEarn module configuration input\n */\nexport interface AutoEarnConfig {\n  chainId: bigint;\n  token: Address;\n  vault: Address;\n}\n\n/**\n * Encodes AutoEarn module configuration data\n * \n * The AutoEarn module expects a config hash encoded as uint256.\n * The encoding process:\n * 1. Encode the config data as a tuple array\n * 2. Calculate keccak256 hash of the encoded data\n * 3. Encode the hash as uint256\n * \n * @param configs - Array of AutoEarn configurations (typically one config per chain)\n * @returns Encoded hex string ready for use in orchestration\n * \n * @example\n * ```typescript\n * const encodedData = encodeAutoEarnModuleData([{\n *   chainId: BigInt(421614), // Arbitrum Sepolia\n *   token: '0x75faf114eafb1bdbe2f0316df893fd58ce46aa4d' as Address,\n *   vault: '0xBfC91D59fdAA134A4ED45f7B584cAf96D7792Eff' as Address,\n * }]);\n * \n * const orchestrationData = await createOrchestrationData(\n *   currentState,\n *   requiredState,\n *   userAddress,\n *   apiKey,\n *   encodedData\n * );\n * ```\n */\nexport const encodeAutoEarnModuleData = (configs: AutoEarnConfig[]): Hex => {\n  // Step 1: Encode the config data as tuple array\n  const configData = encodeAbiParameters(\n    [\n      {\n        type: 'tuple[]',\n        components: [\n          { name: 'chainId', type: 'uint256' },\n          { name: 'token', type: 'address' },\n          { name: 'vault', type: 'address' },\n        ],\n      },\n    ],\n    [configs],\n  );\n\n  // Step 2: Calculate keccak256 hash\n  const configHash = keccak256(configData);\n\n  // Step 3: Encode the hash as uint256\n  // Note: BigInt correctly parses hex strings (0x...) when converting\n  const encodedData = encodeAbiParameters([{ type: 'uint256' }], [BigInt(configHash)]);\n\n  return encodedData as Hex;\n};\n\n/**\n * Helper to create AutoEarn config for a single chain\n * \n * @param chainId - The chain ID where the AutoEarn module will operate\n * @param tokenAddress - The token address to earn with (e.g., USDC)\n * @param vaultAddress - The vault/lending pool address (e.g., Aave pool)\n * @returns AutoEarnConfig ready for encoding\n * \n * @example\n * ```typescript\n * const config = createAutoEarnConfig(\n *   421614, // Arbitrum Sepolia\n *   '0x75faf114eafb1bdbe2f0316df893fd58ce46aa4d', // USDC\n *   '0xBfC91D59fdAA134A4ED45f7B584cAf96D7792Eff' // Aave pool\n * );\n * const encodedData = encodeAutoEarnModuleData([config]);\n * ```\n */\nexport const createAutoEarnConfig = (\n  chainId: number,\n  tokenAddress: Address,\n  vaultAddress: Address,\n): AutoEarnConfig => {\n  return {\n    chainId: BigInt(chainId),\n    token: tokenAddress,\n    vault: vaultAddress,\n  };\n};\n\n","import { type Address, type Hex } from 'viem';\nimport { SERVER_URL_ENS } from './constants';\n\n/**\n * Module Builder API - Server-side module abstraction\n * \n * This module provides functions to use the server-side Module Builder API\n * which handles module address lookup, ABI encoding, and validation.\n */\n\nexport interface ModuleBuilderConfig {\n  baseUrl?: string;\n  apiKey?: string;\n}\n\nexport interface AutoEarnParams {\n  chainId: number;\n  tokenAddress: Address;\n  vaultAddress?: Address;\n}\n\nexport interface AutoSwapParams {\n  chainId: number;\n  defaultTokenAddress: Address;\n}\n\nexport interface AutoBridgeParams {\n  chainId: number; // Source chain\n  sourceTokenAddress: Address;\n  destinationChainId: number;\n}\n\nexport interface BuiltModule {\n  address: Address;\n  chainId: number;\n  data: Hex;\n}\n\nexport interface BuildModuleResponse {\n  success: boolean;\n  module?: BuiltModule;\n  metadata?: {\n    name: string;\n    description: string;\n    supportedTokens?: string[];\n  };\n  error?: string;\n  details?: {\n    message: string;\n    field?: string;\n  };\n}\n\nexport interface BuildBatchResponse {\n  success: boolean;\n  modules?: BuiltModule[];\n  errors?: Array<{\n    index: number;\n    error: string;\n  }>;\n}\n\n/**\n * Build an AutoEarn module using the server-side API\n * \n * @param params - AutoEarn module parameters\n * @param config - Optional configuration (baseUrl, apiKey)\n * @returns Built module with address and encoded data\n * \n * @example\n * ```typescript\n * const module = await buildAutoEarnModule({\n *   chainId: 421614,\n *   tokenAddress: '0x75faf114eafb1bdbe2f0316df893fd58ce46aa4d',\n * });\n * ```\n */\nexport const buildAutoEarnModule = async (\n  params: AutoEarnParams,\n  config: ModuleBuilderConfig = {},\n): Promise<BuiltModule> => {\n  const baseUrl = config.baseUrl || SERVER_URL_ENS;\n  \n  const response = await fetch(`${baseUrl}/api/v1/modules/build`, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n      ...(config.apiKey && { Authorization: `Bearer ${config.apiKey}` }),\n    },\n    body: JSON.stringify({\n      moduleType: 'autoEarn',\n      chainId: params.chainId,\n      params: {\n        tokenAddress: params.tokenAddress,\n        ...(params.vaultAddress && { vaultAddress: params.vaultAddress }),\n      },\n    }),\n  });\n\n  if (!response.ok) {\n    const error = (await response.json()) as { error?: string; details?: any };\n    throw new Error(error.error || `Failed to build module: ${response.status}`);\n  }\n\n  const data = (await response.json()) as BuildModuleResponse;\n  \n  if (!data.success || !data.module) {\n    throw new Error(data.error || 'Failed to build module');\n  }\n\n  return data.module;\n};\n\n/**\n * Build an AutoSwap module using the server-side API\n */\nexport const buildAutoSwapModule = async (\n  params: AutoSwapParams,\n  config: ModuleBuilderConfig = {},\n): Promise<BuiltModule> => {\n  const baseUrl = config.baseUrl || SERVER_URL_ENS;\n  \n  const response = await fetch(`${baseUrl}/api/v1/modules/build`, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n      ...(config.apiKey && { Authorization: `Bearer ${config.apiKey}` }),\n    },\n    body: JSON.stringify({\n      moduleType: 'autoSwap',\n      chainId: params.chainId,\n      params: {\n        defaultTokenAddress: params.defaultTokenAddress,\n      },\n    }),\n  });\n\n  if (!response.ok) {\n    const error = (await response.json()) as { error?: string; details?: any };\n    throw new Error(error.error || `Failed to build module: ${response.status}`);\n  }\n\n  const data = (await response.json()) as BuildModuleResponse;\n  \n  if (!data.success || !data.module) {\n    throw new Error(data.error || 'Failed to build module');\n  }\n\n  return data.module;\n};\n\n/**\n * Build an AutoBridge module using the server-side API\n */\nexport const buildAutoBridgeModule = async (\n  params: AutoBridgeParams,\n  config: ModuleBuilderConfig = {},\n): Promise<BuiltModule> => {\n  const baseUrl = config.baseUrl || SERVER_URL_ENS;\n  \n  const response = await fetch(`${baseUrl}/api/v1/modules/build`, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n      ...(config.apiKey && { Authorization: `Bearer ${config.apiKey}` }),\n    },\n    body: JSON.stringify({\n      moduleType: 'autoBridge',\n      chainId: params.chainId,\n      params: {\n        sourceTokenAddress: params.sourceTokenAddress,\n        destinationChainId: params.destinationChainId,\n      },\n    }),\n  });\n\n  if (!response.ok) {\n    const error = (await response.json()) as { error?: string; details?: any };\n    throw new Error(error.error || `Failed to build module: ${response.status}`);\n  }\n\n  const data = (await response.json()) as BuildModuleResponse;\n  \n  if (!data.success || !data.module) {\n    throw new Error(data.error || 'Failed to build module');\n  }\n\n  return data.module;\n};\n\n/**\n * Build multiple modules in one batch request\n */\nexport const buildModulesBatch = async (\n  modules: Array<{\n    moduleType: 'autoEarn' | 'autoSwap' | 'autoBridge';\n    chainId: number;\n    params: Record<string, any>;\n  }>,\n  config: ModuleBuilderConfig = {},\n): Promise<BuiltModule[]> => {\n  const baseUrl = config.baseUrl || SERVER_URL_ENS;\n  \n  const response = await fetch(`${baseUrl}/api/v1/modules/build-batch`, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n      ...(config.apiKey && { Authorization: `Bearer ${config.apiKey}` }),\n    },\n    body: JSON.stringify({ modules }),\n  });\n\n  if (!response.ok) {\n    const error = (await response.json()) as { error?: string; details?: any };\n    throw new Error(error.error || `Failed to build modules: ${response.status}`);\n  }\n\n  const data = (await response.json()) as BuildBatchResponse;\n  \n  if (!data.success || !data.modules) {\n    throw new Error('Failed to build modules');\n  }\n\n  return data.modules;\n};\n\n/**\n * Validate a module configuration\n */\nexport const validateModule = async (\n  module: BuiltModule,\n  config: ModuleBuilderConfig = {},\n): Promise<{\n  valid: boolean;\n  moduleType: string;\n  decoded?: any;\n  errors?: string[];\n}> => {\n  const baseUrl = config.baseUrl || SERVER_URL_ENS;\n  \n  const response = await fetch(`${baseUrl}/api/v1/modules/validate`, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n      ...(config.apiKey && { Authorization: `Bearer ${config.apiKey}` }),\n    },\n    body: JSON.stringify({ module }),\n  });\n\n  if (!response.ok) {\n    throw new Error('Failed to validate module');\n  }\n\n  return response.json();\n};\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAuCa,mCAcP,gBAaO,eAWA,kBAwBA,2BA8CA,oCA8BA;AAjLb;AAAA;AAAA;AAuCO,IAAM,oCAAoC;AAAA,MAC/C,2BAA2B;AAAA,QACzB,EAAE,MAAM,QAAQ,MAAM,UAAU;AAAA,QAChC,EAAE,MAAM,MAAM,MAAM,UAAU;AAAA,QAC9B,EAAE,MAAM,SAAS,MAAM,UAAU;AAAA,QACjC,EAAE,MAAM,cAAc,MAAM,UAAU;AAAA,QACtC,EAAE,MAAM,eAAe,MAAM,UAAU;AAAA,QACvC,EAAE,MAAM,SAAS,MAAM,UAAU;AAAA,MACnC;AAAA,IACF;AAKA,IAAM,iBAAiB;AAAA,MACrB;AAAA,QACE,QAAQ,CAAC;AAAA,QACT,MAAM;AAAA,QACN,SAAS,CAAC,EAAE,MAAM,IAAI,MAAM,SAAS,CAAC;AAAA,QACtC,iBAAiB;AAAA,QACjB,MAAM;AAAA,MACR;AAAA,IACF;AAKO,IAAM,gBAAgB,MAAW;AACtC,YAAM,cAAc,IAAI,WAAW,E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AO,SAAS,KAAK;AACvB;;;AlB7HO,IAAM,uBAAuB,OAAO;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AACF,MAIuC;AACrC,QAAM,QAAQ,cAAc,OAAO;AACnC,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,SAAS,OAAO,qBAAqB;AAAA,EACvD;AAEA,QAAM,UAAU,MAAM,kBAAkB,cAAwB,UAAU,OAAO;AACjF,SAAO;AACT;AAEO,IAAMC,mBAAkB,OAAO;AAAA,EACpC;AAAA,EACA;AACF,MAGkC;AAChC,SAAO,MAAM,gBAAkB,EAAE,UAAU,aAAa,CAAC;AAC3D;AAEO,IAAM,uBAAuB,OAAO;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAOoC;AAClC,QAAM,SAAS,MAAM,cAAc;AAAA,IACjC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACD,SAAO;AACT;AAEO,IAAMC,sBAAqB;AAC3B,IAAMC,qBAAoB;AAE1B,IAAM,kCAAkC,OAAO;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAQgD;AAC9C,SAAO,MAAM,0BAA0B;AAAA,IACrC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;","names":["checkPaymentStatus","getTransactions","pollPaymentStatus","import_chains","axios","import_axios","import_viem","axios","import_viem","import_accounts","Safe","import_protocol_kit","import_axios","axios","Safe","crypto","import_accounts","module","import_axios","axios","import_accounts","fields","readableFormat","signTransferWithAuthorization","TransferType","import_viem","module","getTransactions","checkPaymentStatus","pollPaymentStatus"]}