Skip to content

Commit

Permalink
cli: Add --program-id option to idl convert command (#3309)
Browse files Browse the repository at this point in the history
  • Loading branch information
acheroncrypto authored Oct 11, 2024
1 parent 5df7fbd commit a043abd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ The minor version will be incremented upon a breaking change and the patch versi
- cli: Check whether the `idl-build` feature exists when using the `idl build` command ([#3273](https://github.com/coral-xyz/anchor/pull/3273)).
- cli: Build IDL if there is only one program when using the `idl build` command ([#3275](https://github.com/coral-xyz/anchor/pull/3275)).
- cli: Add short alias for the `idl build` command ([#3283](https://github.com/coral-xyz/anchor/pull/3283)).
- cli: Add `--program-id` option to `idl convert` command ([#3309](https://github.com/coral-xyz/anchor/pull/3309)).

### Fixes

Expand Down
27 changes: 25 additions & 2 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,9 @@ pub enum IdlCommand {
/// Output file for the IDL (stdout if not specified)
#[clap(short, long)]
out: Option<String>,
/// Address to use (defaults to `metadata.address` value)
#[clap(short, long)]
program_id: Option<Pubkey>,
},
/// Generate TypeScript type for the IDL
Type {
Expand Down Expand Up @@ -2302,7 +2305,11 @@ fn idl(cfg_override: &ConfigOverride, subcmd: IdlCommand) -> Result<()> {
cargo_args,
),
IdlCommand::Fetch { address, out } => idl_fetch(cfg_override, address, out),
IdlCommand::Convert { path, out } => idl_convert(path, out),
IdlCommand::Convert {
path,
out,
program_id,
} => idl_convert(path, out, program_id),
IdlCommand::Type { path, out } => idl_type(path, out),
}
}
Expand Down Expand Up @@ -2809,8 +2816,24 @@ fn idl_fetch(cfg_override: &ConfigOverride, address: Pubkey, out: Option<String>
write_idl(&idl, out)
}

fn idl_convert(path: String, out: Option<String>) -> Result<()> {
fn idl_convert(path: String, out: Option<String>, program_id: Option<Pubkey>) -> Result<()> {
let idl = fs::read(path)?;

// Set the `metadata.address` field based on the given `program_id`
let idl = match program_id {
Some(program_id) => {
let mut idl = serde_json::from_slice::<serde_json::Value>(&idl)?;
idl.as_object_mut()
.ok_or_else(|| anyhow!("IDL must be an object"))?
.insert(
"metadata".into(),
serde_json::json!({ "address": program_id.to_string() }),
);
serde_json::to_vec(&idl)?
}
_ => idl,
};

let idl = convert_idl(&idl)?;
let out = match out {
None => OutFile::Stdout,
Expand Down

0 comments on commit a043abd

Please sign in to comment.