import { address as parseAddress } from '@solana/kit';
import { ArtifactState, } from '@hyperlane-xyz/provider-sdk/artifact';
import { assert, eqAddressSol, isNullish } from '@hyperlane-xyz/utils';
import { resolveProgram } from '../deploy/resolve-program.js';
import { fetchValidatorAnnounceAccount } from './validator-announce-query.js';
import { buildInitValidatorAnnounceInstruction } from './validator-announce-tx.js';
import { DEFAULT_COMPUTE_UNITS } from '../constants.js';
export class SvmValidatorAnnounceReader {
    rpc;
    constructor(rpc) {
        this.rpc = rpc;
    }
    async read(address) {
        const programId = parseAddress(address);
        const account = await fetchValidatorAnnounceAccount(this.rpc, programId);
        assert(account, `Validator announce not initialized at ${programId}`);
        const config = {
            mailboxAddress: account.mailbox,
        };
        return {
            artifactState: ArtifactState.DEPLOYED,
            config,
            deployed: { address: programId },
        };
    }
}
export class SvmValidatorAnnounceWriter extends SvmValidatorAnnounceReader {
    config;
    svmSigner;
    constructor(config, rpc, svmSigner) {
        super(rpc);
        this.config = config;
        this.svmSigner = svmSigner;
    }
    async create(artifact) {
        const receipts = [];
        const { programAddress, receipts: deployReceipts } = await resolveProgram(this.config.program, this.svmSigner, this.rpc);
        receipts.push(...deployReceipts);
        const existing = await fetchValidatorAnnounceAccount(this.rpc, programAddress);
        const deployed = {
            artifactState: ArtifactState.DEPLOYED,
            config: artifact.config,
            deployed: { address: programAddress },
        };
        if (!isNullish(existing)) {
            assert(eqAddressSol(existing.mailbox, artifact.config.mailboxAddress), `Validator announce ${programAddress} already initialized with mailbox ${existing.mailbox}, expected ${artifact.config.mailboxAddress}`);
            assert(existing.localDomain === this.config.domainId, `VA ${programAddress} initialized for domain ${existing.localDomain}, expected ${this.config.domainId}`);
            return [deployed, receipts];
        }
        const initIx = await buildInitValidatorAnnounceInstruction(programAddress, this.svmSigner.signer, {
            mailbox: parseAddress(artifact.config.mailboxAddress),
            localDomain: this.config.domainId,
        });
        receipts.push(await this.svmSigner.send({
            instructions: [initIx],
            computeUnits: DEFAULT_COMPUTE_UNITS,
            skipPreflight: true,
        }));
        return [deployed, receipts];
    }
    async update(_artifact) {
        // Validator announce has no mutable config fields after init.
        return [];
    }
}
//# sourceMappingURL=validator-announce.js.map