// Read on-chain USDC balances for one or more Tempo addresses.
//
// RUN (one-liner, from repo root): cp scripts/tempo-balance.ts /tmp/tempo-transfer/ && (cd /tmp/tempo-transfer && ./node_modules/.bin/tsx tempo-balance.ts)
//
// Edit the ACCOUNTS list in the CONFIG block below to add/remove wallets.
// Each entry prints: USDC balance, nonce (0 = wallet has never sent a tx),
// and whether the address is an EOA or a contract.
//
// Why the copy-into-/tmp dance: the repo's own node_modules has a
// @noble/hashes version conflict that breaks viem's ESM import resolution,
// so the script must run from the isolated /tmp/tempo-transfer/ install.
// To rebuild that dir if it's missing:
//   mkdir -p /tmp/tempo-transfer && cd /tmp/tempo-transfer && npm init -y && npm install viem@2.47.6 tsx

// ─── CONFIG ──────────────────────────────────────────────────────────────────

const ACCOUNTS = [
  { label: 'Bloby', wallet: '0xc65d8a0dB80f637337B87e42b8BEb5D86D46f942' },
  { label: 'Treasury',   wallet: '0x084A80e395FaE8Aaf58F591f47F63DA1EeF06bbC' },
  { label: 'Serge',   wallet: '0x21AC79F74da90c9F441699Ee6215dA32c0CE9F5a' },
];

// ─────────────────────────────────────────────────────────────────────────────

import { createPublicClient, http, formatUnits } from 'viem';
import { tempo } from 'viem/chains';

const USDC = '0x20c000000000000000000000b9537d11c60e8b50' as const;
const DECIMALS = 6;
const RPC = 'https://rpc.tempo.xyz';

const erc20Abi = [{
  name: 'balanceOf',
  type: 'function',
  stateMutability: 'view',
  inputs: [{ name: 'account', type: 'address' }],
  outputs: [{ name: '', type: 'uint256' }],
}] as const;

async function main() {
  const client = createPublicClient({ chain: tempo, transport: http(RPC) });
  const block = await client.getBlockNumber();

  console.log(`Block: ${block}`);
  console.log('');

  for (const { label, wallet } of ACCOUNTS) {
    const address = wallet as `0x${string}`;

    const [balance, nonce, code] = await Promise.all([
      client.readContract({
        address: USDC, abi: erc20Abi, functionName: 'balanceOf', args: [address],
      }),
      client.getTransactionCount({ address }),
      client.getCode({ address }),
    ]);

    const isContract = code && code !== '0x';

    console.log(`${label}  ${address}`);
    console.log(`  USDC:  ${formatUnits(balance, DECIMALS)}`);
    console.log(`  nonce: ${nonce}${nonce === 0 ? '  (never sent a tx)' : ''}`);
    console.log(`  type:  ${isContract ? 'contract' : 'EOA'}`);
    console.log('');
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
