2

Say I have an account in Program A, and I know it looks like this:

#[account(zero_copy)]
pub struct SomeAcc {
    pub some_num: u32,
}

Now in my Program B, I copy and paste this struct exactly into my new codebase. Let's say I have no access to Program A's source code other than that I know this struct. Now I want to access a SomeAcc created from Program A in Program B

#[derive(Accounts)]
pub struct GetSomeAcc<'info> {
    #[account()]
    pub acc: AccountLoader<'info, SomeAcc>,
}

pub fn handler(ctx: Context<GetSomeAcc>) -> Result<()> {
    let acc = ctx.accounts.acc.load()?;
    msg!("acc val {:?}", acc.some_num);
}

This will give me AccountOwnedByWrongProgram, because Program A created that account. So how can I tell AccountLoader to ignore the program ownership check and try to deserialize anyways?

2 Answers 2

2

Best approach I have is to accept the external struct as AccountInfo and parse the bytes with bytemuck, but this is much less ergonomic than AccountLoader:

#[derive(Accounts)]
pub struct GetSomeAcc<'info> {
    /// CHECK: no checks
    #[account()]
    pub acc: AccountInfo<'info>,
}
pub fn handler(ctx: Context<GetSomeAcc>) -> Result<()> {
    // Get the raw data and remove the 8 byte anchor discriminator...
    let acc_data = &ctx.accounts.acc.try_borrow_data()?[..][8..];
    let acc: &SomeAcc = get_some_acc_from_bytes(acc_data);
    msg!("acc val {:?}", acc.some_num);
}
pub fn get_some_acc_from_bytes(v: &[u8]) -> &SomeAcc{
    bytemuck::from_bytes(v)
}
2

If you redefine the struct in your program, Anchor will automatically assume that it belongs to your program, and check that your program owns it on deserialization, which is causing your failure.

If you want to reuse the struct, you'll need to import the program's crate into your program, ie:

use other_program::SomeAcc;
2
  • Many programs don't have a public crate, so this is unfortunate.
    – Whiteseal
    Commented Feb 21, 2023 at 18:56
  • That's absolutely true -- feel free to push them to open-source! You can also publish the crate yourself if needed.
    – Jon C
    Commented Feb 21, 2023 at 19:01

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.