I am calling a solana program A from solana program B using cpi invokes. Is there a way to get the program id of program B on program A or a way to get the cpi is invoked?
2 Answers
The information about the caller program is not provided to a callee program during CPI, but there's a workaround. You could verify the caller program id by:
- including the caller program id as instruction data
- requiring any caller program to sign with a PDA
Then your program needs to check that the PDA address is correctly derived based on the instruction data, and that the account is provided as a signer to your program.
-
Hi I am using pda seeds to sign the transaction, also marked the pda account of target program as signer but getting error
Cross-program invocation with unauthorized signer or writable account
Commented May 22 at 16:32 -
-
Certainly! Let's assume that your program takes the caller program id as instruction data, and there's also a PDA provided to your program. You would check that the PDA is a signer, and that its address is equal to
find_program_address(["some_seed_required_by_your_program"], program_id_in_instruction_data)
– Jon CCommented May 22 at 20:52 -
I got it but my doubt is how to make PDA as signer, I tried using
#[account(signer)]
on top of my pda this way#[account(signer, seeds = [some_seeds], bump)] my_pda: Account<'info, Some_Struct>
, but I am gettingCross-program invocation with unauthorized signer or writable account
error although I check the bump is correct Commented May 23 at 10:33 -
That should be roughly correct, feel free to take a working example and adapt it for your needs, like github.com/coral-xyz/anchor/tree/master/examples/tutorial/…– Jon CCommented May 23 at 10:55
If you are using Anchor, you can get your program ID from the accounts context using
ctx.program_id
For native programs you have to pass in the program ID, which you can in your process_instruction
function
You get this address after building your project with cargo build-sbf
command, and getting the public key by reading the deployment keypair in the /target/deploy
folder
This is the command to get the public key
solana address -k keypair-file.json
-
Hi
ctx.program_id
in program A is returning program A's program_id, although I am calling program A's function with program's B, my question is how to get program B program_id on program A will cpi invoking Commented May 20 at 11:39 -
you need to pass in the program_id in the accounts struct. No other way of doing this.– JimiiCommented May 20 at 11:54
-
and how it can be guaranteed that someone has not passed just program_id as correct and other details as something else, means how can it be validated that the user is authenticated, Program C can be created and program id of B can be passed and for Program A, the call will be coming from Program B? Commented May 20 at 15:37