1use {
4 crate::{
5 error::MetadataError,
6 find_attributes_pda_with_program, find_metadata_pda_with_program,
7 instruction::MetadataInstruction,
8 state::{
9 TokenMetadata, TokenMetadataAttributes, DESCRIPTION_MAX_LEN, IMAGE_MAX_LEN,
10 MAX_ATTRIBUTES, MAX_KEY_LENGTH, MAX_VALUE_LENGTH, NAME_MAX_LEN, SYMBOL_MAX_LEN,
11 },
12 ATTRIBUTES_SEED, METADATA_SEED,
13 },
14 apl_token::{self, state::Mint},
15 arch_program::{
16 account::{next_account_info, AccountInfo},
17 entrypoint::ProgramResult,
18 input_to_sign::InputToSign,
19 msg,
20 program::{invoke, invoke_signed, set_input_to_sign},
21 program_error::ProgramError,
22 program_option::COption,
23 program_pack::{IsInitialized, Pack},
24 pubkey::Pubkey,
25 rent::minimum_rent,
26 system_instruction,
27 },
28};
29
30pub struct Processor {}
32
33impl Processor {
34 pub fn process(
36 program_id: &Pubkey,
37 accounts: &[AccountInfo],
38 instruction_data: &[u8],
39 ) -> ProgramResult {
40 let instruction = MetadataInstruction::unpack(instruction_data)?;
41
42 match instruction {
43 MetadataInstruction::CreateMetadata {
44 name,
45 symbol,
46 image,
47 description,
48 immutable,
49 } => Self::process_create_metadata(
50 program_id,
51 accounts,
52 name,
53 symbol,
54 image,
55 description,
56 immutable,
57 ),
58 MetadataInstruction::UpdateMetadata {
59 name,
60 symbol,
61 image,
62 description,
63 } => Self::process_update_metadata(accounts, name, symbol, image, description),
64 MetadataInstruction::CreateAttributes { data } => {
65 Self::process_create_attributes(program_id, accounts, data)
66 }
67 MetadataInstruction::ReplaceAttributes { data } => {
68 Self::process_replace_attributes(program_id, accounts, data)
69 }
70
71 MetadataInstruction::TransferAuthority { new_authority } => {
72 Self::process_transfer_authority(accounts, new_authority)
73 }
74
75 MetadataInstruction::MakeImmutable => Self::process_make_immutable(accounts),
76 MetadataInstruction::Anchor {
77 input_index,
78 input_signer,
79 } => {
80 msg!("Instruction: Anchor");
81 Self::process_anchor(program_id, accounts, input_index, input_signer)
82 }
83 }
84 }
85
86 fn process_create_metadata(
87 program_id: &Pubkey,
88 accounts: &[AccountInfo],
89 name: String,
90 symbol: String,
91 image: String,
92 description: String,
93 immutable: bool,
94 ) -> ProgramResult {
95 let account_info_iter = &mut accounts.iter();
96 let payer_info = next_account_info(account_info_iter)?; let system_program_info = next_account_info(account_info_iter)?; let mint_info = next_account_info(account_info_iter)?; let metadata_info = next_account_info(account_info_iter)?; let mint_authority_info = next_account_info(account_info_iter)?; if mint_info.owner != &apl_token::id() {
104 msg!(
105 "Mint is not owned by the token program expected {:?}, got {:?}",
106 apl_token::id(),
107 mint_info.owner
108 );
109 return Err(ProgramError::IncorrectProgramId);
110 }
111
112 let mint = Mint::unpack(&mint_info.data.borrow()) .map_err(|_| ProgramError::InvalidAccountData)?;
115
116 if !mint.is_initialized() {
117 msg!("Mint is not initialized");
118 return Err(ProgramError::UninitializedAccount);
119 }
120
121 let matched_signer: Option<Pubkey> = match mint.mint_authority {
123 COption::Some(mint_auth) => {
124 if cmp_pubkeys(&mint_auth, mint_authority_info.key) {
125 Some(mint_auth)
126 } else {
127 msg!("Mint authority does not match expected authority");
128 return Err(MetadataError::InvalidAuthority.into());
129 }
130 }
131 COption::None => match mint.freeze_authority {
132 COption::Some(freeze_auth) => {
133 if cmp_pubkeys(&freeze_auth, mint_authority_info.key) {
134 Some(freeze_auth)
135 } else {
136 msg!("Freeze authority does not match expected authority");
137 return Err(MetadataError::InvalidAuthority.into());
138 }
139 }
140 COption::None => {
141 msg!("Mint has no mint or freeze authority");
142 return Err(MetadataError::InvalidAuthority.into());
143 }
144 },
145 };
146
147 if !mint_authority_info.is_signer {
149 msg!("Mint authority is not a signer");
150 return Err(MetadataError::InvalidAuthority.into());
151 }
152
153 let (expected_md_pda, md_bump) = find_metadata_pda_with_program(program_id, mint_info.key);
155 if !cmp_pubkeys(&expected_md_pda, metadata_info.key) {
156 msg!("Metadata PDA does not match expected PDA");
157 return Err(ProgramError::InvalidSeeds);
158 }
159
160 if name.len() > NAME_MAX_LEN
162 || symbol.len() > SYMBOL_MAX_LEN
163 || image.len() > IMAGE_MAX_LEN
164 || description.len() > DESCRIPTION_MAX_LEN
165 {
166 msg!(
167 "Metadata field size is too long: name={}/{}, symbol={}/{}, image={}/{}, description={}/{}",
168 name.len(),
169 NAME_MAX_LEN,
170 symbol.len(),
171 SYMBOL_MAX_LEN,
172 image.len(),
173 IMAGE_MAX_LEN,
174 description.len(),
175 DESCRIPTION_MAX_LEN,
176 );
177 return Err(MetadataError::StringTooLong.into());
178 }
179
180 if metadata_info.owner != program_id {
182 if *system_program_info.key != Pubkey::system_program() {
184 msg!("System program id does not match expected system program id");
185 return Err(ProgramError::IncorrectProgramId);
186 }
187
188 if !payer_info.is_signer {
189 msg!("Payer is not a signer");
190 return Err(ProgramError::MissingRequiredSignature);
191 }
192
193 create_or_adopt_pda(
194 payer_info,
195 metadata_info,
196 system_program_info,
197 TokenMetadata::LEN,
198 program_id,
199 &[METADATA_SEED, mint_info.key.as_ref(), &[md_bump]],
200 )?;
201 }
202
203 {
205 let data_ref = metadata_info.data.borrow();
206 if !data_ref.is_empty() && data_ref[0] != 0 {
207 return Err(MetadataError::MetadataAlreadyExists.into());
208 }
209 }
210
211 let metadata = TokenMetadata {
213 is_initialized: true,
214 mint: *mint_info.key,
215 name,
216 symbol,
217 image,
218 description,
219 update_authority: if immutable { None } else { matched_signer },
220 };
221
222 metadata.pack_into_slice(&mut metadata_info.data.borrow_mut());
223
224 Ok(())
225 }
226
227 fn process_update_metadata(
228 accounts: &[AccountInfo],
229 name: Option<String>,
230 symbol: Option<String>,
231 image: Option<String>,
232 description: Option<String>,
233 ) -> ProgramResult {
234 let account_info_iter = &mut accounts.iter();
235 let metadata_info = next_account_info(account_info_iter)?; let update_authority_info = next_account_info(account_info_iter)?; if !update_authority_info.is_signer {
239 msg!("Update authority is not a signer");
240 return Err(ProgramError::MissingRequiredSignature);
241 }
242
243 let mut metadata = TokenMetadata::unpack(&metadata_info.data.borrow())
245 .map_err(|_| ProgramError::InvalidAccountData)?;
246
247 if !metadata.is_initialized() {
248 msg!("Metadata not initialized");
249 return Err(ProgramError::UninitializedAccount);
250 }
251
252 match metadata.update_authority {
254 Some(current_auth) => {
255 if !cmp_pubkeys(¤t_auth, update_authority_info.key) {
256 msg!("Update authority does not match");
257 return Err(MetadataError::InvalidAuthority.into());
258 }
259 }
260 None => {
261 msg!("Metadata is immutable");
262 return Err(MetadataError::InvalidAuthority.into());
263 }
264 }
265
266 if let Some(ref n) = name {
268 if n.len() > NAME_MAX_LEN {
269 return Err(MetadataError::StringTooLong.into());
270 }
271 }
272 if let Some(ref s) = symbol {
273 if s.len() > SYMBOL_MAX_LEN {
274 return Err(MetadataError::StringTooLong.into());
275 }
276 }
277 if let Some(ref i) = image {
278 if i.len() > IMAGE_MAX_LEN {
279 return Err(MetadataError::StringTooLong.into());
280 }
281 }
282 if let Some(ref d) = description {
283 if d.len() > DESCRIPTION_MAX_LEN {
284 return Err(MetadataError::StringTooLong.into());
285 }
286 }
287
288 if let Some(n) = name {
289 metadata.name = n;
290 }
291 if let Some(s) = symbol {
292 metadata.symbol = s;
293 }
294 if let Some(i) = image {
295 metadata.image = i;
296 }
297 if let Some(d) = description {
298 metadata.description = d;
299 }
300
301 metadata.pack_into_slice(&mut metadata_info.data.borrow_mut());
302 Ok(())
303 }
304
305 fn process_create_attributes(
306 program_id: &Pubkey,
307 accounts: &[AccountInfo],
308 data: Vec<(String, String)>,
309 ) -> ProgramResult {
310 let account_info_iter = &mut accounts.iter();
311 let payer_info = next_account_info(account_info_iter)?; let system_program_info = next_account_info(account_info_iter)?; let mint_info = next_account_info(account_info_iter)?; let attributes_info = next_account_info(account_info_iter)?; let update_authority_info = next_account_info(account_info_iter)?; let metadata_info = next_account_info(account_info_iter)?; if !payer_info.is_signer || !update_authority_info.is_signer {
319 return Err(ProgramError::MissingRequiredSignature);
320 }
321
322 if mint_info.owner != &apl_token::id() {
323 return Err(ProgramError::IncorrectProgramId);
324 }
325 Mint::unpack(&mint_info.data.borrow())?;
326
327 let (expected_attrs_pda, attrs_bump) =
329 find_attributes_pda_with_program(program_id, mint_info.key);
330 if !cmp_pubkeys(&expected_attrs_pda, attributes_info.key) {
331 msg!("Attributes PDA does not match expected PDA");
332 return Err(ProgramError::InvalidSeeds);
333 }
334
335 if metadata_info.owner != program_id {
337 return Err(ProgramError::IncorrectProgramId);
338 }
339 let (expected_metadata_pda, _) = find_metadata_pda_with_program(program_id, mint_info.key);
340 if metadata_info.key != &expected_metadata_pda {
341 return Err(ProgramError::InvalidSeeds);
342 }
343 let metadata = TokenMetadata::unpack(&metadata_info.data.borrow())
344 .map_err(|_| ProgramError::InvalidAccountData)?;
345 if !metadata.is_initialized() || !cmp_pubkeys(&metadata.mint, mint_info.key) {
346 msg!("Metadata not initialized or mint mismatch");
347 return Err(ProgramError::InvalidAccountData);
348 }
349
350 match metadata.update_authority {
351 Some(current_auth) => {
352 if !cmp_pubkeys(¤t_auth, update_authority_info.key) {
353 msg!("Update authority does not match");
354 return Err(MetadataError::InvalidAuthority.into());
355 }
356 }
357 None => {
358 msg!("Metadata is immutable");
359 return Err(MetadataError::InvalidAuthority.into());
360 }
361 }
362
363 if data.len() > MAX_ATTRIBUTES {
365 msg!("Too many attributes: {} > {}", data.len(), MAX_ATTRIBUTES);
366 return Err(MetadataError::TooManyAttributes.into());
367 }
368 for (k, v) in &data {
369 if k.is_empty() || v.is_empty() {
370 msg!("Attribute key and value must be non-empty");
371 return Err(MetadataError::InvalidInstructionData.into());
372 }
373 if k.len() > MAX_KEY_LENGTH || v.len() > MAX_VALUE_LENGTH {
374 msg!(
375 "Attribute key or value is too long: key={}/{}, value={}/{}",
376 k.len(),
377 MAX_KEY_LENGTH,
378 v.len(),
379 MAX_VALUE_LENGTH,
380 );
381 return Err(MetadataError::StringTooLong.into());
382 }
383 }
384
385 let required_space: u64 = TokenMetadataAttributes::LEN as u64;
387
388 if attributes_info.owner != program_id {
389 if *system_program_info.key != Pubkey::system_program() {
390 msg!("System program id does not match expected system program id");
391 return Err(ProgramError::IncorrectProgramId);
392 }
393 if !payer_info.is_signer {
394 msg!("Payer is not a signer");
395 return Err(ProgramError::MissingRequiredSignature);
396 }
397 create_or_adopt_pda(
398 payer_info,
399 attributes_info,
400 system_program_info,
401 TokenMetadataAttributes::LEN,
402 program_id,
403 &[ATTRIBUTES_SEED, mint_info.key.as_ref(), &[attrs_bump]],
404 )?;
405 } else {
406 let curr_len = attributes_info.data.borrow().len() as u64;
407 if curr_len != required_space {
408 msg!(
409 "Attributes account size mismatch: curr={} required={}",
410 curr_len,
411 required_space
412 );
413 return Err(ProgramError::InvalidAccountData);
414 }
415 }
416
417 {
419 let data_ref = attributes_info.data.borrow();
420 if !data_ref.is_empty() && data_ref[0] != 0 {
421 return Err(MetadataError::MetadataAlreadyExists.into());
422 }
423 }
424
425 let attrs = TokenMetadataAttributes {
426 is_initialized: true,
427 mint: *mint_info.key,
428 data,
429 };
430 attrs.pack_into_slice(&mut attributes_info.data.borrow_mut());
431 Ok(())
432 }
433
434 fn process_replace_attributes(
435 program_id: &Pubkey,
436 accounts: &[AccountInfo],
437 data: Vec<(String, String)>,
438 ) -> ProgramResult {
439 let account_info_iter = &mut accounts.iter();
440 let attributes_info = next_account_info(account_info_iter)?; let update_authority_info = next_account_info(account_info_iter)?; let metadata_info = next_account_info(account_info_iter)?; if !update_authority_info.is_signer {
445 return Err(ProgramError::MissingRequiredSignature);
446 }
447
448 if attributes_info.owner != program_id {
449 return Err(ProgramError::IncorrectProgramId);
450 }
451
452 if metadata_info.owner != program_id {
454 return Err(ProgramError::IncorrectProgramId);
455 }
456 let metadata = TokenMetadata::unpack(&metadata_info.data.borrow())
457 .map_err(|_| ProgramError::InvalidAccountData)?;
458 if !metadata.is_initialized() {
459 return Err(ProgramError::UninitializedAccount);
460 }
461 let (expected_metadata_pda, _) = find_metadata_pda_with_program(program_id, &metadata.mint);
462 if metadata_info.key != &expected_metadata_pda {
463 return Err(ProgramError::InvalidSeeds);
464 }
465 match metadata.update_authority {
466 Some(current_auth) => {
467 if !cmp_pubkeys(¤t_auth, update_authority_info.key) {
468 return Err(MetadataError::InvalidAuthority.into());
469 }
470 }
471 None => return Err(MetadataError::InvalidAuthority.into()),
472 }
473
474 let (expected_attrs_pda, _bump) =
476 find_attributes_pda_with_program(program_id, &metadata.mint);
477 if !cmp_pubkeys(&expected_attrs_pda, attributes_info.key) {
478 return Err(ProgramError::InvalidSeeds);
479 }
480
481 let mut attrs = TokenMetadataAttributes::unpack(&attributes_info.data.borrow())
483 .map_err(|_| ProgramError::InvalidAccountData)?;
484 if !attrs.is_initialized() {
485 return Err(ProgramError::UninitializedAccount);
486 }
487 if attrs.mint != metadata.mint {
488 return Err(ProgramError::InvalidAccountData);
489 }
490
491 if data.len() > MAX_ATTRIBUTES {
493 return Err(MetadataError::TooManyAttributes.into());
494 }
495 for (k, v) in &data {
496 if k.is_empty() || v.is_empty() {
497 return Err(MetadataError::InvalidInstructionData.into());
498 }
499 if k.len() > MAX_KEY_LENGTH || v.len() > MAX_VALUE_LENGTH {
500 return Err(MetadataError::StringTooLong.into());
501 }
502 }
503
504 attrs.data = data;
506 attrs.pack_into_slice(&mut attributes_info.data.borrow_mut());
507 Ok(())
508 }
509
510 fn process_transfer_authority(
511 accounts: &[AccountInfo],
512 new_authority: Pubkey,
513 ) -> ProgramResult {
514 let account_info_iter = &mut accounts.iter();
515 let metadata_info = next_account_info(account_info_iter)?; let current_authority_info = next_account_info(account_info_iter)?; if !current_authority_info.is_signer {
519 msg!("Current authority is not a signer");
520 return Err(ProgramError::MissingRequiredSignature);
521 }
522
523 let mut metadata = TokenMetadata::unpack(&metadata_info.data.borrow())
524 .map_err(|_| ProgramError::InvalidAccountData)?;
525 if !metadata.is_initialized() {
526 msg!("Metadata not initialized");
527 return Err(ProgramError::UninitializedAccount);
528 }
529
530 match metadata.update_authority {
531 Some(current_auth) => {
532 if !cmp_pubkeys(¤t_auth, current_authority_info.key) {
533 msg!("Signer is not current update authority");
534 return Err(MetadataError::InvalidAuthority.into());
535 }
536 }
537 None => {
538 msg!("Metadata is immutable; cannot transfer authority");
539 return Err(MetadataError::InvalidAuthority.into());
540 }
541 }
542
543 metadata.update_authority = Some(new_authority);
544 metadata.pack_into_slice(&mut metadata_info.data.borrow_mut());
545 Ok(())
546 }
547
548 fn process_anchor(
551 program_id: &Pubkey,
552 accounts: &[AccountInfo],
553 input_index: u32,
554 input_signer: Pubkey,
555 ) -> ProgramResult {
556 let account_info_iter = &mut accounts.iter();
557 let account_info = next_account_info(account_info_iter)?;
558 let authority_info = next_account_info(account_info_iter)?;
559
560 if !cmp_pubkeys(program_id, account_info.owner) {
561 msg!("Anchor: account not owned by this program");
562 return Err(ProgramError::IncorrectProgramId);
563 }
564
565 let metadata = TokenMetadata::unpack(&account_info.data.borrow())
566 .map_err(|_| ProgramError::InvalidAccountData)?;
567
568 if !metadata.is_initialized() {
569 msg!("Anchor: metadata not initialized");
570 return Err(ProgramError::UninitializedAccount);
571 }
572
573 let expected_authority = metadata
574 .update_authority
575 .ok_or(MetadataError::InvalidAuthority)?;
576
577 if !cmp_pubkeys(&expected_authority, authority_info.key) {
578 msg!("Anchor: authority does not match");
579 return Err(MetadataError::InvalidAuthority.into());
580 }
581
582 if !authority_info.is_signer {
583 msg!("Anchor: authority must be a signer");
584 return Err(ProgramError::MissingRequiredSignature);
585 }
586
587 Self::validate_anchor_signer(account_info.key, &input_signer)?;
588
589 let input_to_sign = InputToSign {
590 index: input_index,
591 signer: input_signer,
592 };
593
594 set_input_to_sign(&[input_to_sign])?;
595
596 Ok(())
597 }
598
599 fn validate_anchor_signer(account: &Pubkey, input_signer: &Pubkey) -> ProgramResult {
600 if input_signer != account {
601 msg!("Anchor: input signer does not match metadata account");
602 return Err(MetadataError::InvalidAuthority.into());
603 }
604 Ok(())
605 }
606
607 fn process_make_immutable(accounts: &[AccountInfo]) -> ProgramResult {
608 let account_info_iter = &mut accounts.iter();
609 let metadata_info = next_account_info(account_info_iter)?; let current_authority_info = next_account_info(account_info_iter)?; if !current_authority_info.is_signer {
613 msg!("Current authority is not a signer");
614 return Err(ProgramError::MissingRequiredSignature);
615 }
616
617 let mut metadata = TokenMetadata::unpack(&metadata_info.data.borrow())
618 .map_err(|_| ProgramError::InvalidAccountData)?;
619 if !metadata.is_initialized() {
620 msg!("Metadata not initialized");
621 return Err(ProgramError::UninitializedAccount);
622 }
623
624 match metadata.update_authority {
625 Some(current_auth) => {
626 if !cmp_pubkeys(¤t_auth, current_authority_info.key) {
627 msg!("Signer is not current update authority");
628 return Err(MetadataError::InvalidAuthority.into());
629 }
630 }
631 None => {
632 msg!("Metadata already immutable");
633 return Err(MetadataError::InvalidAuthority.into());
634 }
635 }
636
637 metadata.update_authority = None;
638 metadata.pack_into_slice(&mut metadata_info.data.borrow_mut());
639 Ok(())
640 }
641}
642
643fn create_or_adopt_pda<'a>(
644 payer: &AccountInfo<'a>,
645 pda: &AccountInfo<'a>,
646 system_program: &AccountInfo<'a>,
647 space: usize,
648 owner: &Pubkey,
649 signer_seeds: &[&[u8]],
650) -> ProgramResult {
651 if pda.owner != &Pubkey::system_program() {
652 return Err(ProgramError::IllegalOwner);
653 }
654 if !pda.data_is_empty() {
655 return Err(ProgramError::InvalidAccountData);
656 }
657
658 let required_lamports = minimum_rent(space);
659 let accounts = &[payer.clone(), pda.clone(), system_program.clone()];
660
661 if pda.lamports() == 0 {
662 let instruction = system_instruction::create_account(
663 payer.key,
664 pda.key,
665 required_lamports,
666 space as u64,
667 owner,
668 );
669 return invoke_signed(&instruction, accounts, &[signer_seeds]);
670 }
671
672 let missing_lamports = required_lamports.saturating_sub(pda.lamports());
673 if missing_lamports > 0 {
674 invoke(
675 &system_instruction::transfer(payer.key, pda.key, missing_lamports),
676 accounts,
677 )?;
678 }
679 invoke_signed(
680 &system_instruction::allocate(pda.key, space as u64),
681 &[pda.clone(), system_program.clone()],
682 &[signer_seeds],
683 )?;
684 invoke_signed(
685 &system_instruction::assign(pda.key, owner),
686 &[pda.clone(), system_program.clone()],
687 &[signer_seeds],
688 )
689}
690
691fn cmp_pubkeys(a: &Pubkey, b: &Pubkey) -> bool {
693 arch_program::program_memory::sol_memcmp(a.as_ref(), b.as_ref(), 32) == 0
694}
695
696#[cfg(test)]
697mod tests {
698 use super::*;
699
700 #[test]
701 fn validate_anchor_signer_accepts_bound_signer() {
702 let account = Pubkey::new_unique();
703 assert!(Processor::validate_anchor_signer(&account, &account).is_ok());
704 }
705
706 #[test]
707 fn validate_anchor_signer_rejects_unbound_signer() {
708 let account = Pubkey::new_unique();
709 let err = Processor::validate_anchor_signer(&account, &Pubkey::new_unique()).unwrap_err();
710 assert_eq!(err, MetadataError::InvalidAuthority.into());
711 }
712}