0

"In my contract, I require the implementation of an owner role, creating what is commonly known as an 'ownable' contract pattern. This entails the inclusion of three key functions within my contract:

  1. initialize_owner: This function is called once during the contract's initialization. The caller of this function becomes the initial owner.

  2. set_new_owner: Only the initial owner can call this function, and it allows the setting of a new owner by providing a new public key.

  3. renounce_ownership: Only the current owner can invoke this function, resulting in the owner being set to the default address '11111111111111111111111111111111', effectively renouncing ownership.

Additionally, I need a mechanism to retrieve the owner's address within the code, facilitating validation checks to determine if a particular method is being called by the admin.

Could you please provide examples or solutions for implementing these requirements?"

1 Answer 1

3

Unlike Solidity contracts, Solana programs are stateless. Accounts hold the state of solana programs. Hence, the concept of "ownership" is valid only for accounts not for programs itself.

By default init sets the owner field of the created account to the currently executing program. You must add the owner constraint to specify a different program owner.

Here's a simple example:

#[program]
pub mod anchor_example {
    use anchor_lang::solana_program::entrypoint::ProgramResult;

    use super::*;
    pub fn create_pool(ctx: Context<CreatePool>) -> ProgramResult {
        let pool = &mut ctx.accounts.pool_account;
        pool.id = 1;
        pool.owner = *ctx.accounts.user.key;
        Ok(())
    }
 
}

#[derive(Accounts)]
pub struct CreatePool<'info> {
   #[account(init, payer = user, owner = user.key(), space = 8 + 40 )]
    pub pool_account: Account<'info, Pool>,
    #[account(mut)]
    pub user: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
pub struct Pool {
    pub id: u64,
}

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.