hopper-cli 0.3.0

Command-line tooling for Hopper account inspection, schema export, and migration planning
//! `hopper publish-manifest`: publish or read back the full Hopper program
//! manifest through the Program Metadata program.
//!
//! `publish-idl` ships only the lossless Solana IDL v0.1.0 projection, which
//! is what generic explorers read. The Hopper manifest is the richer
//! declaration: contexts, write ranges, lamport powers, PDA bindings, CPI
//! targets, the release-interface commitment. Publishing it under the custom
//! seed `hopper-manifest` puts the exact document `hopper verify
//! --authority-baseline` diffs against on the ledger, next to the program it
//! describes, so a reviewer can fetch the baseline from chain instead of
//! trusting a file handed over out of band.
//!
//! Program Metadata permits custom seeds but does not reserve them, so the
//! record is a Hopper convention: the same 96-byte header, Utf8 + Zlib +
//! Json, canonical PDA `[program, "hopper-manifest"]`, written by the
//! program's upgrade authority.
//!
//! ```text
//! hopper publish-manifest --manifest hopper.manifest.json --program-id <id> --dry-run
//! hopper publish-manifest --manifest hopper.manifest.json --program-id <id> --cluster devnet
//! hopper publish-manifest --read --program-id <id> --cluster devnet
//! ```

use std::process;

use super::publish_idl::{render_dry_run_record, run_publish_send, PreparedPayload, PublishRecord};
use super::publish_security::{read_record, RecordArgs};

/// Custom Program Metadata seed for the Hopper manifest record.
pub const MANIFEST_SEED: &[u8] = b"hopper-manifest";

fn print_usage() {
    eprintln!("Usage: hopper publish-manifest --manifest <path> --program-id <pubkey>");
    eprintln!("                               [--cluster <name> | --url <rpc>] [--keypair <path>]");
    eprintln!("                               [--seed <str>] [--overwrite] [--yes] [--dry-run]");
    eprintln!("       hopper publish-manifest --read --program-id <pubkey> [--cluster <name> | --url <rpc>]");
    eprintln!();
    eprintln!("Publish the normalized Hopper manifest (the document hopper verify diffs) at");
    eprintln!("the canonical [program, \"hopper-manifest\"] Program Metadata PDA, or read the");
    eprintln!("published one back. Same signed-send path as publish-idl.");
    eprintln!();
    eprintln!("Options:");
    eprintln!("  --manifest <path>     Hopper program manifest JSON (also accepts inline/@file)");
    eprintln!("  --program-id <pubkey> Base58 program id the manifest describes");
    eprintln!("  --cluster <name>      devnet (default), testnet, mainnet-beta, or localnet");
    eprintln!("  --url, --rpc <rpc>    Custom RPC endpoint; treated as potentially mainnet");
    eprintln!("  --keypair <path>      Upgrade-authority + fee-payer keypair");
    eprintln!("                        (default: ~/.config/solana/id.json)");
    eprintln!(
        "  --seed <str>          Metadata seed (default \"hopper-manifest\", padded to 16 bytes)"
    );
    eprintln!("  --overwrite           Rewrite an already-published record (SetData; one tx only)");
    eprintln!("  --read                Fetch, decode, and print the published manifest");
    eprintln!("  --yes, -y             Skip mainnet/custom-RPC confirmation");
    eprintln!("  --dry-run             Preview the header/PDA/plan; no network access or prompt");
}

/// `hopper publish-manifest` entry point.
pub fn cmd_publish_manifest(args: &[String]) {
    let parsed = match RecordArgs::parse(args, &["--manifest"], print_usage) {
        Ok(Some(parsed)) => parsed,
        Ok(None) => return,
        Err(e) => {
            eprintln!("publish-manifest: {e}");
            print_usage();
            process::exit(1);
        }
    };
    if let Err(e) = run(&parsed) {
        eprintln!("publish-manifest: {e}");
        process::exit(1);
    }
}

fn run(args: &RecordArgs) -> Result<(), String> {
    if args.init.is_some() {
        return Err("--init is a publish-security option; a manifest is generated by `hopper compile --emit manifest`".to_string());
    }
    let seed16 = args.seed16(MANIFEST_SEED)?;
    if args.read {
        return read_record("publish-manifest", args, &seed16);
    }

    let manifest_arg = args
        .file
        .as_deref()
        .ok_or_else(|| "--manifest <path> is required (or --read)".to_string())?;
    let program_id = args.program_id_bytes()?;

    // Normalize through the same loader every other command uses, so the
    // published bytes are the canonical rendering, not the file's whitespace.
    let load_arg = if manifest_arg.starts_with('@') || manifest_arg.trim_start().starts_with('{') {
        manifest_arg.to_string()
    } else {
        format!("@{manifest_arg}")
    };
    let manifest = crate::load_program_manifest(&load_arg);
    let json = format!("{}", hopper_schema::codama::ManifestJson(&manifest));

    let payload = PreparedPayload::from_json(&json);
    let record = PublishRecord {
        command: "publish-manifest",
        noun: "manifest",
        source: format!(
            "Hopper manifest {} v{} ({} instructions, {} layouts)",
            manifest.name,
            manifest.version,
            manifest.instructions.len(),
            manifest.layouts.len()
        ),
    };

    if args.dry_run {
        print!(
            "{}",
            render_dry_run_record(&record, &program_id, &seed16, &payload)
        );
        return Ok(());
    }

    run_publish_send(
        &record,
        &program_id,
        &seed16,
        &payload,
        args.url.as_deref(),
        args.cluster.as_deref(),
        args.keypair.as_deref(),
        args.overwrite,
        args.yes,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cmd::publish_idl::{pad_seed, SEED_LEN};

    #[test]
    fn manifest_seed_fits_the_sixteen_byte_field() {
        assert!(MANIFEST_SEED.len() <= SEED_LEN);
        let seed = pad_seed(MANIFEST_SEED);
        assert_eq!(&seed[..MANIFEST_SEED.len()], MANIFEST_SEED);
        assert_eq!(seed[MANIFEST_SEED.len()], 0);
    }

    #[test]
    fn dry_run_describes_a_buffered_plan_for_a_real_manifest() {
        // The committed sentinel manifest is well past the 800-byte inline
        // threshold once compressed, so the plan must be Allocate + Write.
        let json = include_str!("../../tests/fixtures/hopper-sentinel.manifest.json");
        let payload = PreparedPayload::from_json(json);
        let record = PublishRecord {
            command: "publish-manifest",
            noun: "manifest",
            source: "Hopper manifest hopper_sentinel".to_string(),
        };
        let report = render_dry_run_record(&record, &[3u8; 32], &pad_seed(MANIFEST_SEED), &payload);
        assert!(report.contains("=== hopper publish-manifest (dry run) ==="));
        assert!(report.contains("Seed:               \"hopper-manifest\""));
        assert!(report.contains("Hopper manifest hopper_sentinel"));
        assert!(
            report.contains("Allocate") || report.contains("single inline Initialize"),
            "{report}"
        );
    }
}