"use strict";
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 });
// This script closes all Relayer PDAs associated with tracking fill Status. Relayers should do this periodically to
// reclaim the lamports within these tracking accounts. Fill Status PDAs can be closed on the deposit has expired.
const anchor = __importStar(require("@coral-xyz/anchor"));
const anchor_1 = require("@coral-xyz/anchor");
const web3_js_1 = require("@solana/web3.js");
const yargs_1 = __importDefault(require("yargs"));
const helpers_1 = require("yargs/helpers");
const web3_v1_1 = require("../../src/svm/web3-v1");
// Set up the provider
const provider = anchor_1.AnchorProvider.env();
anchor.setProvider(provider);
const program = (0, web3_v1_1.getSpokePoolProgram)(provider);
const programId = program.programId;
// Parse arguments
const argv = (0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
    .option("seed", { type: "string", demandOption: true, describe: "Seed for the state account PDA" })
    .option("relayer", { type: "string", demandOption: true, describe: "Relayer public key" }).argv;
async function closeExpiredRelays() {
    const resolvedArgv = await argv;
    const relayer = new web3_js_1.PublicKey(resolvedArgv.relayer);
    const seed = new anchor_1.BN(resolvedArgv.seed);
    console.table([
        { Property: "relayer", Value: relayer.toString() },
        { Property: "seed", Value: seed.toString() },
        { Property: "programId", Value: programId.toString() },
    ]);
    try {
        const events = await (0, web3_v1_1.readProgramEvents)(provider.connection, program);
        const fillEvents = events.filter((event) => event.name === "filledV3Relay" && new web3_js_1.PublicKey(event.data.relayer).equals(relayer));
        console.log(`Number of fill events found: ${fillEvents.length}`);
        if (fillEvents.length === 0) {
            console.log("No fill events found for the given relayer.");
            return;
        }
        for (const event of fillEvents) {
            const currentTime = Math.floor(Date.now() / 1000);
            if (currentTime > event.data.fillDeadline) {
                await closeFillPda(event.data, seed);
            }
            else {
                console.log(`Found relay with depositId: ${event.data.depositId} from source chain id: ${event.data.originChainId}, but it is not expired yet.`);
            }
        }
    }
    catch (error) {
        console.error("An error occurred while fetching the fill events:", error);
    }
}
async function closeFillPda(eventData, seed) {
    // Accept seed as a parameter
    const relayEventData = {
        depositor: new web3_js_1.PublicKey(eventData.depositor),
        recipient: new web3_js_1.PublicKey(eventData.recipient),
        exclusiveRelayer: new web3_js_1.PublicKey(eventData.exclusiveRelayer),
        inputToken: new web3_js_1.PublicKey(eventData.inputToken),
        outputToken: new web3_js_1.PublicKey(eventData.outputToken),
        inputAmount: new anchor_1.BN(eventData.inputAmount),
        outputAmount: new anchor_1.BN(eventData.outputAmount),
        originChainId: new anchor_1.BN(eventData.originChainId),
        depositId: eventData.depositId,
        fillDeadline: eventData.fillDeadline,
        exclusivityDeadline: eventData.exclusivityDeadline,
        messageHash: eventData.messageHash,
    };
    const [statePda] = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("state"), seed.toArrayLike(Buffer, "le", 8)], programId);
    // Fetch the state to get the chainId
    const state = await program.account.state.fetch(statePda);
    const chainId = new anchor_1.BN(state.chainId);
    const relayHashUint8Array = (0, web3_v1_1.calculateRelayEventHashUint8Array)(relayEventData, chainId);
    const [fillStatusPda] = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("fills"), relayHashUint8Array], programId);
    try {
        // Check if the fillStatusPda account exists
        const accountInfo = await provider.connection.getAccountInfo(fillStatusPda);
        if (!accountInfo) {
            console.log(`Fill Status PDA for depositId: ${eventData.depositId} from source chain id: ${eventData.originChainId} is already closed or does not exist.`);
            return;
        }
        // Display additional information in a table
        console.log("Found a relay to close. Relay event data:");
        console.table(Object.entries(relayEventData).map(([key, value]) => ({
            key,
            value: value.toString(),
        })));
        console.table([
            { Property: "State PDA", Value: statePda.toString() },
            { Property: "Fill Status PDA", Value: fillStatusPda.toString() },
            { Property: "Relay Hash", Value: Buffer.from(relayHashUint8Array).toString("hex") },
        ]);
        const tx = await program.methods.closeFillPda()
            .accounts({
            state: statePda,
            signer: provider.wallet.publicKey,
            fillStatus: fillStatusPda,
            systemProgram: web3_js_1.SystemProgram.programId,
        })
            .rpc();
        console.log("Transaction signature:", tx);
    }
    catch (error) {
        console.error("An error occurred while closing the fill PDA:", error);
    }
}
// Run the closeExpiredRelays function
closeExpiredRelays();
