"use strict";
// This script reclaims used nonce accounts created on the sponsored CCTP bridge.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const anchor = __importStar(require("@coral-xyz/anchor"));
const anchor_1 = require("@coral-xyz/anchor");
const yargs_1 = __importDefault(require("yargs"));
const helpers_1 = require("yargs/helpers");
const web3_v1_1 = require("../../../src/svm/web3-v1");
const web3_js_1 = require("@solana/web3.js");
// Set up the provider and programs
const provider = anchor_1.AnchorProvider.env();
anchor.setProvider(provider);
const program = (0, web3_v1_1.getSponsoredCctpSrcPeripheryProgram)(provider);
const programId = program.programId;
const messageTransmitterV2Program = (0, web3_v1_1.getMessageTransmitterV2Program)(provider);
const messageTransmitter = (0, web3_v1_1.findProgramAddress)("message_transmitter", messageTransmitterV2Program.programId).publicKey;
const irisApiUrl = (0, web3_v1_1.isSolanaDevnet)(provider) ? web3_v1_1.CIRCLE_IRIS_API_URL_DEVNET : web3_v1_1.CIRCLE_IRIS_API_URL_MAINNET;
// Parse arguments
const argvPromise = (0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
    .option("from", {
    type: "number",
    demandOption: false,
    default: 0,
    describe: "Filter deposits from this timestamp (in seconds since epoch)",
})
    .option("to", {
    type: "number",
    demandOption: false,
    describe: "Filter deposits to this timestamp (in seconds since epoch)",
}).argv;
async function reclaimEventAccounts() {
    const argv = await argvPromise;
    const fromTs = argv.from;
    const txPayer = provider.wallet.payer;
    if (!txPayer) {
        throw new Error("Provider wallet does not have a keypair");
    }
    const latestSlot = await provider.connection.getSlot("finalized");
    const latestBlockTime = await provider.connection.getBlockTime(latestSlot);
    if (!latestBlockTime) {
        throw new Error("Could not fetch latest block time");
    }
    const toTs = argv.to || latestBlockTime;
    const events = await (0, web3_v1_1.readProgramEvents)(provider.connection, program);
    const createdEvents = events.filter((event) => {
        return event.blockTime >= fromTs && event.blockTime <= toTs && event.name === "createdEventAccount";
    });
    if (createdEvents.length === 0) {
        console.log("No MessageSent creation events found for the given time range.");
        return;
    }
    console.log("MessageSent creation events fetched successfully.");
    for (const event of createdEvents) {
        const messageSentEventData = event.data.messageSentEventData;
        const messageSentAccount = await provider.connection.getAccountInfo(messageSentEventData);
        if (!messageSentAccount) {
            console.log(`MessageSent account ${messageSentEventData.toString()} does not exist, skipping.`);
            continue;
        }
        const { createdAt, message } = await messageTransmitterV2Program.account.messageSent.fetch(messageSentEventData);
        const canCloseAfter = createdAt.toNumber() + web3_v1_1.EVENT_ACCOUNT_WINDOW_SECONDS;
        if (canCloseAfter >= latestBlockTime) {
            console.log(`Skipping MessageSent event event account ${messageSentEventData.toString()} from tx ${event.signature} which can be closed only after ${new Date(canCloseAfter * 1000).toUTCString()}`);
            continue;
        }
        const attestationResponse = await (0, web3_v1_1.getV2BurnAttestation)(event.signature, message, irisApiUrl);
        if (!attestationResponse) {
            console.log(`No matching attestation found for MessageSent event in tx ${event.signature}, skipping.`);
            continue;
        }
        console.log(`Found matching attestation for MessageSent event in tx ${event.signature}, trying to reclaim:`);
        // Encode instruction parameters from decoded destination message.
        const destinationMessage = (0, web3_v1_1.decodeMessageSentDataV2)(attestationResponse.destinationMessage);
        const finalityThresholdExecutedBuffer = Buffer.alloc(4);
        finalityThresholdExecutedBuffer.writeUInt32BE(destinationMessage.finalityThresholdExecuted, 0);
        const reclaimEventAccountParams = {
            attestation: attestationResponse.attestation,
            nonce: (0, web3_v1_1.intToU8Array32)(new anchor_1.BN(destinationMessage.nonce.toString())),
            finalityThresholdExecuted: Array.from(finalityThresholdExecutedBuffer),
            feeExecuted: (0, web3_v1_1.intToU8Array32)(new anchor_1.BN(destinationMessage.messageBody.feeExecuted.toString())),
            expirationBlock: (0, web3_v1_1.intToU8Array32)(new anchor_1.BN(destinationMessage.messageBody.expirationBlock.toString())),
        };
        const reclaimIx = await program.methods
            .reclaimEventAccount(reclaimEventAccountParams)
            .accounts({ messageTransmitter, messageSentEventData, program: programId })
            .instruction();
        const computeBudgetIx = web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: 250_000 });
        const tx = new web3_js_1.Transaction().add(computeBudgetIx, reclaimIx);
        const txSignature = await provider.sendAndConfirm(tx, [txPayer], { commitment: "confirmed" });
        console.log(`-reclaimed event account ${messageSentEventData.toString()}, transaction signature: ${txSignature}`);
    }
}
reclaimEventAccounts();
