constraints.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. use crate::*;
  2. use proc_macro2_diagnostics::SpanDiagnosticExt;
  3. use quote::quote;
  4. use syn::Expr;
  5. pub fn generate(f: &Field) -> proc_macro2::TokenStream {
  6. let constraints = linearize(&f.constraints);
  7. let rent = constraints
  8. .iter()
  9. .any(|c| matches!(c, Constraint::RentExempt(ConstraintRentExempt::Enforce)))
  10. .then(|| quote! { let __anchor_rent = Rent::get()?; })
  11. .unwrap_or_else(|| quote! {});
  12. let checks: Vec<proc_macro2::TokenStream> = constraints
  13. .iter()
  14. .map(|c| generate_constraint(f, c))
  15. .collect();
  16. quote! {
  17. #rent
  18. #(#checks)*
  19. }
  20. }
  21. pub fn generate_composite(f: &CompositeField) -> proc_macro2::TokenStream {
  22. let checks: Vec<proc_macro2::TokenStream> = linearize(&f.constraints)
  23. .iter()
  24. .filter_map(|c| match c {
  25. Constraint::Raw(_) => Some(c),
  26. Constraint::Literal(_) => Some(c),
  27. _ => panic!("Invariant violation: composite constraints can only be raw or literals"),
  28. })
  29. .map(|c| generate_constraint_composite(f, c))
  30. .collect();
  31. quote! {
  32. #(#checks)*
  33. }
  34. }
  35. // Linearizes the constraint group so that constraints with dependencies
  36. // run after those without.
  37. pub fn linearize(c_group: &ConstraintGroup) -> Vec<Constraint> {
  38. let ConstraintGroup {
  39. init,
  40. zeroed,
  41. mutable,
  42. signer,
  43. has_one,
  44. literal,
  45. raw,
  46. owner,
  47. rent_exempt,
  48. seeds,
  49. executable,
  50. state,
  51. close,
  52. address,
  53. associated_token,
  54. } = c_group.clone();
  55. let mut constraints = Vec::new();
  56. if let Some(c) = zeroed {
  57. constraints.push(Constraint::Zeroed(c));
  58. }
  59. if let Some(c) = init {
  60. constraints.push(Constraint::Init(c));
  61. }
  62. if let Some(c) = seeds {
  63. constraints.push(Constraint::Seeds(c));
  64. }
  65. if let Some(c) = associated_token {
  66. constraints.push(Constraint::AssociatedToken(c));
  67. }
  68. if let Some(c) = mutable {
  69. constraints.push(Constraint::Mut(c));
  70. }
  71. if let Some(c) = signer {
  72. constraints.push(Constraint::Signer(c));
  73. }
  74. constraints.append(&mut has_one.into_iter().map(Constraint::HasOne).collect());
  75. constraints.append(&mut literal.into_iter().map(Constraint::Literal).collect());
  76. constraints.append(&mut raw.into_iter().map(Constraint::Raw).collect());
  77. if let Some(c) = owner {
  78. constraints.push(Constraint::Owner(c));
  79. }
  80. if let Some(c) = rent_exempt {
  81. constraints.push(Constraint::RentExempt(c));
  82. }
  83. if let Some(c) = executable {
  84. constraints.push(Constraint::Executable(c));
  85. }
  86. if let Some(c) = state {
  87. constraints.push(Constraint::State(c));
  88. }
  89. if let Some(c) = close {
  90. constraints.push(Constraint::Close(c));
  91. }
  92. if let Some(c) = address {
  93. constraints.push(Constraint::Address(c));
  94. }
  95. constraints
  96. }
  97. fn generate_constraint(f: &Field, c: &Constraint) -> proc_macro2::TokenStream {
  98. match c {
  99. Constraint::Init(c) => generate_constraint_init(f, c),
  100. Constraint::Zeroed(c) => generate_constraint_zeroed(f, c),
  101. Constraint::Mut(c) => generate_constraint_mut(f, c),
  102. Constraint::HasOne(c) => generate_constraint_has_one(f, c),
  103. Constraint::Signer(c) => generate_constraint_signer(f, c),
  104. Constraint::Literal(c) => generate_constraint_literal(c),
  105. Constraint::Raw(c) => generate_constraint_raw(c),
  106. Constraint::Owner(c) => generate_constraint_owner(f, c),
  107. Constraint::RentExempt(c) => generate_constraint_rent_exempt(f, c),
  108. Constraint::Seeds(c) => generate_constraint_seeds(f, c),
  109. Constraint::Executable(c) => generate_constraint_executable(f, c),
  110. Constraint::State(c) => generate_constraint_state(f, c),
  111. Constraint::Close(c) => generate_constraint_close(f, c),
  112. Constraint::Address(c) => generate_constraint_address(f, c),
  113. Constraint::AssociatedToken(c) => generate_constraint_associated_token(f, c),
  114. }
  115. }
  116. fn generate_constraint_composite(_f: &CompositeField, c: &Constraint) -> proc_macro2::TokenStream {
  117. match c {
  118. Constraint::Raw(c) => generate_constraint_raw(c),
  119. Constraint::Literal(c) => generate_constraint_literal(c),
  120. _ => panic!("Invariant violation"),
  121. }
  122. }
  123. fn generate_constraint_address(f: &Field, c: &ConstraintAddress) -> proc_macro2::TokenStream {
  124. let field = &f.ident;
  125. let addr = &c.address;
  126. let error = generate_custom_error(&c.error, quote! { ConstraintAddress });
  127. quote! {
  128. if #field.key() != #addr {
  129. return Err(#error);
  130. }
  131. }
  132. }
  133. pub fn generate_constraint_init(f: &Field, c: &ConstraintInitGroup) -> proc_macro2::TokenStream {
  134. generate_constraint_init_group(f, c)
  135. }
  136. pub fn generate_constraint_zeroed(f: &Field, _c: &ConstraintZeroed) -> proc_macro2::TokenStream {
  137. let field = &f.ident;
  138. let ty_decl = f.ty_decl();
  139. let from_account_info = f.from_account_info_unchecked(None);
  140. quote! {
  141. let #field: #ty_decl = {
  142. let mut __data: &[u8] = &#field.try_borrow_data()?;
  143. let mut __disc_bytes = [0u8; 8];
  144. __disc_bytes.copy_from_slice(&__data[..8]);
  145. let __discriminator = u64::from_le_bytes(__disc_bytes);
  146. if __discriminator != 0 {
  147. return Err(anchor_lang::__private::ErrorCode::ConstraintZero.into());
  148. }
  149. #from_account_info
  150. };
  151. }
  152. }
  153. pub fn generate_constraint_close(f: &Field, c: &ConstraintClose) -> proc_macro2::TokenStream {
  154. let field = &f.ident;
  155. let target = &c.sol_dest;
  156. quote! {
  157. if #field.key() == #target.key() {
  158. return Err(anchor_lang::__private::ErrorCode::ConstraintClose.into());
  159. }
  160. }
  161. }
  162. pub fn generate_constraint_mut(f: &Field, c: &ConstraintMut) -> proc_macro2::TokenStream {
  163. let ident = &f.ident;
  164. let error = generate_custom_error(&c.error, quote! { ConstraintMut });
  165. quote! {
  166. if !#ident.to_account_info().is_writable {
  167. return Err(#error);
  168. }
  169. }
  170. }
  171. pub fn generate_constraint_has_one(f: &Field, c: &ConstraintHasOne) -> proc_macro2::TokenStream {
  172. let target = c.join_target.clone();
  173. let ident = &f.ident;
  174. let field = match &f.ty {
  175. Ty::Loader(_) => quote! {#ident.load()?},
  176. Ty::AccountLoader(_) => quote! {#ident.load()?},
  177. _ => quote! {#ident},
  178. };
  179. let error = generate_custom_error(&c.error, quote! { ConstraintHasOne });
  180. quote! {
  181. if #field.#target != #target.key() {
  182. return Err(#error);
  183. }
  184. }
  185. }
  186. pub fn generate_constraint_signer(f: &Field, c: &ConstraintSigner) -> proc_macro2::TokenStream {
  187. let ident = &f.ident;
  188. let info = match f.ty {
  189. Ty::AccountInfo => quote! { #ident },
  190. Ty::ProgramAccount(_) => quote! { #ident.to_account_info() },
  191. Ty::Account(_) => quote! { #ident.to_account_info() },
  192. Ty::Loader(_) => quote! { #ident.to_account_info() },
  193. Ty::AccountLoader(_) => quote! { #ident.to_account_info() },
  194. Ty::CpiAccount(_) => quote! { #ident.to_account_info() },
  195. _ => panic!("Invalid syntax: signer cannot be specified."),
  196. };
  197. let error = generate_custom_error(&c.error, quote! { ConstraintSigner });
  198. quote! {
  199. if !#info.is_signer {
  200. return Err(#error);
  201. }
  202. }
  203. }
  204. pub fn generate_constraint_literal(c: &ConstraintLiteral) -> proc_macro2::TokenStream {
  205. let lit: proc_macro2::TokenStream = {
  206. let lit = &c.lit;
  207. let constraint = lit.value().replace('\"', "");
  208. let message = format!(
  209. "Deprecated. Should be used with constraint: #[account(constraint = {})]",
  210. constraint,
  211. );
  212. lit.span().warning(message).emit_as_item_tokens();
  213. constraint.parse().unwrap()
  214. };
  215. quote! {
  216. if !(#lit) {
  217. return Err(anchor_lang::__private::ErrorCode::Deprecated.into());
  218. }
  219. }
  220. }
  221. pub fn generate_constraint_raw(c: &ConstraintRaw) -> proc_macro2::TokenStream {
  222. let raw = &c.raw;
  223. let error = generate_custom_error(&c.error, quote! { ConstraintRaw });
  224. quote! {
  225. if !(#raw) {
  226. return Err(#error);
  227. }
  228. }
  229. }
  230. pub fn generate_constraint_owner(f: &Field, c: &ConstraintOwner) -> proc_macro2::TokenStream {
  231. let ident = &f.ident;
  232. let owner_address = &c.owner_address;
  233. let error = generate_custom_error(&c.error, quote! { ConstraintOwner });
  234. quote! {
  235. if #ident.as_ref().owner != &#owner_address {
  236. return Err(#error);
  237. }
  238. }
  239. }
  240. pub fn generate_constraint_rent_exempt(
  241. f: &Field,
  242. c: &ConstraintRentExempt,
  243. ) -> proc_macro2::TokenStream {
  244. let ident = &f.ident;
  245. let info = quote! {
  246. #ident.to_account_info()
  247. };
  248. match c {
  249. ConstraintRentExempt::Skip => quote! {},
  250. ConstraintRentExempt::Enforce => quote! {
  251. if !__anchor_rent.is_exempt(#info.lamports(), #info.try_data_len()?) {
  252. return Err(anchor_lang::__private::ErrorCode::ConstraintRentExempt.into());
  253. }
  254. },
  255. }
  256. }
  257. fn generate_constraint_init_group(f: &Field, c: &ConstraintInitGroup) -> proc_macro2::TokenStream {
  258. let field = &f.ident;
  259. let ty_decl = f.ty_decl();
  260. let if_needed = if c.if_needed {
  261. quote! {true}
  262. } else {
  263. quote! {false}
  264. };
  265. let space = &c.space;
  266. // Payer for rent exemption.
  267. let payer = {
  268. let p = &c.payer;
  269. quote! {
  270. let payer = #p.to_account_info();
  271. }
  272. };
  273. // Convert from account info to account context wrapper type.
  274. let from_account_info = f.from_account_info_unchecked(Some(&c.kind));
  275. // PDA bump seeds.
  276. let (find_pda, seeds_with_bump) = match &c.seeds {
  277. None => (quote! {}, quote! {}),
  278. Some(c) => {
  279. let name_str = f.ident.to_string();
  280. let seeds = &mut c.seeds.clone();
  281. // If the seeds came with a trailing comma, we need to chop it off
  282. // before we interpolate them below.
  283. if let Some(pair) = seeds.pop() {
  284. seeds.push_value(pair.into_value());
  285. }
  286. let maybe_seeds_plus_comma = (!seeds.is_empty()).then(|| {
  287. quote! { #seeds, }
  288. });
  289. (
  290. quote! {
  291. let (__pda_address, __bump) = Pubkey::find_program_address(
  292. &[#maybe_seeds_plus_comma],
  293. program_id,
  294. );
  295. __bumps.insert(#name_str.to_string(), __bump);
  296. },
  297. quote! {
  298. &[
  299. #maybe_seeds_plus_comma
  300. &[__bump][..]
  301. ][..]
  302. },
  303. )
  304. }
  305. };
  306. match &c.kind {
  307. InitKind::Token { owner, mint } => {
  308. let create_account = generate_create_account(
  309. field,
  310. quote! {anchor_spl::token::TokenAccount::LEN},
  311. quote! {&token_program.key()},
  312. seeds_with_bump,
  313. );
  314. quote! {
  315. // Define the bump and pda variable.
  316. #find_pda
  317. let #field: #ty_decl = {
  318. if !#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID {
  319. // Define payer variable.
  320. #payer
  321. // Create the account with the system program.
  322. #create_account
  323. // Initialize the token account.
  324. let cpi_program = token_program.to_account_info();
  325. let accounts = anchor_spl::token::InitializeAccount {
  326. account: #field.to_account_info(),
  327. mint: #mint.to_account_info(),
  328. authority: #owner.to_account_info(),
  329. rent: rent.to_account_info(),
  330. };
  331. let cpi_ctx = anchor_lang::context::CpiContext::new(cpi_program, accounts);
  332. anchor_spl::token::initialize_account(cpi_ctx)?;
  333. }
  334. let pa: #ty_decl = #from_account_info;
  335. if !(!#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID) {
  336. if pa.mint != #mint.key() {
  337. return Err(anchor_lang::__private::ErrorCode::ConstraintTokenMint.into());
  338. }
  339. if pa.owner != #owner.key() {
  340. return Err(anchor_lang::__private::ErrorCode::ConstraintTokenOwner.into());
  341. }
  342. }
  343. pa
  344. };
  345. }
  346. }
  347. InitKind::AssociatedToken { owner, mint } => {
  348. quote! {
  349. // Define the bump and pda variable.
  350. #find_pda
  351. let #field: #ty_decl = {
  352. if !#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID {
  353. #payer
  354. let cpi_program = associated_token_program.to_account_info();
  355. let cpi_accounts = anchor_spl::associated_token::Create {
  356. payer: payer.to_account_info(),
  357. associated_token: #field.to_account_info(),
  358. authority: #owner.to_account_info(),
  359. mint: #mint.to_account_info(),
  360. system_program: system_program.to_account_info(),
  361. token_program: token_program.to_account_info(),
  362. rent: rent.to_account_info(),
  363. };
  364. let cpi_ctx = anchor_lang::context::CpiContext::new(cpi_program, cpi_accounts);
  365. anchor_spl::associated_token::create(cpi_ctx)?;
  366. }
  367. let pa: #ty_decl = #from_account_info;
  368. if !(!#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID) {
  369. if pa.mint != #mint.key() {
  370. return Err(anchor_lang::__private::ErrorCode::ConstraintTokenMint.into());
  371. }
  372. if pa.owner != #owner.key() {
  373. return Err(anchor_lang::__private::ErrorCode::ConstraintTokenOwner.into());
  374. }
  375. if pa.key() != anchor_spl::associated_token::get_associated_token_address(&#owner.key(), &#mint.key()) {
  376. return Err(anchor_lang::__private::ErrorCode::AccountNotAssociatedTokenAccount.into());
  377. }
  378. }
  379. pa
  380. };
  381. }
  382. }
  383. InitKind::Mint {
  384. owner,
  385. decimals,
  386. freeze_authority,
  387. } => {
  388. let create_account = generate_create_account(
  389. field,
  390. quote! {anchor_spl::token::Mint::LEN},
  391. quote! {&token_program.key()},
  392. seeds_with_bump,
  393. );
  394. let freeze_authority = match freeze_authority {
  395. Some(fa) => quote! { Option::<&anchor_lang::prelude::Pubkey>::Some(&#fa.key()) },
  396. None => quote! { Option::<&anchor_lang::prelude::Pubkey>::None },
  397. };
  398. quote! {
  399. // Define the bump and pda variable.
  400. #find_pda
  401. let #field: #ty_decl = {
  402. if !#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID {
  403. // Define payer variable.
  404. #payer
  405. // Create the account with the system program.
  406. #create_account
  407. // Initialize the mint account.
  408. let cpi_program = token_program.to_account_info();
  409. let accounts = anchor_spl::token::InitializeMint {
  410. mint: #field.to_account_info(),
  411. rent: rent.to_account_info(),
  412. };
  413. let cpi_ctx = anchor_lang::context::CpiContext::new(cpi_program, accounts);
  414. anchor_spl::token::initialize_mint(cpi_ctx, #decimals, &#owner.key(), #freeze_authority)?;
  415. }
  416. let pa: #ty_decl = #from_account_info;
  417. if !(!#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID) {
  418. if pa.mint_authority != anchor_lang::solana_program::program_option::COption::Some(#owner.key()) {
  419. return Err(anchor_lang::__private::ErrorCode::ConstraintMintMintAuthority.into());
  420. }
  421. if pa.freeze_authority
  422. .as_ref()
  423. .map(|fa| #freeze_authority.as_ref().map(|expected_fa| fa != *expected_fa).unwrap_or(true))
  424. .unwrap_or(#freeze_authority.is_some()) {
  425. return Err(anchor_lang::__private::ErrorCode::ConstraintMintFreezeAuthority.into());
  426. }
  427. if pa.decimals != #decimals {
  428. return Err(anchor_lang::__private::ErrorCode::ConstraintMintDecimals.into());
  429. }
  430. }
  431. pa
  432. };
  433. }
  434. }
  435. InitKind::Program { owner } => {
  436. // Define the space variable.
  437. let space = match space {
  438. // If no explicit space param was given, serialize the type to bytes
  439. // and take the length (with +8 for the discriminator.)
  440. None => {
  441. let account_ty = f.account_ty();
  442. match matches!(f.ty, Ty::Loader(_) | Ty::AccountLoader(_)) {
  443. false => {
  444. quote! {
  445. let space = 8 + #account_ty::default().try_to_vec().unwrap().len();
  446. }
  447. }
  448. true => {
  449. quote! {
  450. let space = 8 + anchor_lang::__private::bytemuck::bytes_of(&#account_ty::default()).len();
  451. }
  452. }
  453. }
  454. }
  455. // Explicit account size given. Use it.
  456. Some(s) => quote! {
  457. let space = #s;
  458. },
  459. };
  460. // Define the owner of the account being created. If not specified,
  461. // default to the currently executing program.
  462. let owner = match owner {
  463. None => quote! {
  464. program_id
  465. },
  466. Some(o) => quote! {
  467. &#o
  468. },
  469. };
  470. // CPI to the system program to create the account.
  471. let create_account =
  472. generate_create_account(field, quote! {space}, owner.clone(), seeds_with_bump);
  473. // Put it all together.
  474. quote! {
  475. // Define the bump variable.
  476. #find_pda
  477. let #field = {
  478. let actual_field = #field.to_account_info();
  479. let actual_owner = actual_field.owner;
  480. // Define the account space variable.
  481. #space
  482. // Create the account. Always do this in the event
  483. // if needed is not specified or the system program is the owner.
  484. if !#if_needed || actual_owner == &anchor_lang::solana_program::system_program::ID {
  485. // Define the payer variable.
  486. #payer
  487. // CPI to the system program to create.
  488. #create_account
  489. }
  490. // Convert from account info to account context wrapper type.
  491. let pa: #ty_decl = #from_account_info;
  492. // Assert the account was created correctly.
  493. if !(!#if_needed || actual_owner == &anchor_lang::solana_program::system_program::ID) {
  494. if space != actual_field.data_len() {
  495. return Err(anchor_lang::__private::ErrorCode::ConstraintSpace.into());
  496. }
  497. if actual_owner != #owner {
  498. return Err(anchor_lang::__private::ErrorCode::ConstraintOwner.into());
  499. }
  500. {
  501. let required_lamports = __anchor_rent.minimum_balance(space);
  502. if pa.to_account_info().lamports() < required_lamports {
  503. return Err(anchor_lang::__private::ErrorCode::ConstraintRentExempt.into());
  504. }
  505. }
  506. }
  507. // Done.
  508. pa
  509. };
  510. }
  511. }
  512. }
  513. }
  514. fn generate_constraint_seeds(f: &Field, c: &ConstraintSeedsGroup) -> proc_macro2::TokenStream {
  515. let name = &f.ident;
  516. let name_str = name.to_string();
  517. let s = &mut c.seeds.clone();
  518. let deriving_program_id = c
  519. .program_seed
  520. .clone()
  521. // If they specified a seeds::program to use when deriving the PDA, use it.
  522. .map(|program_id| quote! { #program_id })
  523. // Otherwise fall back to the current program's program_id.
  524. .unwrap_or(quote! { program_id });
  525. // If the seeds came with a trailing comma, we need to chop it off
  526. // before we interpolate them below.
  527. if let Some(pair) = s.pop() {
  528. s.push_value(pair.into_value());
  529. }
  530. // If the bump is provided with init *and target*, then force it to be the
  531. // canonical bump.
  532. //
  533. // Note that for `#[account(init, seeds)]`, find_program_address has already
  534. // been run in the init constraint.
  535. if c.is_init && c.bump.is_some() {
  536. let b = c.bump.as_ref().unwrap();
  537. quote! {
  538. if #name.key() != __pda_address {
  539. return Err(anchor_lang::__private::ErrorCode::ConstraintSeeds.into());
  540. }
  541. if __bump != #b {
  542. return Err(anchor_lang::__private::ErrorCode::ConstraintSeeds.into());
  543. }
  544. }
  545. }
  546. // Init seeds but no bump. We already used the canonical to create bump so
  547. // just check the address.
  548. //
  549. // Note that for `#[account(init, seeds)]`, find_program_address has already
  550. // been run in the init constraint.
  551. else if c.is_init {
  552. quote! {
  553. if #name.key() != __pda_address {
  554. return Err(anchor_lang::__private::ErrorCode::ConstraintSeeds.into());
  555. }
  556. }
  557. }
  558. // No init. So we just check the address.
  559. else {
  560. let maybe_seeds_plus_comma = (!s.is_empty()).then(|| {
  561. quote! { #s, }
  562. });
  563. let define_pda = match c.bump.as_ref() {
  564. // Bump target not given. Find it.
  565. None => quote! {
  566. let (__pda_address, __bump) = Pubkey::find_program_address(
  567. &[#maybe_seeds_plus_comma],
  568. &#deriving_program_id,
  569. );
  570. __bumps.insert(#name_str.to_string(), __bump);
  571. },
  572. // Bump target given. Use it.
  573. Some(b) => quote! {
  574. let __pda_address = Pubkey::create_program_address(
  575. &[#maybe_seeds_plus_comma &[#b][..]],
  576. &#deriving_program_id,
  577. ).map_err(|_| anchor_lang::__private::ErrorCode::ConstraintSeeds)?;
  578. },
  579. };
  580. quote! {
  581. // Define the PDA.
  582. #define_pda
  583. // Check it.
  584. if #name.key() != __pda_address {
  585. return Err(anchor_lang::__private::ErrorCode::ConstraintSeeds.into());
  586. }
  587. }
  588. }
  589. }
  590. fn generate_constraint_associated_token(
  591. f: &Field,
  592. c: &ConstraintAssociatedToken,
  593. ) -> proc_macro2::TokenStream {
  594. let name = &f.ident;
  595. let wallet_address = &c.wallet;
  596. let spl_token_mint_address = &c.mint;
  597. quote! {
  598. if #name.owner != #wallet_address.key() {
  599. return Err(anchor_lang::__private::ErrorCode::ConstraintTokenOwner.into());
  600. }
  601. let __associated_token_address = anchor_spl::associated_token::get_associated_token_address(&#wallet_address.key(), &#spl_token_mint_address.key());
  602. if #name.key() != __associated_token_address {
  603. return Err(anchor_lang::__private::ErrorCode::ConstraintAssociated.into());
  604. }
  605. }
  606. }
  607. // Generated code to create an account with with system program with the
  608. // given `space` amount of data, owned by `owner`.
  609. //
  610. // `seeds_with_nonce` should be given for creating PDAs. Otherwise it's an
  611. // empty stream.
  612. pub fn generate_create_account(
  613. field: &Ident,
  614. space: proc_macro2::TokenStream,
  615. owner: proc_macro2::TokenStream,
  616. seeds_with_nonce: proc_macro2::TokenStream,
  617. ) -> proc_macro2::TokenStream {
  618. quote! {
  619. // If the account being initialized already has lamports, then
  620. // return them all back to the payer so that the account has
  621. // zero lamports when the system program's create instruction
  622. // is eventually called.
  623. let __current_lamports = #field.lamports();
  624. if __current_lamports == 0 {
  625. // Create the token account with right amount of lamports and space, and the correct owner.
  626. let lamports = __anchor_rent.minimum_balance(#space);
  627. anchor_lang::solana_program::program::invoke_signed(
  628. &anchor_lang::solana_program::system_instruction::create_account(
  629. &payer.key(),
  630. &#field.key(),
  631. lamports,
  632. #space as u64,
  633. #owner,
  634. ),
  635. &[
  636. payer.to_account_info(),
  637. #field.to_account_info(),
  638. system_program.to_account_info(),
  639. ],
  640. &[#seeds_with_nonce],
  641. )?;
  642. } else {
  643. // Fund the account for rent exemption.
  644. let required_lamports = __anchor_rent
  645. .minimum_balance(#space)
  646. .max(1)
  647. .saturating_sub(__current_lamports);
  648. if required_lamports > 0 {
  649. anchor_lang::solana_program::program::invoke(
  650. &anchor_lang::solana_program::system_instruction::transfer(
  651. &payer.key(),
  652. &#field.key(),
  653. required_lamports,
  654. ),
  655. &[
  656. payer.to_account_info(),
  657. #field.to_account_info(),
  658. system_program.to_account_info(),
  659. ],
  660. )?;
  661. }
  662. // Allocate space.
  663. anchor_lang::solana_program::program::invoke_signed(
  664. &anchor_lang::solana_program::system_instruction::allocate(
  665. &#field.key(),
  666. #space as u64,
  667. ),
  668. &[
  669. #field.to_account_info(),
  670. system_program.to_account_info(),
  671. ],
  672. &[#seeds_with_nonce],
  673. )?;
  674. // Assign to the spl token program.
  675. anchor_lang::solana_program::program::invoke_signed(
  676. &anchor_lang::solana_program::system_instruction::assign(
  677. &#field.key(),
  678. #owner,
  679. ),
  680. &[
  681. #field.to_account_info(),
  682. system_program.to_account_info(),
  683. ],
  684. &[#seeds_with_nonce],
  685. )?;
  686. }
  687. }
  688. }
  689. pub fn generate_constraint_executable(
  690. f: &Field,
  691. _c: &ConstraintExecutable,
  692. ) -> proc_macro2::TokenStream {
  693. let name = &f.ident;
  694. quote! {
  695. if !#name.to_account_info().executable {
  696. return Err(anchor_lang::__private::ErrorCode::ConstraintExecutable.into());
  697. }
  698. }
  699. }
  700. pub fn generate_constraint_state(f: &Field, c: &ConstraintState) -> proc_macro2::TokenStream {
  701. let program_target = c.program_target.clone();
  702. let ident = &f.ident;
  703. let account_ty = match &f.ty {
  704. Ty::CpiState(ty) => &ty.account_type_path,
  705. _ => panic!("Invalid state constraint"),
  706. };
  707. quote! {
  708. // Checks the given state account is the canonical state account for
  709. // the target program.
  710. if #ident.key() != anchor_lang::accounts::cpi_state::CpiState::<#account_ty>::address(&#program_target.key()) {
  711. return Err(anchor_lang::__private::ErrorCode::ConstraintState.into());
  712. }
  713. if #ident.as_ref().owner != &#program_target.key() {
  714. return Err(anchor_lang::__private::ErrorCode::ConstraintState.into());
  715. }
  716. }
  717. }
  718. fn generate_custom_error(
  719. custom_error: &Option<Expr>,
  720. error: proc_macro2::TokenStream,
  721. ) -> proc_macro2::TokenStream {
  722. match custom_error {
  723. Some(error) => quote! { #error.into() },
  724. None => quote! { anchor_lang::__private::ErrorCode::#error.into() },
  725. }
  726. }