"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
const anchor = __importStar(require("@coral-xyz/anchor"));
const child_process_1 = require("child_process");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const RPC_URL = "https://api.devnet.solana.com";
const main = async () => {
    const externalPrograms = [
        { name: "message_transmitter", id: "CCTPmbSD7gX1bxKPAmg77w8oFzNFpaQiQUWD43TKaecd" },
        { name: "token_messenger_minter", id: "CCTPiPYPc6AsJuwueEnWgSgucamXDZwBd53dQ11YiKX3" },
    ];
    for (const program of externalPrograms) {
        await fetchIdl(program.name, program.id);
        await convertIdl(program.name);
        await generateType(program.name);
        await copyIdls(program.name);
    }
};
const fetchIdl = async (programName, programId) => {
    const provider = anchor.AnchorProvider.local(RPC_URL);
    const idl = (await anchor.Program.fetchIdl(programId, provider));
    // CCTP programs have missing metadata.address
    idl.metadata = { address: programId };
    const idlDir = path.resolve(__dirname, "../../target/idl");
    const outputFilePath = path.join(idlDir, `${programName}.json`);
    fs.writeFileSync(outputFilePath, JSON.stringify(idl, null, 2));
};
const convertIdl = async (programName) => {
    const idlDir = path.resolve(__dirname, "../../target/idl");
    const idlFilePath = path.join(idlDir, `${programName}.json`);
    return new Promise((resolve, reject) => {
        (0, child_process_1.exec)(`anchor idl convert --out ${idlFilePath} ${idlFilePath}`, (err, _stdout, stderr) => {
            if (stderr) {
                console.error(`${stderr}`);
            }
            if (err) {
                reject(new Error(`Failed to convert ${programName} IDL`));
            }
            else {
                resolve();
            }
        });
    });
};
const generateType = async (programName) => {
    const idlDir = path.resolve(__dirname, "../../target/idl");
    const idlFilePath = path.join(idlDir, `${programName}.json`);
    const typesDir = path.resolve(__dirname, "../../target/types");
    const typeFilePath = path.join(typesDir, `${programName}.ts`);
    return new Promise((resolve, reject) => {
        (0, child_process_1.exec)(`anchor idl type --out "${typeFilePath}" "${idlFilePath}"`, (err, _stdout, stderr) => {
            if (stderr) {
                console.error(`${stderr}`);
            }
            if (err) {
                reject(new Error(`Failed to generate type for ${programName}`));
            }
            else {
                resolve();
            }
        });
    });
};
const copyIdls = async (programName) => {
    const idlDir = path.resolve(__dirname, "../../target/idl");
    const idlsDir = path.resolve(__dirname, "../../idls");
    const idlFilePath = path.join(idlDir, `${programName}.json`);
    const idlFilePathCopy = path.join(idlsDir, `${programName}.json`);
    if (!fs.existsSync(idlsDir))
        fs.mkdirSync(idlsDir, { recursive: true });
    fs.copyFileSync(idlFilePath, idlFilePathCopy);
};
main()
    .then(() => process.exit(0))
    .catch((err) => {
    console.error(err);
    process.exit(1);
});
