Solana: Having any pubkey as signer for a function

Here is an example article about creating a function with any pubkey as a signer for a function on Solana:

Creating a function with any Pubkey as a signer on Solana

In the blockchain world, having different types of accounts (or “signers”) can be crucial in building complex programs. One common scenario is when you want to create a function that requires two or more signers to confirm its execution. In this article, we’ll explore how to achieve this on Solana using Anchor.

Basics

Before we dive into the code, let’s quickly cover some essential concepts:

  • A signer' is an account that has a private key (also known as a "pubkey") and can be used to sign messages or contracts.

  • In Anchor, you do not need to specify the type of signer in your program. Instead, you will use thedeclare_id!macro for the declaration.

Example code

Here's an example code snippet that shows how to create a function with any pubkey as a signer:


use anchor_lang::prelude::*;

declare_id!("5Fb2dXrY8jW4K9yfB6JhZz1aPpUu3oK9kqCZcR7eJLs");

#[program]

pub fn create_function(

#[-parameter]

pub new_value: string,

#[parameter]

pub pubkey1: Pubkey,

#[parameter]

pub pubkey2: Pubkey,

) -> Result<(), Error> {

let them close their accounts = [

Signer::new(&pubkey1, 1),

Signer::new(&pubkey2, 1),

];

let (address, account) = self.signer_sign_out(accounts)?;

// Now we can use the signed address and account to call our function

#[allow(dead_code)]

pub fn my_function(

#[param]

param_value: string,

) -> Result {

let result = Account::call(&address, "my_function", ¶m_value)?;

OK (result)

}

}

In this example, we created a create_function'' program that takes three parameters:

  • new_value: the string that our function will return

  • pubkey1andpubkey2: these are the two public keys. In Anchor, you can use any pubkey as a signer for your functions.

  • The functionsigner_sign_outreturns a tuple(address, account), whereaddressis the signed address andaccountis the signed account.

When we call our functionmy_function, we passparam_value: “hello”. Sincepubkey1andpubkey2are any pubkey as a signer, we can use them to sign this parameter value. The functionAccount::callreturns a result of typeResult, indicating whether the call was successful.

Conclusion

Solana: Having any pubkey as signer for a function

In this article, we explored how to create a function with any pubkey as a signer on Solana using Anchor. By exploiting thedeclare_id!macro and usingSigner::new` to create a signer, you can write functions that require multiple signers to confirm their execution. Remember to protect your code by following best practices for signing and verifying signatures.

Hope this helps! Let me know if you have any questions or need further clarification on any of the concepts discussed in this article.

Leave a Reply

Your email address will not be published. Required fields are marked *