constraints.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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 payer = {
  259. let p = &c.payer;
  260. quote! {
  261. let payer = #p.to_account_info();
  262. }
  263. };
  264. let seeds_with_nonce = match &c.seeds {
  265. None => quote! {},
  266. Some(c) => {
  267. let s = &mut c.seeds.clone();
  268. // If the seeds came with a trailing comma, we need to chop it off
  269. // before we interpolate them below.
  270. if let Some(pair) = s.pop() {
  271. s.push_value(pair.into_value());
  272. }
  273. let maybe_seeds_plus_comma = (!s.is_empty()).then(|| {
  274. quote! { #s, }
  275. });
  276. let inner = match c.bump.as_ref() {
  277. // Bump target not given. Use the canonical bump.
  278. None => {
  279. quote! {
  280. [
  281. #maybe_seeds_plus_comma
  282. &[
  283. Pubkey::find_program_address(
  284. &[#s],
  285. program_id,
  286. ).1
  287. ][..]
  288. ]
  289. }
  290. }
  291. // Bump target given. Use it.
  292. Some(b) => quote! {
  293. [#maybe_seeds_plus_comma &[#b][..]]
  294. },
  295. };
  296. quote! {
  297. &#inner[..]
  298. }
  299. }
  300. };
  301. generate_init(f, c.if_needed, seeds_with_nonce, payer, &c.space, &c.kind)
  302. }
  303. fn generate_constraint_seeds(f: &Field, c: &ConstraintSeedsGroup) -> proc_macro2::TokenStream {
  304. let name = &f.ident;
  305. let s = &mut c.seeds.clone();
  306. let deriving_program_id = c
  307. .program_seed
  308. .clone()
  309. // If they specified a seeds::program to use when deriving the PDA, use it.
  310. .map(|program_id| quote! { #program_id })
  311. // Otherwise fall back to the current program's program_id.
  312. .unwrap_or(quote! { program_id });
  313. // If the seeds came with a trailing comma, we need to chop it off
  314. // before we interpolate them below.
  315. if let Some(pair) = s.pop() {
  316. s.push_value(pair.into_value());
  317. }
  318. // If the bump is provided with init *and target*, then force it to be the
  319. // canonical bump.
  320. if c.is_init && c.bump.is_some() {
  321. let b = c.bump.as_ref().unwrap();
  322. quote! {
  323. let (__program_signer, __bump) = anchor_lang::solana_program::pubkey::Pubkey::find_program_address(
  324. &[#s],
  325. &#deriving_program_id,
  326. );
  327. if #name.key() != __program_signer {
  328. return Err(anchor_lang::__private::ErrorCode::ConstraintSeeds.into());
  329. }
  330. if __bump != #b {
  331. return Err(anchor_lang::__private::ErrorCode::ConstraintSeeds.into());
  332. }
  333. }
  334. } else {
  335. let maybe_seeds_plus_comma = (!s.is_empty()).then(|| {
  336. quote! { #s, }
  337. });
  338. let seeds = match c.bump.as_ref() {
  339. // Bump target not given. Find it.
  340. None => {
  341. quote! {
  342. [
  343. #maybe_seeds_plus_comma
  344. &[
  345. Pubkey::find_program_address(
  346. &[#s],
  347. &#deriving_program_id,
  348. ).1
  349. ][..]
  350. ]
  351. }
  352. }
  353. // Bump target given. Use it.
  354. Some(b) => {
  355. quote! {
  356. [#maybe_seeds_plus_comma &[#b][..]]
  357. }
  358. }
  359. };
  360. quote! {
  361. let __program_signer = Pubkey::create_program_address(
  362. &#seeds[..],
  363. &#deriving_program_id,
  364. ).map_err(|_| anchor_lang::__private::ErrorCode::ConstraintSeeds)?;
  365. if #name.key() != __program_signer {
  366. return Err(anchor_lang::__private::ErrorCode::ConstraintSeeds.into());
  367. }
  368. }
  369. }
  370. }
  371. fn generate_constraint_associated_token(
  372. f: &Field,
  373. c: &ConstraintAssociatedToken,
  374. ) -> proc_macro2::TokenStream {
  375. let name = &f.ident;
  376. let wallet_address = &c.wallet;
  377. let spl_token_mint_address = &c.mint;
  378. quote! {
  379. if #name.owner != #wallet_address.key() {
  380. return Err(anchor_lang::__private::ErrorCode::ConstraintTokenOwner.into());
  381. }
  382. let __associated_token_address = anchor_spl::associated_token::get_associated_token_address(&#wallet_address.key(), &#spl_token_mint_address.key());
  383. if #name.key() != __associated_token_address {
  384. return Err(anchor_lang::__private::ErrorCode::ConstraintAssociated.into());
  385. }
  386. }
  387. }
  388. // `if_needed` is set if account allocation and initialization is optional.
  389. pub fn generate_init(
  390. f: &Field,
  391. if_needed: bool,
  392. seeds_with_nonce: proc_macro2::TokenStream,
  393. payer: proc_macro2::TokenStream,
  394. space: &Option<Expr>,
  395. kind: &InitKind,
  396. ) -> proc_macro2::TokenStream {
  397. let field = &f.ident;
  398. let ty_decl = f.ty_decl();
  399. let from_account_info = f.from_account_info_unchecked(Some(kind));
  400. let if_needed = if if_needed {
  401. quote! {true}
  402. } else {
  403. quote! {false}
  404. };
  405. match kind {
  406. InitKind::Token { owner, mint } => {
  407. let create_account = generate_create_account(
  408. field,
  409. quote! {anchor_spl::token::TokenAccount::LEN},
  410. quote! {&token_program.key()},
  411. seeds_with_nonce,
  412. );
  413. quote! {
  414. let #field: #ty_decl = {
  415. if !#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID {
  416. // Define payer variable.
  417. #payer
  418. // Create the account with the system program.
  419. #create_account
  420. // Initialize the token account.
  421. let cpi_program = token_program.to_account_info();
  422. let accounts = anchor_spl::token::InitializeAccount {
  423. account: #field.to_account_info(),
  424. mint: #mint.to_account_info(),
  425. authority: #owner.to_account_info(),
  426. rent: rent.to_account_info(),
  427. };
  428. let cpi_ctx = anchor_lang::context::CpiContext::new(cpi_program, accounts);
  429. anchor_spl::token::initialize_account(cpi_ctx)?;
  430. }
  431. let pa: #ty_decl = #from_account_info;
  432. if !(!#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID) {
  433. if pa.mint != #mint.key() {
  434. return Err(anchor_lang::__private::ErrorCode::ConstraintTokenMint.into());
  435. }
  436. if pa.owner != #owner.key() {
  437. return Err(anchor_lang::__private::ErrorCode::ConstraintTokenOwner.into());
  438. }
  439. }
  440. pa
  441. };
  442. }
  443. }
  444. InitKind::AssociatedToken { owner, mint } => {
  445. quote! {
  446. let #field: #ty_decl = {
  447. if !#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID {
  448. #payer
  449. let cpi_program = associated_token_program.to_account_info();
  450. let cpi_accounts = anchor_spl::associated_token::Create {
  451. payer: payer.to_account_info(),
  452. associated_token: #field.to_account_info(),
  453. authority: #owner.to_account_info(),
  454. mint: #mint.to_account_info(),
  455. system_program: system_program.to_account_info(),
  456. token_program: token_program.to_account_info(),
  457. rent: rent.to_account_info(),
  458. };
  459. let cpi_ctx = anchor_lang::context::CpiContext::new(cpi_program, cpi_accounts);
  460. anchor_spl::associated_token::create(cpi_ctx)?;
  461. }
  462. let pa: #ty_decl = #from_account_info;
  463. if !(!#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID) {
  464. if pa.mint != #mint.key() {
  465. return Err(anchor_lang::__private::ErrorCode::ConstraintTokenMint.into());
  466. }
  467. if pa.owner != #owner.key() {
  468. return Err(anchor_lang::__private::ErrorCode::ConstraintTokenOwner.into());
  469. }
  470. if pa.key() != anchor_spl::associated_token::get_associated_token_address(&#owner.key(), &#mint.key()) {
  471. return Err(anchor_lang::__private::ErrorCode::AccountNotAssociatedTokenAccount.into());
  472. }
  473. }
  474. pa
  475. };
  476. }
  477. }
  478. InitKind::Mint {
  479. owner,
  480. decimals,
  481. freeze_authority,
  482. } => {
  483. let create_account = generate_create_account(
  484. field,
  485. quote! {anchor_spl::token::Mint::LEN},
  486. quote! {&token_program.key()},
  487. seeds_with_nonce,
  488. );
  489. let freeze_authority = match freeze_authority {
  490. Some(fa) => quote! { Option::<&anchor_lang::prelude::Pubkey>::Some(&#fa.key()) },
  491. None => quote! { Option::<&anchor_lang::prelude::Pubkey>::None },
  492. };
  493. quote! {
  494. let #field: #ty_decl = {
  495. if !#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID {
  496. // Define payer variable.
  497. #payer
  498. // Create the account with the system program.
  499. #create_account
  500. // Initialize the mint account.
  501. let cpi_program = token_program.to_account_info();
  502. let accounts = anchor_spl::token::InitializeMint {
  503. mint: #field.to_account_info(),
  504. rent: rent.to_account_info(),
  505. };
  506. let cpi_ctx = anchor_lang::context::CpiContext::new(cpi_program, accounts);
  507. anchor_spl::token::initialize_mint(cpi_ctx, #decimals, &#owner.key(), #freeze_authority)?;
  508. }
  509. let pa: #ty_decl = #from_account_info;
  510. if !(!#if_needed || #field.as_ref().owner == &anchor_lang::solana_program::system_program::ID) {
  511. if pa.mint_authority != anchor_lang::solana_program::program_option::COption::Some(#owner.key()) {
  512. return Err(anchor_lang::__private::ErrorCode::ConstraintMintMintAuthority.into());
  513. }
  514. if pa.freeze_authority
  515. .as_ref()
  516. .map(|fa| #freeze_authority.as_ref().map(|expected_fa| fa != *expected_fa).unwrap_or(true))
  517. .unwrap_or(#freeze_authority.is_some()) {
  518. return Err(anchor_lang::__private::ErrorCode::ConstraintMintFreezeAuthority.into());
  519. }
  520. if pa.decimals != #decimals {
  521. return Err(anchor_lang::__private::ErrorCode::ConstraintMintDecimals.into());
  522. }
  523. }
  524. pa
  525. };
  526. }
  527. }
  528. InitKind::Program { owner } => {
  529. let space = match space {
  530. // If no explicit space param was given, serialize the type to bytes
  531. // and take the length (with +8 for the discriminator.)
  532. None => {
  533. let account_ty = f.account_ty();
  534. match matches!(f.ty, Ty::Loader(_) | Ty::AccountLoader(_)) {
  535. false => {
  536. quote! {
  537. let space = 8 + #account_ty::default().try_to_vec().unwrap().len();
  538. }
  539. }
  540. true => {
  541. quote! {
  542. let space = 8 + anchor_lang::__private::bytemuck::bytes_of(&#account_ty::default()).len();
  543. }
  544. }
  545. }
  546. }
  547. // Explicit account size given. Use it.
  548. Some(s) => quote! {
  549. let space = #s;
  550. },
  551. };
  552. // Owner of the account being created. If not specified,
  553. // default to the currently executing program.
  554. let owner = match owner {
  555. None => quote! {
  556. program_id
  557. },
  558. Some(o) => quote! {
  559. &#o
  560. },
  561. };
  562. let pda_check = if !seeds_with_nonce.is_empty() {
  563. quote! {
  564. let expected_key = anchor_lang::prelude::Pubkey::create_program_address(
  565. #seeds_with_nonce,
  566. #owner
  567. ).map_err(|_| anchor_lang::__private::ErrorCode::ConstraintSeeds)?;
  568. if expected_key != #field.key() {
  569. return Err(anchor_lang::__private::ErrorCode::ConstraintSeeds.into());
  570. }
  571. }
  572. } else {
  573. quote! {}
  574. };
  575. let create_account =
  576. generate_create_account(field, quote! {space}, owner.clone(), seeds_with_nonce);
  577. quote! {
  578. let #field = {
  579. let actual_field = #field.to_account_info();
  580. let actual_owner = actual_field.owner;
  581. #space
  582. if !#if_needed || actual_owner == &anchor_lang::solana_program::system_program::ID {
  583. #payer
  584. #create_account
  585. }
  586. let pa: #ty_decl = #from_account_info;
  587. if !(!#if_needed || actual_owner == &anchor_lang::solana_program::system_program::ID) {
  588. if space != actual_field.data_len() {
  589. return Err(anchor_lang::__private::ErrorCode::ConstraintSpace.into());
  590. }
  591. if actual_owner != #owner {
  592. return Err(anchor_lang::__private::ErrorCode::ConstraintOwner.into());
  593. }
  594. {
  595. let required_lamports = __anchor_rent.minimum_balance(space);
  596. if pa.to_account_info().lamports() < required_lamports {
  597. return Err(anchor_lang::__private::ErrorCode::ConstraintRentExempt.into());
  598. }
  599. }
  600. #pda_check
  601. }
  602. pa
  603. };
  604. }
  605. }
  606. }
  607. }
  608. // Generated code to create an account with with system program with the
  609. // given `space` amount of data, owned by `owner`.
  610. //
  611. // `seeds_with_nonce` should be given for creating PDAs. Otherwise it's an
  612. // empty stream.
  613. pub fn generate_create_account(
  614. field: &Ident,
  615. space: proc_macro2::TokenStream,
  616. owner: proc_macro2::TokenStream,
  617. seeds_with_nonce: proc_macro2::TokenStream,
  618. ) -> proc_macro2::TokenStream {
  619. quote! {
  620. // If the account being initialized already has lamports, then
  621. // return them all back to the payer so that the account has
  622. // zero lamports when the system program's create instruction
  623. // is eventually called.
  624. let __current_lamports = #field.lamports();
  625. if __current_lamports == 0 {
  626. // Create the token account with right amount of lamports and space, and the correct owner.
  627. let lamports = __anchor_rent.minimum_balance(#space);
  628. anchor_lang::solana_program::program::invoke_signed(
  629. &anchor_lang::solana_program::system_instruction::create_account(
  630. &payer.key(),
  631. &#field.key(),
  632. lamports,
  633. #space as u64,
  634. #owner,
  635. ),
  636. &[
  637. payer.to_account_info(),
  638. #field.to_account_info(),
  639. system_program.to_account_info(),
  640. ],
  641. &[#seeds_with_nonce],
  642. )?;
  643. } else {
  644. // Fund the account for rent exemption.
  645. let required_lamports = __anchor_rent
  646. .minimum_balance(#space)
  647. .max(1)
  648. .saturating_sub(__current_lamports);
  649. if required_lamports > 0 {
  650. anchor_lang::solana_program::program::invoke(
  651. &anchor_lang::solana_program::system_instruction::transfer(
  652. &payer.key(),
  653. &#field.key(),
  654. required_lamports,
  655. ),
  656. &[
  657. payer.to_account_info(),
  658. #field.to_account_info(),
  659. system_program.to_account_info(),
  660. ],
  661. )?;
  662. }
  663. // Allocate space.
  664. anchor_lang::solana_program::program::invoke_signed(
  665. &anchor_lang::solana_program::system_instruction::allocate(
  666. &#field.key(),
  667. #space as u64,
  668. ),
  669. &[
  670. #field.to_account_info(),
  671. system_program.to_account_info(),
  672. ],
  673. &[#seeds_with_nonce],
  674. )?;
  675. // Assign to the spl token program.
  676. anchor_lang::solana_program::program::invoke_signed(
  677. &anchor_lang::solana_program::system_instruction::assign(
  678. &#field.key(),
  679. #owner,
  680. ),
  681. &[
  682. #field.to_account_info(),
  683. system_program.to_account_info(),
  684. ],
  685. &[#seeds_with_nonce],
  686. )?;
  687. }
  688. }
  689. }
  690. pub fn generate_constraint_executable(
  691. f: &Field,
  692. _c: &ConstraintExecutable,
  693. ) -> proc_macro2::TokenStream {
  694. let name = &f.ident;
  695. quote! {
  696. if !#name.to_account_info().executable {
  697. return Err(anchor_lang::__private::ErrorCode::ConstraintExecutable.into());
  698. }
  699. }
  700. }
  701. pub fn generate_constraint_state(f: &Field, c: &ConstraintState) -> proc_macro2::TokenStream {
  702. let program_target = c.program_target.clone();
  703. let ident = &f.ident;
  704. let account_ty = match &f.ty {
  705. Ty::CpiState(ty) => &ty.account_type_path,
  706. _ => panic!("Invalid state constraint"),
  707. };
  708. quote! {
  709. // Checks the given state account is the canonical state account for
  710. // the target program.
  711. if #ident.key() != anchor_lang::accounts::cpi_state::CpiState::<#account_ty>::address(&#program_target.key()) {
  712. return Err(anchor_lang::__private::ErrorCode::ConstraintState.into());
  713. }
  714. if #ident.as_ref().owner != &#program_target.key() {
  715. return Err(anchor_lang::__private::ErrorCode::ConstraintState.into());
  716. }
  717. }
  718. }
  719. fn generate_custom_error(
  720. custom_error: &Option<Expr>,
  721. error: proc_macro2::TokenStream,
  722. ) -> proc_macro2::TokenStream {
  723. match custom_error {
  724. Some(error) => quote! { #error.into() },
  725. None => quote! { anchor_lang::__private::ErrorCode::#error.into() },
  726. }
  727. }