"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getConnectedProgram = getConnectedProgram;
exports.getSpokePoolProgram = getSpokePoolProgram;
exports.getMessageTransmitterProgram = getMessageTransmitterProgram;
exports.getTokenMessengerMinterProgram = getTokenMessengerMinterProgram;
exports.getMulticallHandlerProgram = getMulticallHandlerProgram;
exports.getMessageTransmitterV2Program = getMessageTransmitterV2Program;
exports.getTokenMessengerMinterV2Program = getTokenMessengerMinterV2Program;
const anchor_1 = require("@coral-xyz/anchor");
const DeploymentUtils_1 = require("../../DeploymentUtils");
const assets_1 = require("../assets");
const helpers_1 = require("./helpers");
function getConnectedProgram(idl, provider, programId) {
    idl.address = programId;
    return new anchor_1.Program(idl, provider);
}
// Resolves the program ID from options or defaults to the deployed address. Prioritizes programId, falls back to
// network, and if network is not defined, determines the network from the provider's RPC URL. Throws an error if
// the program ID cannot be resolved.
function resolveProgramId(programName, provider, options) {
    const { network, programId } = options ?? {};
    if (programId) {
        return programId; // Prioritize explicitly provided programId
    }
    const resolvedNetwork = network ?? ((0, helpers_1.isSolanaDevnet)(provider) ? "devnet" : "mainnet");
    const deployedAddress = (0, DeploymentUtils_1.getDeployedAddress)(programName, (0, helpers_1.getSolanaChainId)(resolvedNetwork).toString());
    if (!deployedAddress) {
        throw new Error(`${programName} Program ID not found for ${resolvedNetwork}`);
    }
    return deployedAddress;
}
function getSpokePoolProgram(provider, options) {
    const id = resolveProgramId("SvmSpoke", provider, options);
    return getConnectedProgram(assets_1.SvmSpokeIdl, provider, id);
}
function getMessageTransmitterProgram(provider, options) {
    const id = resolveProgramId("MessageTransmitter", provider, options);
    return getConnectedProgram(assets_1.MessageTransmitterIdl, provider, id);
}
function getTokenMessengerMinterProgram(provider, options) {
    const id = resolveProgramId("TokenMessengerMinter", provider, options);
    return getConnectedProgram(assets_1.TokenMessengerMinterIdl, provider, id);
}
function getMulticallHandlerProgram(provider, options) {
    const id = resolveProgramId("MulticallHandler", provider, options);
    return getConnectedProgram(assets_1.MulticallHandlerIdl, provider, id);
}
function getMessageTransmitterV2Program(provider, options) {
    const id = resolveProgramId("MessageTransmitterV2", provider, options);
    return getConnectedProgram(assets_1.MessageTransmitterV2Idl, provider, id);
}
function getTokenMessengerMinterV2Program(provider, options) {
    const id = resolveProgramId("TokenMessengerMinterV2", provider, options);
    return getConnectedProgram(assets_1.TokenMessengerMinterV2Idl, provider, id);
}
