// 测试 lendingProxy 合约是否正确部署
const { createPublicClient, http } = require('viem')
const { bscTestnet } = require('viem/chains')

const lendingProxyAddress = '0xCb4E7B1069F6C26A1c27523ce4c8dfD884552d1D'
const userAddress = '0xa013422A5918CD099C63c8CC35283EACa99a705d'

const client = createPublicClient({
  chain: bscTestnet,
  transport: http('https://data-seed-prebsc-1-s1.binance.org:8545'),
})

async function testContract() {
  console.log('🔍 测试 lendingProxy 合约...\n')
  console.log('链:', 'BSC Testnet')
  console.log('合约地址:', lendingProxyAddress)
  console.log('用户地址:', userAddress)
  console.log('---\n')

  try {
    // 1. 检查合约是否存在
    console.log('1️⃣ 检查合约代码...')
    const code = await client.getBytecode({ address: lendingProxyAddress })
    if (!code || code === '0x') {
      console.error('❌ 合约未部署或地址错误！')
      return
    }
    console.log('✅ 合约已部署，代码长度:', code.length, '字节\n')

    // 2. 尝试调用 supplyBalanceOf
    console.log('2️⃣ 调用 supplyBalanceOf...')
    const supplyBalanceOfABI = {
      type: 'function',
      name: 'supplyBalanceOf',
      inputs: [{ name: 'account', type: 'address' }],
      outputs: [{ name: '', type: 'uint256' }],
      stateMutability: 'view',
    }

    const balance = await client.readContract({
      address: lendingProxyAddress,
      abi: [supplyBalanceOfABI],
      functionName: 'supplyBalanceOf',
      args: [userAddress],
    })

    console.log('✅ 查询成功！')
    console.log('供应余额:', balance.toString())
    console.log('格式化:', (Number(balance) / 1e18).toFixed(2), 'USDC\n')

    // 3. 尝试调用其他函数
    console.log('3️⃣ 检查其他函数...')

    const getTotalSupplyABI = {
      type: 'function',
      name: 'getTotalSupply',
      inputs: [],
      outputs: [{ name: '', type: 'uint256' }],
      stateMutability: 'view',
    }

    const totalSupply = await client.readContract({
      address: lendingProxyAddress,
      abi: [getTotalSupplyABI],
      functionName: 'getTotalSupply',
    })

    console.log('✅ getTotalSupply:', totalSupply.toString())
    console.log('总供应量:', (Number(totalSupply) / 1e18).toFixed(2), 'USDC\n')

  } catch (error) {
    console.error('❌ 错误:', error.message)
    console.error('详细:', error)
  }
}

testContract()
