/**
 * Transaction example: Send a transaction on ChainID 138
 * 
 * Important: Transactions must be signed with chainId: 138 (EIP-155)
 */

import { ethers } from 'ethers';
import { initTatumSDK } from '../tatum-client';
import { CHAIN_ID, CHAIN_NAME, DEFAULT_RPC_URL } from '../config';

async function main() {
  console.log(`Sending transaction on ${CHAIN_NAME} (ChainID ${CHAIN_ID})...`);
  
  // Load private key from environment
  const privateKey = process.env.PRIVATE_KEY;
  if (!privateKey) {
    throw new Error('PRIVATE_KEY environment variable not set');
  }
  
  // Initialize ethers provider with ChainID 138
  const provider = new ethers.JsonRpcProvider(DEFAULT_RPC_URL, {
    chainId: CHAIN_ID,
    name: 'defi-oracle-mainnet',
  });
  
  // Create wallet
  const wallet = new ethers.Wallet(privateKey, provider);
  console.log('Wallet Address:', wallet.address);
  
  // Get balance
  const balance = await provider.getBalance(wallet.address);
  console.log('Balance:', ethers.formatEther(balance), 'ETH');
  
  // Check if we have enough balance
  if (balance === 0n) {
    throw new Error('Insufficient balance. Please fund the wallet first.');
  }
  
  // Get recipient address from environment or use a test address
  const recipient = process.env.RECIPIENT_ADDRESS || '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb';
  const amount = process.env.AMOUNT || '0.01'; // ETH
  
  console.log(`\nSending ${amount} ETH to ${recipient}...`);
  
  // Send transaction with correct chainId
  const tx = await wallet.sendTransaction({
    to: recipient,
    value: ethers.parseEther(amount),
    chainId: CHAIN_ID, // Important: Must match ChainID 138
  });
  
  console.log('Transaction Hash:', tx.hash);
  console.log('Waiting for confirmation...');
  
  // Wait for transaction to be mined
  const receipt = await tx.wait();
  console.log('Transaction confirmed!');
  console.log('Block Number:', receipt?.blockNumber);
  console.log('Gas Used:', receipt?.gasUsed.toString());
  
  // Verify transaction using Tatum SDK
  console.log('\n=== Verifying Transaction with Tatum SDK ===');
  const tatum = await initTatumSDK({
    rpcUrl: DEFAULT_RPC_URL,
    verbose: false,
  });
  
  const txFromChain = await tatum.rpc.request('eth_getTransactionByHash', [tx.hash]);
  console.log('Transaction from chain:', JSON.stringify(txFromChain, null, 2));
  
  // Verify chainId in transaction
  if (txFromChain && typeof txFromChain === 'object' && 'chainId' in txFromChain) {
    const txChainId = parseInt(txFromChain.chainId as string, 16);
    if (txChainId === CHAIN_ID) {
      console.log('✓ ChainID verified in transaction');
    } else {
      console.error(`✗ ChainID mismatch! Expected ${CHAIN_ID}, got ${txChainId}`);
    }
  }
  
  console.log('\n=== Transaction Example Complete ===');
}

main().catch((error) => {
  console.error('Error:', error);
  process.exit(1);
});

