1

I currently have a PDA account with the following structure:

#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct NewFoo {
    pub foo_id: String,
}

#[derive(Accounts)]
#[instruction(new_foo: NewFoo)]
pub struct CreateFoo<'info> {
    #[account(
      init,
      space = 8 + Foo::INIT_SPACE,
      payer = sender,
      seeds = [
        FOO_SEED.as_bytes(),
        new_foo.foo_id.as_bytes(),
      ],
      bump,
    )]
    pub foo: Account<'info, Foo>,

With this setup, the compiled IDL structure of the PDA account looks like this:

  {
    "name": "foo",
    "writable": true,
    "pda": {
      "seeds": [
        {
          "kind": "const",
          "value": [
            83,
            116,
            97,
            116,
            101,
            109,
            101,
            110,
            116
          ]
        },
        {
          "kind": "arg",
          "path": "new_foo.foo_id"
        }
      ]
    }
  }

However, I modified the CreateFoo structure to use a hash function to generate one of the seeds. The updated structure is as follows:

use anchor_lang::{prelude::*, solana_program::hash::hash};

#[derive(Accounts)]
#[instruction(new_foo: NewFoo)]
pub struct CreateFoo<'info> {
    #[account(
      init,
      space = 8 + Foo::INIT_SPACE,
      payer = sender,
      seeds = [
        FOO_SEED.as_bytes(),
        &hash(&new_foo.foo_id.as_bytes()).to_bytes()[..], // changed this line
      ],
      bump,
    )]
    pub foo: Account<'info, Foo>,

After this change, I noticed that the compiled IDL structure no longer represents a PDA account. Instead, it appears as a regular account:

{
    "name": "foo",
    "writable": true,
}

My questions are:

  1. Is it correct for a PDA account generated using a hash function to compile like this? Are there any risks with this approach?
  2. Can a hash function be used to generate a seed for a PDA account? If yes, is this a common practice?

I appreciate any insights or guidance you can provide on this. Thank you in advance for your help and time!

1 Answer 1

0
  1. I'm not sure what Anchor does exactly to extract the IDL, but it seems suspicious that it doesn't give more info. I imagine something is going wrong during IDL extraction.
  2. You can use a hash function if you want, but I wouldn't encourage it. The PDA generation code itself is already hashing together all of the seeds, so that adds an additional hash step, which is compute-intensive when executed on-chain.

You can read more about PDA generation at https://solana.com/developers/courses/native-onchain-development/program-derived-addresses#3-create-program-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.