Skip to main content
#!/usr/bin/env tsx
/**
 * Schedule automated counter increases on the AutoCounter contract
 * 
 * This script calls scheduleCounterIncrease() which schedules 10 automated
 * increaseCounter() calls to execute every 900 blocks via SchedulerHelper.
 */
import 'dotenv/config';
import {
    ensureEnv,
    PRIVATE_KEY,
    RPC_URL,
    AUTO_COUNTER_ADDRESS,
    DEFAULT_MAX_FEE_PER_GAS,
    DEFAULT_MAX_PRIORITY_FEE,
    DEFAULT_PAYMENT_AMOUNT,
    cast,
    getEOAAddress,
    getBlockNumber,
    getBalance,
    formatWeiToRit,
    extractTxHash,
} from './helpers';

function main() {
    console.log('='.repeat(58));
    console.log('Schedule AutoCounter Increases');
    console.log('='.repeat(58));

    // 0) Ensure required env vars are set
    ensureEnv();
    console.log('\n✓ Environment variables validated');

    // 1) Display account info
    const eoaAddress = getEOAAddress();
    const balance = getBalance(eoaAddress);
    console.log('\n[Account Info]');
    console.log(`  Address: ${eoaAddress}`);
    console.log(`  Balance: ${formatWeiToRit(balance)} RIT`);

    // 2) Display current block number
    const currentBlock = getBlockNumber();
    console.log('\n[Chain Info]');
    console.log(`  Current Block: ${currentBlock}`);
    console.log(`  RPC URL: ${RPC_URL}`);

    // 3) Display contract info
    console.log('\n[Contract Info]');
    console.log(`  AutoCounter: ${AUTO_COUNTER_ADDRESS}`);

    // 4) Read current counter value
    try {
        const currentCounter = cast(
            `call ${AUTO_COUNTER_ADDRESS} "counter()(uint256)" --rpc-url ${RPC_URL}`
        );
        console.log(`  Current Counter: ${currentCounter}`);
    } catch (_e) {
        console.log('  Current Counter: (unable to read)');
    }

    // 5) Display scheduling parameters
    console.log('\n[Scheduling Parameters]');
    console.log(`  Max Fee Per Gas: ${formatWeiToRit(DEFAULT_MAX_FEE_PER_GAS)} Gwei (${DEFAULT_MAX_FEE_PER_GAS} wei)`);
    console.log(`  Max Priority Fee: ${formatWeiToRit(DEFAULT_MAX_PRIORITY_FEE)} Gwei (${DEFAULT_MAX_PRIORITY_FEE} wei)`);
    console.log(`  Payment Amount: ${formatWeiToRit(DEFAULT_PAYMENT_AMOUNT)} RIT`);
    console.log(`  Value per Call: 0 RIT`);
    console.log('\n[Contract Configuration]');
    console.log('  Counter Increase: 100 per call');
    console.log('  Gas Limit: 50,000');
    console.log('  Frequency: 900 blocks');
    console.log('  Number of Calls: 10');
    console.log('  TTL: 100 blocks');

    // 6) Calculate expected execution schedule
    const firstExecution = parseInt(currentBlock) + 900;
    const lastExecution = firstExecution + (900 * 9);
    console.log('\n[Expected Execution]');
    console.log(`  First Call: Block ~${firstExecution.toLocaleString()}`);
    console.log(`  Last Call: Block ~${lastExecution.toLocaleString()}`);
    console.log(`  Total Duration: ~${(900 * 10).toLocaleString()} blocks`);

    // 7) Call scheduleCounterIncrease
    console.log('\n[Scheduling Transaction]');
    console.log('Calling scheduleCounterIncrease()...');
    
    const scheduleCmd = [
        'send',
        AUTO_COUNTER_ADDRESS,
        '"scheduleCounterIncrease(uint256,uint256,uint256)"',
        DEFAULT_MAX_FEE_PER_GAS,
        DEFAULT_MAX_PRIORITY_FEE,
        '0', // value per call
        `--value ${DEFAULT_PAYMENT_AMOUNT}`,
        `--rpc-url ${RPC_URL}`,
        `--private-key ${PRIVATE_KEY}`,
    ].join(' ');

    try {
        const scheduleOut = cast(scheduleCmd);
        const txHash = extractTxHash(scheduleOut);
        
        console.log('\n✓ Transaction successful!');
        console.log(`  Tx Hash: ${txHash}`);

        // 8) Try to read the emitted event (scheduleId)
        console.log('\n[Reading Schedule ID]');
        try {
            // Parse logs for CounterIncreaseScheduled event
            const receipt = cast(`receipt ${txHash} --rpc-url ${RPC_URL} --json`);
            const receiptData = JSON.parse(receipt);
            
            if (receiptData.logs && receiptData.logs.length > 0) {
                // The first topic is the event signature, second is the indexed scheduleId
                const scheduleIdTopic = receiptData.logs[0].topics?.[1];
                if (scheduleIdTopic) {
                    const scheduleId = BigInt(scheduleIdTopic).toString();
                    console.log(`  Schedule ID: ${scheduleId}`);
                }
            }
        } catch (_e) {
            console.log('  Schedule ID: (unable to parse from logs)');
        }

        // 9) Read updated counter value
        console.log('\n[Updated Counter]');
        try {
            const newCounter = cast(
                `call ${AUTO_COUNTER_ADDRESS} "counter()(uint256)" --rpc-url ${RPC_URL}`
            );
            console.log(`  Counter: ${newCounter} (unchanged until first execution)`);
        } catch (_e) {
            console.log('  Counter: (unable to read)');
        }

        console.log(`\n${'='.repeat(58)}`);
        console.log('✓ Schedule created successfully!');
        console.log('  Counter will increase by 100 every 900 blocks (10 times total)');
        console.log(`${'='.repeat(58)}`);
        
    } catch (error) {
        console.error('\n✗ Transaction failed!');
        console.error(error);
        process.exit(1);
    }
}

// Run if executed directly
if (require.main === module) {
    main();
}