Skip to content

Commit 51432c7

Browse files
fix: 🐛 Components CPI caller check
1 parent afd4fca commit 51432c7

File tree

1 file changed

+37
-16
lines changed
  • programs/bolt-component/src

1 file changed

+37
-16
lines changed

programs/bolt-component/src/lib.rs

+37-16
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use anchor_lang::prelude::*;
2+
use anchor_lang::solana_program::sysvar::instructions::get_instruction_relative;
23

34
declare_id!("CmP2djJgABZ4cRokm4ndxuq6LerqpNHLBsaUv2XKEJua");
45

@@ -7,15 +8,22 @@ pub mod bolt_component {
78
use super::*;
89

910
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
10-
let instruction =
11-
anchor_lang::solana_program::sysvar::instructions::get_instruction_relative(
12-
0,
13-
&ctx.accounts.instruction_sysvar_account.to_account_info(),
14-
)
15-
.unwrap();
16-
if instruction.program_id == id() {
17-
panic!("The instruction must be called from a CPI");
11+
// Check if the program is called via CPI
12+
match get_instruction_relative(
13+
-1,
14+
&ctx.accounts.instruction_sysvar_account.to_account_info(),
15+
) {
16+
Ok(instruction) => {
17+
// Verify the caller's program ID, if necessary
18+
if instruction.program_id != ctx.accounts.authority.key() {
19+
return Err(ErrorCode::UnauthorizedCaller.into());
20+
}
21+
}
22+
Err(_) => {
23+
return Err(ErrorCode::MustBeCalledViaCpi.into());
24+
}
1825
}
26+
1927
ctx.accounts.data.bolt_metadata.authority = *ctx.accounts.authority.key;
2028
Ok(())
2129
}
@@ -47,14 +55,19 @@ pub mod bolt_component {
4755
}
4856

4957
pub fn update(ctx: Context<Update>, _data: Vec<u8>) -> Result<()> {
50-
let instruction =
51-
anchor_lang::solana_program::sysvar::instructions::get_instruction_relative(
52-
0,
53-
&ctx.accounts.instruction_sysvar_account.to_account_info(),
54-
)
55-
.unwrap();
56-
if instruction.program_id == id() {
57-
panic!("The instruction must be called from a CPI");
58+
// Same CPI check as in initialize
59+
match get_instruction_relative(
60+
-1,
61+
&ctx.accounts.instruction_sysvar_account.to_account_info(),
62+
) {
63+
Ok(instruction) => {
64+
if instruction.program_id != ctx.accounts.authority.key() {
65+
return Err(ErrorCode::UnauthorizedCaller.into());
66+
}
67+
}
68+
Err(_) => {
69+
return Err(ErrorCode::MustBeCalledViaCpi.into());
70+
}
5871
}
5972
Ok(())
6073
}
@@ -118,3 +131,11 @@ pub struct Position {
118131
pub struct BoltMetadata {
119132
pub authority: Pubkey,
120133
}
134+
135+
#[error_code]
136+
pub enum ErrorCode {
137+
#[msg("The instruction must be called from a CPI")]
138+
MustBeCalledViaCpi,
139+
#[msg("Unauthorized caller program")]
140+
UnauthorizedCaller,
141+
}

0 commit comments

Comments
 (0)