Best practices for setting up PDAs in the Solana Anchor framework

Trying to create a basic Solana Program using Rust/Anchor that involves a PDA is causing a CPI error upon invocation, even though there doesn't appear to be any CPI happening (possibly due to the PDA account initialization).

Below is the Program code:

use anchor_lang::prelude::*;

declare_id!("51v31qHaEQniLoYuvvtXByZcfiyvog3R2EKC39EPD52p");

#[program]
pub mod solana_sandbox {
  use super::*;
  pub fn initialize(ctx: Context<Initialize>, bump: u8) -> ProgramResult {
    ctx.accounts.sandbox_account.bump = bump;
    Ok(())
  }
}

#[derive(Accounts)]
#[instruction(bump: u8)]
pub struct Initialize<'info> {
  #[account(mut)]
  pub signer: Signer<'info>,
  #[account(
    init,
    seeds = [b"seed".as_ref()],
    bump,
    payer = signer,
  )]
  pub sandbox_account: Account<'info, SandboxAccount>,
  pub system_program: Program<'info, System>,
}

#[account]
#[derive(Default)]
pub struct SandboxAccount {
  pub bump: u8,
}

And here is the client-side code:

const [sandboxPda, sandboxBump] = await PublicKey.findProgramAddress([Buffer.from('seed')], SystemProgram.programId);

await program.rpc.initialize(
sandboxBump,
{
accounts: {
signer: keypair.publicKey,
sandboxAccount: sandboxPda,
systemProgram: anchor.web3.SystemProgram.programId,
},
signers: [keypair],
instructions: []
});

Upon running the above, the following error occurs:

Transaction simulation failed: Error processing Instruction 0: Cross-program invocation with unauthorized signer or writable account 
    Program 51v31qHaEQniLoYuvvtXByZcfiyvog3R2EKC39EPD52p invoke [1]
    8ZiyjNgnFFPyw39NyMQE5FGETTjyUhSHUVQG3oKAFZiU's signer privilege escalated
    Program 51v31qHaEQniLoYuvvtXByZcfiyvog3R2EKC39EPD52p consumed 200000 of 200000 compute units
    Program 51v31qHaEQniLoYuvvtXByZcfiyvog3R2EKC39EPD52p failed: Cross-program invocation with unauthorized signer or writable account

The PDA address being used is

8ZiyjNgnFFPyw39NyMQE5FGETTjyUhSHUVQG3oKAFZiU
, and anchor-cli 0.18.0 is in use.

Answer №1

It appears that my mistake was using the System Program ID instead of my actual Program ID to generate the PDA in my client code.

The correct approach should be:

  const [sandboxPda, sandboxBump] = await PublicKey.findProgramAddress([Buffer.from('seed')], <PROGRAM_ID>);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for exporting all functions from a TypeScript file with a default export included?

An example of the export type mentioned is React. To use it, we can include the following code: import React, {Component} from "react". This allows us to access both React.Component and Component. What steps are necessary to make this possible? ...

What is preventing me from applying styles to the first word in my Angular ngFor iteration?

I'm currently attempting to customize the initial word of a string within my Angular ngFor loop. Strangely, the class gets applied but the style defined in my CSS file is not. Inline styling also does not seem to work - any ideas why? This is the CSS ...

Completion of TypeScript code is not working as expected, the variable that is dependent upon is not

