OverviewFilesCommitsIssuesDocsReleasesPeers

hyper-wallet-desktop / debug-usdt-balance.cjs

125 lines · javascript ref:
#!/usr/bin/env bare

// Debug script to test USDT balance loading
require('bare-node-runtime/global')
require('bare-node-runtime/imports')

const { initializeWDK, getTokenInfo, getBaseChain } = require('./lib/wdk-integration.cjs')
const { loadWalletMnemonic } = require('./lib/wdk-integration.cjs')
const { loadIdentity } = require('./lib/wallet-storage.cjs')
const { initializeStorage } = require('./lib/wallet-storage.cjs')
const { getCurrentAddress } = require('./lib/wallet-storage.cjs')

async function debugUSDTBalance() {
  console.log('🔍 USDT Balance Debug Script')
  console.log('=' .repeat(60))

  try {
    // 1. Load wallet mnemonic
    console.log('\n1️⃣ Loading wallet mnemonic...')
    const password = process.argv[2]
    if (!password) {
      console.error('❌ Usage: bare debug-usdt-balance.cjs <password>')
      process.exit(1)
    }

    const walletMnemonic = loadWalletMnemonic(password)
    if (!walletMnemonic) {
      console.error('❌ Wallet mnemonic not found')
      process.exit(1)
    }
    console.log('✅ Wallet mnemonic loaded')

    // 2. Initialize storage
    console.log('\n2️⃣ Initializing storage...')
    const identity = await loadIdentity()
    await initializeStorage(identity)
    console.log('✅ Storage initialized')

    // 3. Get current address for USDT
    console.log('\n3️⃣ Getting current USDT address...')
    const chain = 'ethereum-usdt'
    const currentAddr = await getCurrentAddress(chain)
    const accountIndex = currentAddr ? currentAddr.index : 0
    console.log(`   Address index: ${accountIndex}`)
    if (currentAddr) {
      console.log(`   Address: ${currentAddr.address}`)
    }

    // 4. Test both testnet and mainnet
    for (const network of ['testnet', 'mainnet']) {
      console.log(`\n4️⃣ Testing ${network.toUpperCase()}...`)
      console.log('-'.repeat(60))

      try {
        // Get token info
        const tokenInfo = getTokenInfo(chain, network === 'testnet')
        console.log(`   Token: ${tokenInfo.symbol}`)
        console.log(`   Contract: ${tokenInfo.contractAddress}`)
        console.log(`   Decimals: ${tokenInfo.decimals}`)

        // Initialize WDK
        console.log(`\n   Initializing WDK for ${network}...`)
        const { wdk } = await initializeWDK(walletMnemonic, { testnet: network === 'testnet' })
        console.log('   ✅ WDK initialized')

        // Get base chain account
        const baseChain = getBaseChain(chain)
        console.log(`\n   Getting ${baseChain} account at index ${accountIndex}...`)
        const account = await wdk.getAccount(baseChain, accountIndex)
        console.log('   ✅ Account retrieved')

        // Get address
        const address = await account.getAddress()
        console.log(`   Address: ${address}`)

        // Check if stored address matches
        if (currentAddr && currentAddr.address.toLowerCase() !== address.toLowerCase()) {
          console.warn(`   ⚠️  WARNING: Stored address mismatch!`)
          console.warn(`      Stored: ${currentAddr.address}`)
          console.warn(`      Derived: ${address}`)
        }

        // Get token balance
        console.log(`\n   Fetching USDT balance...`)
        console.log(`   Calling: account.getTokenBalance("${tokenInfo.contractAddress}")`)

        const startTime = Date.now()
        const balance = await account.getTokenBalance(tokenInfo.contractAddress)
        const duration = Date.now() - startTime

        console.log(`   ✅ Balance retrieved in ${duration}ms`)
        console.log(`   Raw balance: ${balance.toString()}`)

        // Format balance
        const balanceDecimal = Number(balance) / Math.pow(10, tokenInfo.decimals)
        console.log(`   Formatted: ${balanceDecimal.toFixed(2)} ${tokenInfo.symbol}`)

        // Also get ETH balance for gas
        console.log(`\n   Checking ETH balance (for gas)...`)
        const ethBalance = await account.getBalance()
        const ethBalanceDecimal = Number(ethBalance) / 1e18
        console.log(`   ETH balance: ${ethBalanceDecimal.toFixed(6)} ETH`)

        if (ethBalance === 0n) {
          console.warn(`   ⚠️  WARNING: No ETH for gas fees!`)
        }

      } catch (err) {
        console.error(`   ❌ ${network} failed:`, err.message)
        console.error(`   Stack:`, err.stack)
      }
    }

    console.log('\n' + '='.repeat(60))
    console.log('✅ Debug complete')

  } catch (err) {
    console.error('\n❌ Fatal error:', err.message)
    console.error('Stack:', err.stack)
    process.exit(1)
  }
}

debugUSDTBalance()