3

So, I want one function to be accessible to the only contract owner. So can I hard code that address and I want my rent sol to go back to that account when that account closes?

Is there a way to get the program's upgrade authority or the program's deployer in the contract itself?

If there is no way, is Any other optimal way?

2 Answers 2

4

You can use the macro pubkey! from use solana_program::pubkey;

Here's an example of only allowing one pubkey to call an instruction:

#[program]
mod hello_anchor {
    use super::*;

    const OWNER: Pubkey = pubkey!("766Mum7jSmvDPpvcKrY7WV4A69Jk6Xhgps958RDQgYcq");

    pub fn initialize(ctx: Context<Initialize>, data: u64) -> Result<()> {
        if ctx.accounts.signer.key() != OWNER {
            return Err(error!(ErrorCode::Unauthorized));
        }
        
        ctx.accounts.new_account.data = data;
        msg!("Changed data to: {}!", data); // Message will show up in the tx logs
        Ok(())
    }
}

You can see a complete example on Playground here: https://beta.solpg.io/6310e05288a7fca897ad7d0f

If you change the pubkey! to your playground wallet address (shown at the bottom of the UI) and deploy, you'll be able to call that initialize instruction from the test UI.

If you change the pubkey! in the code and re-deploy (or change the signer in the instruction call) it'll fail with the Unauthorized message.

3

A neat way to initialize constant Pubkeys in an organized way.

Lib.rs

// Program Id
declare_id!("e8zpvHybTbjMjoDR7CWjBUj1ttxQwRMUebhAf2z52ba");

mod pubkeys {
    use anchor_lang::prelude::*;

    // User Publickey
    pub mod user {
        use super::*;
        declare_id!("a8zpvHybTbjMjoDR7CWjBUj1ttxQwRMUebhAf2z5aaa");
    }

    // Vault Publickey
    pub mod vault {
        use super::*;
        declare_id!("b8zpvHybTbjMjoDR7CWjBUj1ttxQwRMUebhAf2z5bbb");
    }
}

Usage

use crate::*;

msg!("{}", ID)                   // prints Program Id
msg!("{}", pubkeys::user::ID);   // user User Address
msg!("{}", pubkeys::vault::ID);  // vault Vault Address

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.