Looking for assistance with creating code completion in TypeScript. Variable.Append1 Variable.Append2 Variable.Append3 I have defined the following class: class Variable { Append1(name: string){ if (name == undefined) ...

Having trouble with a tslint error in Typescript when creating a reducer

I encountered an error while working with a simple reducer in ngRx, specifically with the on() method. https://i.sstatic.net/9fsvj.png In addition, I came across some errors in the reducer_creator.d.ts file: https://i.sstatic.net/sWvMu.png https://i.ss ...

What steps should I take to resolve the issue of 'unable to locate the name 'OktaAuthService' error?

I am currently trying to incorporate authentication into an Angular application using Okta. I have carefully followed the step-by-step instructions provided in the documentation at this link: . However, I am encountering an error when attempting to start t ...

What is the best way to modify specific data retrieved from an API using Angular?

After successfully listing some data from an API using ngFor, I am facing an issue with editing the data. Whenever I click the edit button, it edits the entire data instead of just the specific row. Below is the code snippet for reference: HTML <table ...

Accessing Webpack bundles using an "@" symbol for imports

I am currently working on bundling a Node Express server that was created using TypeScript and is being packaged with Webpack. Everything seems to be running smoothly when I compile/transpile the code into one JavaScript file called server.js. However, af ...

How to pass a String Array to a String literal in JavaScript

I need to pass an array of string values to a string literal in the following way Code : var arr = ['1','2556','3','4','5']; ... ... var output = ` <scr`+`ipt> window.stringArray = [`+ arr +`] & ...

The user's type from express-session is not being properly detected by Typescript

I have a process where I retrieve the user object from the database and set it on the express-session: export const postLogin = async ( request: Request, response: Response, next: NextFunction ): Promise<void> => { try { re ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

The error message "better-sqlite3 TypeError: o.default is not a constructor" indicates that

As part of my vscode extension development in typescript, webpack, and better-sqlite3, I am attempting to create a database within the C:\Users\userName\AppData\Roaming\Code\User\globalStorage\ folder. However, when ...

Encountered an issue while trying to access Hyperledger explorer: "Error: Unable to retrieve the requested page /

I have successfully set up our Fabric network (v1.4) with the latest version of Explorer. node --version v8.16.0 The database log shows no errors, and there are no application-level errors. The Explorer syncing process for the network is running continuo ...

Utilizing flatMap to implement nested service calls with parameters

Recently, I encountered an issue while working on a service call to retrieve data from a JSON file containing multiple items. After fetching all the items, I needed to make another service call to retrieve the contents of each item. I tried using flatMap f ...

How to retrieve the value of an input field in Angular 2/Typescript without using ngModel

Currently, I'm utilizing Typescript in conjunction with Angular2, mirroring the structure of the Angular2 Tour of Heroes guide. There is a specific input field that I aim to associate a change event with, triggering custom logic whenever the value wi ...

Using TypeScript to destructure by providing types

I encountered an issue while trying to destructure some code. The error message Property 'name' does not exist on type '{}'. is appearing. I thought about using let user:any = {}; as a workaround, but that goes against the eslint rule o ...

Can anyone guide me on implementing getServerSideProps in a TypeScript NextPage component?

I've come across a page that I'd like to replicate, with the code sourced from https://github.com/dabit3/nextjs-lit-token-gating/blob/main/pages/protected.js: import Cookies from 'cookies' import LitJsSdk from 'lit-js-sdk' ex ...

Maintaining the selected option on page refresh with React Remix

I have a dropdown menu with 2 choices (en, no) for switching the language when onChange event occurs. To save the selected language, I am using localStorage. Due to the server-side rendering in Remix, direct access to localStorage is not possible. Therefo ...

Sorting List Algorithm

Looking to create an algorithm in Node.js that abides by specific rules. It takes a series of numbers as input and the maximum consecutive number before taking a break. The logic is as follows: The rules : Only one competition per day Competitions are hel ...

Console.log is displaying array as [object Object] when utilizing Typescript

When working with an object in typescript called "obj," I encountered a strange behavior. Initially, when I ran the console.log(obj); command, the output in the terminal console was displayed as [object Object]. However, after wrapping it in JSON.stringify ...

Ensuring the correct type for an object's interface property value

I am currently working on defining a new interface interface SUser { ID: number; NAME: string; MAIL: string; PASSWORD: string; GENDER: number; BIRTHDATE: string; ID_FB: string; CREDIT: number; ID_REFERRAL: number; } My objective is to c ...