Here is an article with explanations and examples on how to conditionally set the program_id
in the declare_id!
macro:
Conditional Program IDs in Anchor Declarations
In Anchor, you can use the declare_id!
macro to create a program identifier that can be used in different builds. A common use case is when you want to deploy your application differently depending on whether it is running in production or staging.
Basic Usage
First, let’s see how you can conditionally set the program_id
using the declare_id!
macro:
use anchor_lang::declares;
#[derive(AnchorProgram)]
pub mod my_program {
declare_id!("3gHtqUaKGu3RJCWVbgQFd5Gv4MQfQKmQjKSvdejkLoA6");
}
In this example, the program_id
is hardcoded to "3gHtqUaKGu3RJCWVbgQFd5Gv4MQfQKmQjKSvdejkLoA6"
, which will always be used.
Using a Constant
To make your code more readable and maintainable, you can define a constant for the program_id
:
use anchor_lang::declares;
const PROGRAM_ID: &str = "3gHtqUaKGu3RJCWVbgQFd5Gv4MQfQKmQjKSvdejkLoA6";
#[derive(AnchorProgram)]
pub mod my_program {
declare_id!(&PROGRAM_ID);
}
In this example, the constant PROGRAM_ID
is defined and used in the declare_id!
macro.
Using a Variable
If you need to use the program ID as a variable, you can define it using the program_id
type:
use anchor_lang::declares;
pub const PROGRAM_ID: &str = get_program_id();
And then use it in your declare_id!
macro:
#[derive(AnchorProgram)]
pub mod my_program {
declare_id!(PROGRAM_ID);
}
Test Builds
To create test builds, you can use program_id
to conditionally set the program ID. For example, let’s say you have a function that depends on the program ID:
use anchor_lang::declares;
fn my_function(program_id: &str) -> Result<(), AnchorError> {
// ...
}
You can define a test build using the program_id
like this:
#[derive(AnchorProgram)]
pub mod my_program {
declare_id!(if is_staging() { PROGRAM_ID } else { get_program_id() });
#[function]
pub fn my_function(program_id: &str) -> Result<(), AnchorError> {
// ...
}
}
In this example, the my_function
function will use the program ID defined in the test build if it is run in test.
Conclusion
Using the declare_id!
macro and defining constants or variables for the program ID will help you create more flexible and maintainable code that adapts to different builds. Remember to always follow the guidelines in the Anchor documentation when writing your code.