@@ -1317,6 +1317,9 @@ pub fn build(
13171317 check_anchor_version ( & cfg) . ok ( ) ;
13181318 check_deps ( & cfg) . ok ( ) ;
13191319
1320+ // Check for program ID mismatches before building
1321+ check_program_id_mismatch ( & cfg, program_name. clone ( ) ) ?;
1322+
13201323 let idl_out = match idl {
13211324 Some ( idl) => Some ( PathBuf :: from ( idl) ) ,
13221325 None => Some ( cfg_parent. join ( "target" ) . join ( "idl" ) ) ,
@@ -4236,6 +4239,51 @@ fn keys_sync(cfg_override: &ConfigOverride, program_name: Option<String>) -> Res
42364239 } )
42374240}
42384241
4242+ /// Check if there's a mismatch between the program keypair and the `declare_id!` in the source code.
4243+ /// Returns an error if a mismatch is detected, prompting the user to run `anchor keys sync`.
4244+ fn check_program_id_mismatch ( cfg : & WithPath < Config > , program_name : Option < String > ) -> Result < ( ) > {
4245+ let declare_id_regex = RegexBuilder :: new ( r#"^(([\w]+::)*)declare_id!\("(\w*)"\)"# )
4246+ . multi_line ( true )
4247+ . build ( )
4248+ . unwrap ( ) ;
4249+
4250+ for program in cfg. get_programs ( program_name) ? {
4251+ // Get the pubkey from the keypair file
4252+ let actual_program_id = program. pubkey ( ) ?. to_string ( ) ;
4253+
4254+ // Check declaration in program files
4255+ let src_path = program. path . join ( "src" ) ;
4256+ let files_to_check = vec ! [ src_path. join( "lib.rs" ) , src_path. join( "id.rs" ) ] ;
4257+
4258+ for path in files_to_check {
4259+ let content = match fs:: read_to_string ( & path) {
4260+ Ok ( content) => content,
4261+ Err ( _) => continue ,
4262+ } ;
4263+
4264+ let incorrect_program_id = declare_id_regex
4265+ . captures ( & content)
4266+ . and_then ( |captures| captures. get ( 3 ) )
4267+ . filter ( |program_id_match| program_id_match. as_str ( ) != actual_program_id) ;
4268+
4269+ if let Some ( program_id_match) = incorrect_program_id {
4270+ let declared_id = program_id_match. as_str ( ) ;
4271+ return Err ( anyhow ! (
4272+ "Program ID mismatch detected for program '{}':\n \
4273+ Keypair file has: {}\n \
4274+ Source code has: {}\n \n \
4275+ Please run 'anchor keys sync' to update the program ID in your source code.",
4276+ program. lib_name,
4277+ actual_program_id,
4278+ declared_id
4279+ ) ) ;
4280+ }
4281+ }
4282+ }
4283+
4284+ Ok ( ( ) )
4285+ }
4286+
42394287fn localnet (
42404288 cfg_override : & ConfigOverride ,
42414289 skip_build : bool ,
0 commit comments