2

Is there some special approach for defining constants in Anchor? I tried it normally just before the program ID:

pub const MY_CONST: &'static str = "some example str";

declare_id!("MY_PROGRAM_PUBKEY");

But then I try to verify if my constants were defined within some of my Anchor instructions:

msg! {"My const value: {:#?}", std::env::var("MY_CONST")};
msg! {"My const value: {:#?}", option_env!("MY_CONST")};

But I keep getting empty values, I guess it has something to do with the run time. Is there some "Anchor way" of defining constants or verify if they are actually defined?

1 Answer 1

6

I think you're mixing up constants and environment variables. You can use constants by just referring to them by name, they don't become environment variables.

For example:

use anchor_lang::prelude::*;

declare_id!("B5KGifZpdZqPtnC1qgkwjMZB2LBp9seXC5fJXPTN8x4W");

const THE_NUMBER: u8 = 42;

#[program]
mod hello_anchor {
    use super::*;
    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        msg!("The number is: {}!", THE_NUMBER); // Message will show up in the tx logs
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize {
}

Transaction: https://explorer.solana.com/tx/2BxPY6pNU2d6C1hZfBdfvFvDqwxeB14m6LohwLCrZQ4eWnigqr3DUufiuuSyM7f3HavAothwBAZvtVQVAGfjA3Mw?cluster=devnet (notice "The number is: 42!" in the logs)

Example playground: https://beta.solpg.io/63f8a3cf67edfe0f001069d4

2
  • What if THE_NUMBERis not defined? how can you handle that case within the ìnitialize()` function? That's what I really want to achieve here. Commented Feb 27, 2023 at 1:27
  • I'm not really sure what you're asking here, but if you wanted to pass the number into the instruction instead of having it be a constant it'd be like this: beta.solpg.io/63fe190f67edfe0f001069d9 Does that help?
    – Callum M
    Commented Feb 28, 2023 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.