2

I'd like to define something like:

pub mod mints {
    use solana_program::{pubkey, pubkey::Pubkey};
    pub const USDC: Pubkey = pubkey!("key");
}

But then be able to access it with mints::USDC and have the value be environment dependent.

Is this possible? How do I achieve this with either just solana/rust or within Anchor?

2 Answers 2

2

I personally use the env! and option_env! macros, then set an environment variable e.g. MAINNET when I want to build for mainnet and assume devnet otherwise.

Combined with just to set env-vars it works pretty well, e.g. you can setup a command just build-bpf-mainnet as MAINNET=1 cargo build-bpf

This way it's pretty easy to setup constants for different mints:

pub fn is_mainnet() -> bool {
    option_env!("MAINNET").is_some()
}

pub struct Mint {
    dev: Pubkey,
    main: Pubkey,
}

impl Mint {
    pub fn pubkey(&self) -> Pubkey {
        if is_mainnet() {
            self.main
        } else {
            self.dev
        }
    }
}

pub const USDC: Mint = Mint {
    main: pubkey!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),
    dev: pubkey!("4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"),
};

pub const LIKE: Mint = Mint {
    main: pubkey!("3bRTivrVsitbmCTGtqwp7hxXPsybkjn4XLNtPsHqa3zR"),
    dev: pubkey!("8KM7nEzUebxtnJ1BRbbnh58Bnm1ZCtmCsp1xW1zYsuWp"),
};

I tried looking for a way for on-chain programs to determine dev/local/mainnet recently but couldn't find any.

0

this library might might help?

confy

1
  • Thanks. Perhaps to specialize this a bit more: Is it possible for environment detection to happen when the code is deployed? If I deploy to mainnet a different set of constants is defined as opposed to local dev? Commented Oct 31, 2022 at 10:27

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.