"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
const provider = anchor_1.AnchorProvider.env();
anchor.setProvider(provider);
const program = (0, web3_v1_1.getSponsoredCctpSrcPeripheryProgram)(provider);
const programId = program.programId;
// 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 reclaimUsedNonceAccounts() {
    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 depositEvents = events.filter((event) => {
        return event.blockTime >= fromTs && event.blockTime <= toTs && event.name === "sponsoredDepositForBurn";
    });
    if (depositEvents.length === 0) {
        console.log("No deposit events found for the given time range.");
        return;
    }
    console.log("Sponsored deposit events fetched successfully.");
    for (const event of depositEvents) {
        const quoteNonce = event.data.quoteNonce;
        const [usedNonce] = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("used_nonce"), quoteNonce], programId);
        const usedNonceAccount = await provider.connection.getAccountInfo(usedNonce);
        if (!usedNonceAccount) {
            console.log(`Used nonce account ${usedNonce.toString()} does not exist, skipping.`);
            continue;
        }
        console.log(`Sponsored deposit with used nonce 0x${quoteNonce.toString("hex")}:`);
        const quoteDeadline = event.data.quoteDeadline.toNumber();
        if (quoteDeadline >= latestBlockTime) {
            console.log(`- skipping used nonce account ${usedNonce.toString()} from tx ${event.signature} which can be closed only after ${new Date(quoteDeadline * 1000).toUTCString()}`);
            continue;
        }
        console.log(`-reclaiming used nonce account ${usedNonce.toString()}`);
        const ix = await program.methods.reclaimUsedNonceAccount({ nonce: Array.from(quoteNonce) }).instruction();
        const tx = new web3_js_1.Transaction().add(ix);
        const txSignature = await provider.sendAndConfirm(tx, [txPayer], { commitment: "confirmed" });
        console.log(`-reclaimed used nonce account ${usedNonce.toString()}, transaction signature: ${txSignature}`);
    }
}
reclaimUsedNonceAccounts();
