1
1
use anchor_lang:: prelude:: * ;
2
+ use anchor_lang:: solana_program:: sysvar:: instructions:: get_instruction_relative;
2
3
3
4
declare_id ! ( "CmP2djJgABZ4cRokm4ndxuq6LerqpNHLBsaUv2XKEJua" ) ;
4
5
@@ -7,15 +8,22 @@ pub mod bolt_component {
7
8
use super :: * ;
8
9
9
10
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
+ }
18
25
}
26
+
19
27
ctx. accounts . data . bolt_metadata . authority = * ctx. accounts . authority . key ;
20
28
Ok ( ( ) )
21
29
}
@@ -47,14 +55,19 @@ pub mod bolt_component {
47
55
}
48
56
49
57
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
+ }
58
71
}
59
72
Ok ( ( ) )
60
73
}
@@ -118,3 +131,11 @@ pub struct Position {
118
131
pub struct BoltMetadata {
119
132
pub authority : Pubkey ,
120
133
}
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