constraints.rs 28 KB

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