Przeglądaj źródła

Merge pull request #51 from ZYJLiu/main

update anchor basics examples
Nick Frostbutter 2 lat temu
rodzic
commit
bbe6a8d8a4
56 zmienionych plików z 801 dodań i 625 usunięć
  1. 1 0
      .github/workflows/anchor.yml
  2. 5 3
      basics/account-data/anchor/Anchor.toml
  3. 20 32
      basics/account-data/anchor/programs/anchor-program-example/src/instructions/create.rs
  4. 0 1
      basics/account-data/anchor/programs/anchor-program-example/src/instructions/mod.rs
  5. 2 5
      basics/account-data/anchor/programs/anchor-program-example/src/lib.rs
  6. 8 15
      basics/account-data/anchor/programs/anchor-program-example/src/state/address_info.rs
  7. 36 21
      basics/account-data/anchor/tests/test.ts
  8. 13 8
      basics/checking-accounts/anchor/programs/anchor-program-example/src/lib.rs
  9. 27 22
      basics/checking-accounts/anchor/tests/test.ts
  10. 3 2
      basics/close-account/anchor/Anchor.toml
  11. 9 15
      basics/close-account/anchor/programs/close-account/src/instructions/close_user.rs
  12. 15 26
      basics/close-account/anchor/programs/close-account/src/instructions/create_user.rs
  13. 3 4
      basics/close-account/anchor/programs/close-account/src/lib.rs
  14. 2 3
      basics/close-account/anchor/programs/close-account/src/state/mod.rs
  15. 0 18
      basics/close-account/anchor/programs/close-account/src/state/user.rs
  16. 10 0
      basics/close-account/anchor/programs/close-account/src/state/user_state.rs
  17. 33 78
      basics/close-account/anchor/tests/close-account.ts
  18. 3 2
      basics/counter/anchor/Anchor.toml
  19. 15 9
      basics/counter/anchor/programs/counter_anchor/src/lib.rs
  20. 49 34
      basics/counter/anchor/tests/counter_anchor.ts
  21. 5 3
      basics/create-account/anchor/Anchor.toml
  22. 9 8
      basics/create-account/anchor/programs/create-system-account/src/lib.rs
  23. 23 12
      basics/create-account/anchor/tests/test.ts
  24. 6 4
      basics/cross-program-invocation/anchor/Anchor.toml
  25. 1 1
      basics/cross-program-invocation/anchor/programs/hand/src/lib.rs
  26. 1 1
      basics/cross-program-invocation/anchor/programs/lever/src/lib.rs
  27. 17 16
      basics/cross-program-invocation/anchor/tests/test.ts
  28. 5 3
      basics/hello-solana/anchor/Anchor.toml
  29. 1 1
      basics/hello-solana/anchor/programs/hello-solana/src/lib.rs
  30. 30 28
      basics/pda-rent-payer/anchor/programs/anchor-program-example/src/instructions/create_new_account.rs
  31. 20 24
      basics/pda-rent-payer/anchor/programs/anchor-program-example/src/instructions/init_rent_vault.rs
  32. 2 6
      basics/pda-rent-payer/anchor/programs/anchor-program-example/src/lib.rs
  33. 0 11
      basics/pda-rent-payer/anchor/programs/anchor-program-example/src/state/mod.rs
  34. 43 28
      basics/pda-rent-payer/anchor/tests/test.ts
  35. 1 1
      basics/processing-instructions/anchor/Anchor.toml
  36. 16 18
      basics/program-derived-addresses/anchor/programs/anchor-program-example/src/instructions/create.rs
  37. 10 14
      basics/program-derived-addresses/anchor/programs/anchor-program-example/src/instructions/increment.rs
  38. 2 2
      basics/program-derived-addresses/anchor/programs/anchor-program-example/src/lib.rs
  39. 3 8
      basics/program-derived-addresses/anchor/programs/anchor-program-example/src/state/page_visits.rs
  40. 27 55
      basics/program-derived-addresses/anchor/tests/test.ts
  41. 8 0
      basics/realloc/anchor/.gitignore
  42. 8 0
      basics/realloc/anchor/.prettierignore
  43. 16 0
      basics/realloc/anchor/Anchor.toml
  44. 13 0
      basics/realloc/anchor/Cargo.toml
  45. 12 0
      basics/realloc/anchor/migrations/deploy.ts
  46. 19 0
      basics/realloc/anchor/package.json
  47. 19 0
      basics/realloc/anchor/programs/anchor-realloc/Cargo.toml
  48. 2 0
      basics/realloc/anchor/programs/anchor-realloc/Xargo.toml
  49. 63 0
      basics/realloc/anchor/programs/anchor-realloc/src/lib.rs
  50. 75 0
      basics/realloc/anchor/tests/anchor-realloc.ts
  51. 11 0
      basics/realloc/anchor/tsconfig.json
  52. 12 19
      basics/transfer-sol/anchor/programs/transfer-sol/src/lib.rs
  53. 62 59
      basics/transfer-sol/anchor/tests/test.ts
  54. 1 1
      tokens/pda-mint-authority/anchor/programs/token-minter/src/instructions/create.rs
  55. 2 2
      tokens/spl-token-minter/anchor/programs/spl-token-minter/src/instructions/create.rs
  56. 2 2
      tokens/transfer-tokens/anchor/programs/transfer-tokens/src/instructions/create.rs

+ 1 - 0
.github/workflows/anchor.yml

@@ -30,6 +30,7 @@ jobs:
             "basics/pda-rent-payer/anchor"
             "basics/processing-instructions/anchor"
             "basics/program-derived-addresses/anchor"
+            "basics/realloc/anchor"
             "basics/rent/anchor"
             "basics/repository-layout/anchor"
             "basics/transfer-sol/anchor"

+ 5 - 3
basics/account-data/anchor/Anchor.toml

@@ -1,13 +1,15 @@
 [features]
 seeds = false
+skip-lint = false
+
 [programs.localnet]
-anchor_program_example = "FFKtnYFyzPj1qFjE9epkrfYHJwZMdh8CvJrB6XsKeFVz"
+anchor_program_example = "GpVcgWdgVErgLqsn8VYUch6EqDerMgNqoLSmGyKrd6MR"
 
 [registry]
-url = "https://anchor.projectserum.com"
+url = "https://api.apr.dev"
 
 [provider]
-cluster = "localnet"
+cluster = "Localnet"
 wallet = "~/.config/solana/id.json"
 
 [scripts]

+ 20 - 32
basics/account-data/anchor/programs/anchor-program-example/src/instructions/create.rs

@@ -1,9 +1,20 @@
+use crate::state::AddressInfo;
 use anchor_lang::prelude::*;
-use anchor_lang::system_program;
 
-use crate::state::AddressInfo;
+#[derive(Accounts)]
+pub struct CreateAddressInfo<'info> {
+    #[account(mut)]
+    payer: Signer<'info>,
+
+    #[account(
+        init,
+        payer = payer,
+        space = 8 + AddressInfo::INIT_SPACE,
+    )]
+    address_info: Account<'info, AddressInfo>,
+    system_program: Program<'info, System>,
+}
 
-#[allow(clippy::result_large_err)]
 pub fn create_address_info(
     ctx: Context<CreateAddressInfo>,
     name: String,
@@ -11,34 +22,11 @@ pub fn create_address_info(
     street: String,
     city: String,
 ) -> Result<()> {
-    let address_info = AddressInfo::new(name, house_number, street, city);
-
-    let account_span = (address_info.try_to_vec()?).len();
-    let lamports_required = (Rent::get()?).minimum_balance(account_span);
-
-    system_program::create_account(
-        CpiContext::new(
-            ctx.accounts.system_program.to_account_info(),
-            system_program::CreateAccount {
-                from: ctx.accounts.payer.to_account_info(),
-                to: ctx.accounts.address_info.to_account_info(),
-            },
-        ),
-        lamports_required,
-        account_span as u64,
-        &ctx.accounts.system_program.key(),
-    )?;
-
-    let address_info_account = &mut ctx.accounts.address_info;
-    address_info_account.set_inner(address_info);
+    *ctx.accounts.address_info = AddressInfo {
+        name,
+        house_number,
+        street,
+        city,
+    };
     Ok(())
 }
-
-#[derive(Accounts)]
-pub struct CreateAddressInfo<'info> {
-    #[account(mut)]
-    address_info: Account<'info, AddressInfo>,
-    #[account(mut)]
-    payer: Signer<'info>,
-    system_program: Program<'info, System>,
-}

+ 0 - 1
basics/account-data/anchor/programs/anchor-program-example/src/instructions/mod.rs

@@ -1,3 +1,2 @@
 pub mod create;
-
 pub use create::*;

+ 2 - 5
basics/account-data/anchor/programs/anchor-program-example/src/lib.rs

@@ -1,19 +1,16 @@
 #![allow(clippy::result_large_err)]
-
 use anchor_lang::prelude::*;
-
 use instructions::*;
 
 pub mod instructions;
 pub mod state;
 
-declare_id!("FFKtnYFyzPj1qFjE9epkrfYHJwZMdh8CvJrB6XsKeFVz");
+declare_id!("GpVcgWdgVErgLqsn8VYUch6EqDerMgNqoLSmGyKrd6MR");
 
 #[program]
 pub mod anchor_program_example {
     use super::*;
 
-    #[allow(clippy::result_large_err)]
     pub fn create_address_info(
         ctx: Context<CreateAddressInfo>,
         name: String,
@@ -21,6 +18,6 @@ pub mod anchor_program_example {
         street: String,
         city: String,
     ) -> Result<()> {
-        instructions::create::create_address_info(ctx, name, house_number, street, city)
+        create::create_address_info(ctx, name, house_number, street, city)
     }
 }

+ 8 - 15
basics/account-data/anchor/programs/anchor-program-example/src/state/address_info.rs

@@ -1,20 +1,13 @@
 use anchor_lang::prelude::*;
 
 #[account]
+#[derive(InitSpace)] // automatically calculate the space required for the struct
 pub struct AddressInfo {
-    pub name: String,
-    pub house_number: u8,
-    pub street: String,
-    pub city: String,
-}
-
-impl AddressInfo {
-    pub fn new(name: String, house_number: u8, street: String, city: String) -> Self {
-        AddressInfo {
-            name,
-            house_number,
-            street,
-            city,
-        }
-    }
+    #[max_len(50)] // set a max length for the string
+    pub name: String, // 4 bytes + 50 bytes
+    pub house_number: u8, // 1 byte
+    #[max_len(50)]
+    pub street: String, // 4 bytes + 50 bytes
+    #[max_len(50)]
+    pub city: String, // 4 bytes + 50 bytes
 }

+ 36 - 21
basics/account-data/anchor/tests/test.ts

@@ -1,36 +1,51 @@
-import * as anchor from "@coral-xyz/anchor";
-import { AnchorProgramExample } from "../target/types/anchor_program_example";
+import * as anchor from "@coral-xyz/anchor"
+import { AnchorProgramExample } from "../target/types/anchor_program_example"
+import { Keypair } from "@solana/web3.js"
 
 describe("Account Data!", () => {
-  const provider = anchor.AnchorProvider.env();
-  anchor.setProvider(provider);
-  const payer = provider.wallet as anchor.Wallet;
+  const provider = anchor.AnchorProvider.env()
+  anchor.setProvider(provider)
+  const payer = provider.wallet as anchor.Wallet
   const program = anchor.workspace
-    .AnchorProgramExample as anchor.Program<AnchorProgramExample>;
+    .AnchorProgramExample as anchor.Program<AnchorProgramExample>
 
-  const addressInfoAccount = anchor.web3.Keypair.generate();
+  // Generate a new keypair for the addressInfo account
+  const addressInfoAccount = new Keypair()
 
   it("Create the address info account", async () => {
-    console.log(`Payer Address      : ${payer.publicKey}`);
-    console.log(`Address Info Acct  : ${addressInfoAccount.publicKey}`);
+    console.log(`Payer Address      : ${payer.publicKey}`)
+    console.log(`Address Info Acct  : ${addressInfoAccount.publicKey}`)
+
+    // Instruction data
+    const addressInfo = {
+      name: "Joe C",
+      houseNumber: 136,
+      street: "Mile High Dr.",
+      city: "Solana Beach",
+    }
+
     await program.methods
-      .createAddressInfo("Joe C", 136, "Mile High Dr.", "Solana Beach")
+      .createAddressInfo(
+        addressInfo.name,
+        addressInfo.houseNumber,
+        addressInfo.street,
+        addressInfo.city
+      )
       .accounts({
         addressInfo: addressInfoAccount.publicKey,
         payer: payer.publicKey,
-        systemProgram: anchor.web3.SystemProgram.programId,
       })
-      .signers([payer.payer])
-      .rpc();
-  });
+      .signers([addressInfoAccount])
+      .rpc()
+  })
 
   it("Read the new account's data", async () => {
     const addressInfo = await program.account.addressInfo.fetch(
       addressInfoAccount.publicKey
-    );
-    console.log(`Name     : ${addressInfo.name}`);
-    console.log(`House Num: ${addressInfo.houseNumber}`);
-    console.log(`Street   : ${addressInfo.street}`);
-    console.log(`City     : ${addressInfo.city}`);
-  });
-});
+    )
+    console.log(`Name     : ${addressInfo.name}`)
+    console.log(`House Num: ${addressInfo.houseNumber}`)
+    console.log(`Street   : ${addressInfo.street}`)
+    console.log(`City     : ${addressInfo.city}`)
+  })
+})

+ 13 - 8
basics/checking-accounts/anchor/programs/anchor-program-example/src/lib.rs

@@ -8,20 +8,25 @@ declare_id!("ECWPhR3rJbaPfyNFgphnjxSEexbTArc7vxD8fnW6tgKw");
 pub mod anchor_program_example {
     use super::*;
 
-    #[allow(clippy::result_large_err)]
     pub fn check_accounts(_ctx: Context<CheckingAccounts>) -> Result<()> {
         Ok(())
     }
 }
 
+// Account validation in Anchor is done using the types and constraints specified in the #[derive(Accounts)] structs
+// This is a simple example and does not include all possible constraints and types
 #[derive(Accounts)]
 pub struct CheckingAccounts<'info> {
-    payer: Signer<'info>,
-    #[account(mut)]
-    /// CHECK: This account's data is empty
-    account_to_create: AccountInfo<'info>,
+    payer: Signer<'info>, // checks account is signer
+
+    /// CHECK: No checks performed, example of an unchecked account
     #[account(mut)]
-    /// CHECK: This account's data is empty
-    account_to_change: AccountInfo<'info>,
-    system_program: Program<'info, System>,
+    account_to_create: UncheckedAccount<'info>,
+    /// CHECK: Perform owner check using constraint
+    #[account(
+        mut,
+        owner = id()
+    )]
+    account_to_change: UncheckedAccount<'info>,
+    system_program: Program<'info, System>, // checks account is executable, and is the system program
 }

+ 27 - 22
basics/checking-accounts/anchor/tests/test.ts

@@ -1,45 +1,50 @@
-import * as anchor from "@coral-xyz/anchor";
-import { AnchorProgramExample } from "../target/types/anchor_program_example";
+import * as anchor from "@coral-xyz/anchor"
+import { AnchorProgramExample } from "../target/types/anchor_program_example"
+import {
+  Keypair,
+  SystemProgram,
+  Transaction,
+  sendAndConfirmTransaction,
+} from "@solana/web3.js"
 
 describe("Anchor example", () => {
-  const provider = anchor.AnchorProvider.env();
-  anchor.setProvider(provider);
+  const provider = anchor.AnchorProvider.env()
+  anchor.setProvider(provider)
   const program = anchor.workspace
-    .AnchorProgramExample as anchor.Program<AnchorProgramExample>;
-  const payer = provider.wallet as anchor.Wallet;
+    .AnchorProgramExample as anchor.Program<AnchorProgramExample>
+  const wallet = provider.wallet as anchor.Wallet
 
   // We'll create this ahead of time.
   // Our program will try to modify it.
-  const accountToChange = anchor.web3.Keypair.generate();
+  const accountToChange = new Keypair()
   // Our program will create this.
-  const accountToCreate = anchor.web3.Keypair.generate();
+  const accountToCreate = new Keypair()
 
   it("Create an account owned by our program", async () => {
-    let ix = anchor.web3.SystemProgram.createAccount({
+    let instruction = SystemProgram.createAccount({
       fromPubkey: provider.wallet.publicKey,
       newAccountPubkey: accountToChange.publicKey,
       lamports: await provider.connection.getMinimumBalanceForRentExemption(0),
       space: 0,
       programId: program.programId, // Our program
-    });
+    })
 
-    await anchor.web3.sendAndConfirmTransaction(
-      provider.connection,
-      new anchor.web3.Transaction().add(ix),
-      [payer.payer, accountToChange]
-    );
-  });
+    const transaction = new Transaction().add(instruction)
+
+    await sendAndConfirmTransaction(provider.connection, transaction, [
+      wallet.payer,
+      accountToChange,
+    ])
+  })
 
   it("Check accounts", async () => {
     await program.methods
       .checkAccounts()
       .accounts({
-        payer: provider.wallet.publicKey,
+        payer: wallet.publicKey,
         accountToCreate: accountToCreate.publicKey,
         accountToChange: accountToChange.publicKey,
-        systemProgram: anchor.web3.SystemProgram.programId,
       })
-      .signers([payer.payer])
-      .rpc();
-  });
-});
+      .rpc()
+  })
+})

+ 3 - 2
basics/close-account/anchor/Anchor.toml

@@ -1,14 +1,15 @@
 [features]
 seeds = false
 skip-lint = false
+
 [programs.localnet]
-close_account_program = "9SWqhEABWnKXTPvSLc4aQAJyESVxtRvYBvwF2WuBy7jf"
+close_account_program = "99TQtoDdQ5NS2v5Ppha93aqEmv3vV9VZVfHTP5rGST3c"
 
 [registry]
 url = "https://api.apr.dev"
 
 [provider]
-cluster = "localnet"
+cluster = "Localnet"
 wallet = "~/.config/solana/id.json"
 
 [scripts]

+ 9 - 15
basics/close-account/anchor/programs/close-account/src/instructions/close_user.rs

@@ -1,29 +1,23 @@
-use anchor_lang::prelude::*;
-use anchor_lang::AccountsClose;
-
 use crate::state::*;
+use anchor_lang::prelude::*;
 
 #[derive(Accounts)]
 pub struct CloseUserContext<'info> {
+    #[account(mut)]
+    pub user: Signer<'info>,
+
     #[account(
         mut,
         seeds = [
-            User::PREFIX.as_bytes(),
+            b"USER",
             user.key().as_ref(),
         ],
-        has_one = user,
-        bump = user_account.bump
+        bump = user_account.bump,
+        close = user, // close account and return lamports to user
     )]
-    pub user_account: Account<'info, User>,
-    #[account(mut)]
-    pub user: Signer<'info>,
-    pub system_program: Program<'info, System>,
-    pub rent: Sysvar<'info, Rent>,
+    pub user_account: Account<'info, UserState>,
 }
 
-pub fn close_user(ctx: Context<CloseUserContext>) -> Result<()> {
-    let user = &mut ctx.accounts.user;
-    let user_account = &mut ctx.accounts.user_account;
-    user_account.close(user.to_account_info())?;
+pub fn close_user(_ctx: Context<CloseUserContext>) -> Result<()> {
     Ok(())
 }

+ 15 - 26
basics/close-account/anchor/programs/close-account/src/instructions/create_user.rs

@@ -1,41 +1,30 @@
-use anchor_lang::prelude::*;
-
 use crate::state::*;
-
-#[derive(AnchorSerialize, AnchorDeserialize)]
-pub struct CreateUserArgs {
-    pub name: String,
-}
+use anchor_lang::prelude::*;
 
 #[derive(Accounts)]
-#[instruction(args: CreateUserArgs)]
 pub struct CreateUserContext<'info> {
+    #[account(mut)]
+    pub user: Signer<'info>,
+
     #[account(
         init,
-        space = User::SIZE,
-        payer = payer,
+        payer = user,
+        space = UserState::INIT_SPACE,
         seeds = [
-            User::PREFIX.as_bytes(),
-            payer.key().as_ref(),
+            b"USER",
+            user.key().as_ref(),
         ],
         bump
     )]
-    pub user_account: Account<'info, User>,
-    #[account(mut)]
-    pub payer: Signer<'info>,
+    pub user_account: Account<'info, UserState>,
     pub system_program: Program<'info, System>,
-    pub rent: Sysvar<'info, Rent>,
 }
 
-pub fn create_user(ctx: Context<CreateUserContext>, args: CreateUserArgs) -> Result<()> {
-    let payer = &ctx.accounts.payer;
-    let user_account = &mut ctx.accounts.user_account;
-
-    msg!("{:#?}", ctx.bumps);
-
-    user_account.bump = *ctx.bumps.get("user_account").expect("Bump not found.");
-    user_account.user = payer.key();
-    user_account.name = args.name;
-
+pub fn create_user(ctx: Context<CreateUserContext>, name: String) -> Result<()> {
+    *ctx.accounts.user_account = UserState {
+        bump: *ctx.bumps.get("user_account").unwrap(),
+        user: ctx.accounts.user.key(),
+        name,
+    };
     Ok(())
 }

+ 3 - 4
basics/close-account/anchor/programs/close-account/src/lib.rs

@@ -1,19 +1,18 @@
 #![allow(clippy::result_large_err)]
 
 use anchor_lang::prelude::*;
-
 mod instructions;
 mod state;
 use instructions::*;
 
-declare_id!("9SWqhEABWnKXTPvSLc4aQAJyESVxtRvYBvwF2WuBy7jf");
+declare_id!("99TQtoDdQ5NS2v5Ppha93aqEmv3vV9VZVfHTP5rGST3c");
 
 #[program]
 pub mod close_account_program {
     use super::*;
 
-    pub fn create_user(ctx: Context<CreateUserContext>, args: CreateUserArgs) -> Result<()> {
-        create_user::create_user(ctx, args)
+    pub fn create_user(ctx: Context<CreateUserContext>, name: String) -> Result<()> {
+        create_user::create_user(ctx, name)
     }
 
     pub fn close_user(ctx: Context<CloseUserContext>) -> Result<()> {

+ 2 - 3
basics/close-account/anchor/programs/close-account/src/state/mod.rs

@@ -1,3 +1,2 @@
-pub mod user;
-
-pub use user::*;
+pub mod user_state;
+pub use user_state::*;

+ 0 - 18
basics/close-account/anchor/programs/close-account/src/state/user.rs

@@ -1,18 +0,0 @@
-use anchor_lang::prelude::*;
-
-#[account]
-pub struct User {
-    pub bump: u8,
-    pub user: Pubkey,
-    pub name: String,
-}
-
-impl User {
-    pub const PREFIX: &'static str = "USER";
-
-    pub const SIZE: usize = 8 + /* discriminator */
-        std::mem::size_of::<u8>() + /* bump */
-        std::mem::size_of::<Pubkey>() + /* user */
-        80 /* name */
-    ;
-}

+ 10 - 0
basics/close-account/anchor/programs/close-account/src/state/user_state.rs

@@ -0,0 +1,10 @@
+use anchor_lang::prelude::*;
+
+#[account]
+#[derive(InitSpace)] // automatically calculate the space required for the struct
+pub struct UserState {
+    pub bump: u8,     // 1 byte
+    pub user: Pubkey, // 32 bytes
+    #[max_len(50)] // set a max length for the string
+    pub name: String, // 4 bytes + 50 bytes
+}

+ 33 - 78
basics/close-account/anchor/tests/close-account.ts

@@ -1,99 +1,54 @@
-import * as anchor from "@coral-xyz/anchor";
-import { Program } from "@coral-xyz/anchor";
-import { Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
-import { CloseAccountProgram } from "../target/types/close_account_program";
-import {
-  BlockheightBasedTransactionConfirmationStrategy,
-  PublicKey,
-} from "@solana/web3.js";
-import assert from "assert";
+import * as anchor from "@coral-xyz/anchor"
+import { Program } from "@coral-xyz/anchor"
+import { CloseAccountProgram } from "../target/types/close_account_program"
+import { PublicKey } from "@solana/web3.js"
+import assert from "assert"
 
 describe("close-an-account", () => {
   // Configure the client to use the local cluster.
-  anchor.setProvider(anchor.AnchorProvider.env());
+  const provider = anchor.AnchorProvider.env()
+  anchor.setProvider(provider)
 
   const program = anchor.workspace
-    .CloseAccountProgram as Program<CloseAccountProgram>;
-  const connection = program.provider.connection;
-  const payer = Keypair.generate();
+    .CloseAccountProgram as Program<CloseAccountProgram>
+  const payer = provider.wallet as anchor.Wallet
 
-  async function airdrop(receiver: PublicKey, amount: number) {
-    const sig = await program.provider.connection.requestAirdrop(
-      receiver,
-      amount
-    );
-    const blockStats = await program.provider.connection.getLatestBlockhash();
-    const strategy: BlockheightBasedTransactionConfirmationStrategy = {
-      signature: sig,
-      blockhash: blockStats.blockhash,
-      lastValidBlockHeight: blockStats.lastValidBlockHeight,
-    };
-    await program.provider.connection.confirmTransaction(strategy, "confirmed");
-  }
-
-  function getUserAccount(user: PublicKey): [PublicKey, number] {
-    return PublicKey.findProgramAddressSync(
-      [Buffer.from("USER"), user.toBuffer()],
-      program.programId
-    );
-  }
-
-  it("Airdrop", async () => {
-    const balanceBefore = await connection.getBalance(payer.publicKey);
-    await airdrop(payer.publicKey, LAMPORTS_PER_SOL);
-    const balanceAfter = await connection.getBalance(payer.publicKey);
-    assert.equal(balanceAfter, balanceBefore + LAMPORTS_PER_SOL);
-  });
+  // Derive the PDA for the user's account.
+  const [userAccountAddress] = PublicKey.findProgramAddressSync(
+    [Buffer.from("USER"), payer.publicKey.toBuffer()],
+    program.programId
+  )
 
   it("Create Account", async () => {
-    const [userAccountAddress] = getUserAccount(payer.publicKey);
-    const userAccountBefore = await program.account.user.fetchNullable(
-      userAccountAddress,
-      "confirmed"
-    );
-    assert.equal(userAccountBefore, null);
-
     await program.methods
-      .createUser({
-        name: "John Doe",
-      })
+      .createUser("John Doe")
       .accounts({
-        payer: payer.publicKey,
+        user: payer.publicKey,
         userAccount: userAccountAddress,
       })
-      .signers([payer])
-      .rpc({ commitment: "confirmed", skipPreflight: true });
+      .rpc()
 
-    const userAccountAfter = await program.account.user.fetchNullable(
-      userAccountAddress,
-      "confirmed"
-    );
-    assert.notEqual(userAccountAfter, null);
-    assert.equal(userAccountAfter.name, "John Doe");
-    assert.equal(userAccountAfter.user.toBase58(), payer.publicKey.toBase58());
-  });
+    // Fetch the account data
+    const userAccount = await program.account.userState.fetch(
+      userAccountAddress
+    )
+    assert.equal(userAccount.name, "John Doe")
+    assert.equal(userAccount.user.toBase58(), payer.publicKey.toBase58())
+  })
 
   it("Close Account", async () => {
-    const [userAccountAddress] = getUserAccount(payer.publicKey);
-    const userAccountBefore = await program.account.user.fetchNullable(
-      userAccountAddress,
-      "confirmed"
-    );
-    assert.notEqual(userAccountBefore, null);
-
     await program.methods
       .closeUser()
       .accounts({
         user: payer.publicKey,
         userAccount: userAccountAddress,
       })
-      .signers([payer])
-      .rpc({ commitment: "confirmed" });
-
-    const userAccountAfter = await program.account.user.fetchNullable(
-      userAccountAddress,
-      "processed"
-    );
-    assert.equal(userAccountAfter, null);
-  });
-});
+      .rpc()
+
+    // The account should no longer exist, returning null.
+    const userAccount = await program.account.userState.fetchNullable(
+      userAccountAddress
+    )
+    assert.equal(userAccount, null)
+  })
+})

+ 3 - 2
basics/counter/anchor/Anchor.toml

@@ -1,14 +1,15 @@
 [features]
 seeds = false
 skip-lint = false
+
 [programs.localnet]
-counter_anchor = "Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"
+counter_anchor = "BmDHboaj1kBUoinJKKSRqKfMeRKJqQqEbUj1VgzeQe4A"
 
 [registry]
 url = "https://api.apr.dev"
 
 [provider]
-cluster = "localnet"
+cluster = "Localnet"
 wallet = "~/.config/solana/id.json"
 
 [scripts]

+ 15 - 9
basics/counter/anchor/programs/counter_anchor/src/lib.rs

@@ -2,7 +2,7 @@
 
 use anchor_lang::prelude::*;
 
-declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
+declare_id!("BmDHboaj1kBUoinJKKSRqKfMeRKJqQqEbUj1VgzeQe4A");
 
 #[program]
 pub mod counter_anchor {
@@ -13,22 +13,22 @@ pub mod counter_anchor {
     }
 
     pub fn increment(ctx: Context<Increment>) -> Result<()> {
-        ctx.accounts.counter.count += 1;
+        ctx.accounts.counter.count = ctx.accounts.counter.count.checked_add(1).unwrap();
         Ok(())
     }
 }
 
-#[account]
-pub struct Counter {
-    count: u64,
-}
-
 #[derive(Accounts)]
 pub struct InitializeCounter<'info> {
-    #[account(init, space=8+8, payer=payer)]
-    pub counter: Account<'info, Counter>,
     #[account(mut)]
     pub payer: Signer<'info>,
+
+    #[account(
+        init,
+        space = 8 + Counter::INIT_SPACE,
+        payer = payer
+    )]
+    pub counter: Account<'info, Counter>,
     pub system_program: Program<'info, System>,
 }
 
@@ -37,3 +37,9 @@ pub struct Increment<'info> {
     #[account(mut)]
     pub counter: Account<'info, Counter>,
 }
+
+#[account]
+#[derive(InitSpace)]
+pub struct Counter {
+    count: u64,
+}

+ 49 - 34
basics/counter/anchor/tests/counter_anchor.ts

@@ -1,48 +1,63 @@
-import * as anchor from "@coral-xyz/anchor";
-import { Program } from "@coral-xyz/anchor";
-import { Keypair } from "@solana/web3.js";
-import { assert } from "chai";
-import { CounterAnchor } from "../target/types/counter_anchor";
+import * as anchor from "@coral-xyz/anchor"
+import { Program } from "@coral-xyz/anchor"
+import { Keypair } from "@solana/web3.js"
+import { assert } from "chai"
+import { CounterAnchor } from "../target/types/counter_anchor"
 
 describe("counter_anchor", () => {
   // Configure the client to use the local cluster.
-  anchor.setProvider(anchor.AnchorProvider.env());
+  const provider = anchor.AnchorProvider.env()
+  anchor.setProvider(provider)
+  const payer = provider.wallet as anchor.Wallet
 
-  const program = anchor.workspace.CounterAnchor as Program<CounterAnchor>;
+  const program = anchor.workspace.CounterAnchor as Program<CounterAnchor>
 
-  it("Test increment", async () => {
-    const counterKeypair = Keypair.generate();
-    const counter = counterKeypair.publicKey;
+  // Generate a new keypair for the counter account
+  const counterKeypair = new Keypair()
 
-    // Initialize counter
+  it("Initialize Counter", async () => {
     await program.methods
       .initializeCounter()
-      .accounts({ counter, payer: program.provider.publicKey })
+      .accounts({
+        counter: counterKeypair.publicKey,
+        payer: payer.publicKey,
+      })
       .signers([counterKeypair])
-      .rpc({ skipPreflight: true, commitment: "confirmed" });
-    let currentCount = (
-      await program.account.counter.fetch(counter, "confirmed")
-    ).count.toNumber();
-    assert(currentCount === 0, "Expected initialized count to be 0");
+      .rpc()
 
-    // Increment counter
+    const currentCount = await program.account.counter.fetch(
+      counterKeypair.publicKey
+    )
+
+    assert(
+      currentCount.count.toNumber() === 0,
+      "Expected initialized count to be 0"
+    )
+  })
+
+  it("Increment Counter", async () => {
     await program.methods
       .increment()
-      .accounts({ counter })
-      .rpc({ skipPreflight: true, commitment: "confirmed" });
-    currentCount = (
-      await program.account.counter.fetch(counter, "confirmed")
-    ).count.toNumber();
-    assert(currentCount === 1, "Expected count to be 1");
-
-    // Increment counter
+      .accounts({ counter: counterKeypair.publicKey })
+      .rpc()
+
+    const currentCount = await program.account.counter.fetch(
+      counterKeypair.publicKey
+    )
+
+    assert(currentCount.count.toNumber() === 1, "Expected  count to be 1")
+  })
+
+  it("Increment Counter Again", async () => {
     await program.methods
       .increment()
-      .accounts({ counter })
-      .rpc({ skipPreflight: true, commitment: "confirmed" });
-    currentCount = (
-      await program.account.counter.fetch(counter, "confirmed")
-    ).count.toNumber();
-    assert(currentCount === 2, "Expected count to be 2");
-  });
-});
+      .accounts({ counter: counterKeypair.publicKey })
+      .rpc()
+
+    const currentCount = await program.account.counter.fetch(
+      counterKeypair.publicKey
+    )
+
+    assert(currentCount.count.toNumber() === 2, "Expected  count to be 2")
+  })
+})

+ 5 - 3
basics/create-account/anchor/Anchor.toml

@@ -1,13 +1,15 @@
 [features]
 seeds = false
+skip-lint = false
+
 [programs.localnet]
-create_system_account = "6gUwvaZPvC8ZxKuC1h5aKz4mRd7pFyEfUZckiEsBZSbk"
+create_system_account = "ARVNCsYKDQsCLHbwUTJLpFXVrJdjhWZStyzvxmKe2xHi"
 
 [registry]
-url = "https://anchor.projectserum.com"
+url = "https://api.apr.dev"
 
 [provider]
-cluster = "localnet"
+cluster = "Localnet"
 wallet = "~/.config/solana/id.json"
 
 [scripts]

+ 9 - 8
basics/create-account/anchor/programs/create-system-account/src/lib.rs

@@ -1,11 +1,9 @@
 #![allow(clippy::result_large_err)]
 
 use anchor_lang::prelude::*;
-use anchor_lang::system_program;
+use anchor_lang::system_program::{create_account, CreateAccount};
 
-declare_id!("6gUwvaZPvC8ZxKuC1h5aKz4mRd7pFyEfUZckiEsBZSbk");
-
-const LAMPORTS_PER_SOL: u64 = 1000000000;
+declare_id!("ARVNCsYKDQsCLHbwUTJLpFXVrJdjhWZStyzvxmKe2xHi");
 
 #[program]
 pub mod create_system_account {
@@ -18,17 +16,20 @@ pub mod create_system_account {
             &ctx.accounts.new_account.key().to_string()
         );
 
-        system_program::create_account(
+        // The minimum lamports for rent exemption
+        let lamports = (Rent::get()?).minimum_balance(0);
+
+        create_account(
             CpiContext::new(
                 ctx.accounts.system_program.to_account_info(),
-                system_program::CreateAccount {
+                CreateAccount {
                     from: ctx.accounts.payer.to_account_info(), // From pubkey
                     to: ctx.accounts.new_account.to_account_info(), // To pubkey
                 },
             ),
-            LAMPORTS_PER_SOL,                   // Lamports (1 SOL)
+            lamports,                           // Lamports
             0,                                  // Space
-            &ctx.accounts.system_program.key(), // Owner
+            &ctx.accounts.system_program.key(), // Owner Program
         )?;
 
         msg!("Account created succesfully.");

+ 23 - 12
basics/create-account/anchor/tests/test.ts

@@ -1,24 +1,35 @@
-import * as anchor from "@coral-xyz/anchor";
-import { CreateSystemAccount } from "../target/types/create_system_account";
+import * as anchor from "@coral-xyz/anchor"
+import { CreateSystemAccount } from "../target/types/create_system_account"
+import { Keypair, SystemProgram } from "@solana/web3.js"
+import { assert } from "chai"
 
 describe("Create a system account", () => {
-  const provider = anchor.AnchorProvider.env();
-  anchor.setProvider(provider);
-  const wallet = provider.wallet as anchor.Wallet;
+  const provider = anchor.AnchorProvider.env()
+  anchor.setProvider(provider)
+  const wallet = provider.wallet as anchor.Wallet
+  const connection = provider.connection
   const program = anchor.workspace
-    .CreateSystemAccount as anchor.Program<CreateSystemAccount>;
+    .CreateSystemAccount as anchor.Program<CreateSystemAccount>
 
   it("Create the account", async () => {
-    const newKeypair = anchor.web3.Keypair.generate();
+    // Generate a new keypair for the new account
+    const newKeypair = new Keypair()
 
     await program.methods
       .createSystemAccount()
       .accounts({
         payer: wallet.publicKey,
         newAccount: newKeypair.publicKey,
-        systemProgram: anchor.web3.SystemProgram.programId,
       })
-      .signers([wallet.payer, newKeypair])
-      .rpc();
-  });
-});
+      .signers([newKeypair])
+      .rpc()
+
+    // Minimum balance for rent exemption for new account
+    const lamports = await connection.getMinimumBalanceForRentExemption(0)
+
+    // Check that the account was created
+    const accountInfo = await connection.getAccountInfo(newKeypair.publicKey)
+    assert((accountInfo.owner = SystemProgram.programId))
+    assert(accountInfo.lamports === lamports)
+  })
+})

+ 6 - 4
basics/cross-program-invocation/anchor/Anchor.toml

@@ -1,14 +1,16 @@
 [features]
 seeds = false
+skip-lint = false
+
 [programs.localnet]
-hand = "ABoYG2GWbzLgnnGhK2pUGNupzKoYe7UGk2idrAXbstAS"
-lever = "EnjN3cm7xYqYHNUZbQfhJYj5S5RBrSU9tc5aHwQ6LqvT"
+hand = "EJfTLXDCJTVwBgGpz9X2Me4CWHbvg8F8zsM7fiVJLLeR"
+lever = "CABVoybzrbAJSv7QhQd6GXNGKxDMRjw9niqFzizhk6uk"
 
 [registry]
-url = "https://anchor.projectserum.com"
+url = "https://api.apr.dev"
 
 [provider]
-cluster = "localnet"
+cluster = "Localnet"
 wallet = "~/.config/solana/id.json"
 
 [scripts]

+ 1 - 1
basics/cross-program-invocation/anchor/programs/hand/src/lib.rs

@@ -5,7 +5,7 @@ use lever::cpi::accounts::SetPowerStatus;
 use lever::program::Lever;
 use lever::{self, PowerStatus};
 
-declare_id!("ABoYG2GWbzLgnnGhK2pUGNupzKoYe7UGk2idrAXbstAS");
+declare_id!("EJfTLXDCJTVwBgGpz9X2Me4CWHbvg8F8zsM7fiVJLLeR");
 
 #[program]
 mod hand {

+ 1 - 1
basics/cross-program-invocation/anchor/programs/lever/src/lib.rs

@@ -2,7 +2,7 @@
 
 use anchor_lang::prelude::*;
 
-declare_id!("EnjN3cm7xYqYHNUZbQfhJYj5S5RBrSU9tc5aHwQ6LqvT");
+declare_id!("CABVoybzrbAJSv7QhQd6GXNGKxDMRjw9niqFzizhk6uk");
 
 #[program]
 pub mod lever {

+ 17 - 16
basics/cross-program-invocation/anchor/tests/test.ts

@@ -1,14 +1,16 @@
-import * as anchor from "@coral-xyz/anchor";
-import { Hand } from "../target/types/hand";
-import { Lever } from "../target/types/lever";
+import * as anchor from "@coral-xyz/anchor"
+import { Hand } from "../target/types/hand"
+import { Lever } from "../target/types/lever"
+import { Keypair } from "@solana/web3.js"
 
 describe("CPI Example", () => {
-  const provider = anchor.AnchorProvider.env();
-  anchor.setProvider(provider);
-  const hand = anchor.workspace.Hand as anchor.Program<Hand>;
-  const lever = anchor.workspace.Lever as anchor.Program<Lever>;
+  const provider = anchor.AnchorProvider.env()
+  anchor.setProvider(provider)
+  const hand = anchor.workspace.Hand as anchor.Program<Hand>
+  const lever = anchor.workspace.Lever as anchor.Program<Lever>
 
-  const powerAccount = anchor.web3.Keypair.generate();
+  // Generate a new keypair for the power account
+  const powerAccount = new Keypair()
 
   it("Initialize the lever!", async () => {
     await lever.methods
@@ -16,11 +18,10 @@ describe("CPI Example", () => {
       .accounts({
         power: powerAccount.publicKey,
         user: provider.wallet.publicKey,
-        systemProgram: anchor.web3.SystemProgram.programId,
       })
       .signers([powerAccount])
-      .rpc();
-  });
+      .rpc()
+  })
 
   it("Pull the lever!", async () => {
     await hand.methods
@@ -29,8 +30,8 @@ describe("CPI Example", () => {
         power: powerAccount.publicKey,
         leverProgram: lever.programId,
       })
-      .rpc();
-  });
+      .rpc()
+  })
 
   it("Pull it again!", async () => {
     await hand.methods
@@ -39,6 +40,6 @@ describe("CPI Example", () => {
         power: powerAccount.publicKey,
         leverProgram: lever.programId,
       })
-      .rpc();
-  });
-});
+      .rpc()
+  })
+})

+ 5 - 3
basics/hello-solana/anchor/Anchor.toml

@@ -1,13 +1,15 @@
 [features]
 seeds = false
+skip-lint = false
+
 [programs.localnet]
-hello_solana = "2nYa9FRtxLnaGa5agENEE1ehy6Tr2HnyziwG7ynnyhPC"
+hello_solana = "2phbC62wekpw95XuBk4i1KX4uA8zBUWmYbiTMhicSuBV"
 
 [registry]
-url = "https://anchor.projectserum.com"
+url = "https://api.apr.dev"
 
 [provider]
-cluster = "localnet"
+cluster = "Localnet"
 wallet = "~/.config/solana/id.json"
 
 [scripts]

+ 1 - 1
basics/hello-solana/anchor/programs/hello-solana/src/lib.rs

@@ -2,7 +2,7 @@
 
 use anchor_lang::prelude::*;
 
-declare_id!("2nYa9FRtxLnaGa5agENEE1ehy6Tr2HnyziwG7ynnyhPC");
+declare_id!("2phbC62wekpw95XuBk4i1KX4uA8zBUWmYbiTMhicSuBV");
 
 #[program]
 pub mod hello_solana {

+ 30 - 28
basics/pda-rent-payer/anchor/programs/anchor-program-example/src/instructions/create_new_account.rs

@@ -1,40 +1,42 @@
 use anchor_lang::prelude::*;
-
-use crate::state::RentVault;
-
-pub fn create_new_account(ctx: Context<CreateNewAccount>) -> Result<()> {
-    // Assuming this account has no inner data (size 0)
-    //
-    let lamports_required_for_rent = (Rent::get()?).minimum_balance(0);
-
-    **ctx
-        .accounts
-        .rent_vault
-        .to_account_info()
-        .lamports
-        .borrow_mut() -= lamports_required_for_rent;
-    **ctx
-        .accounts
-        .new_account
-        .to_account_info()
-        .lamports
-        .borrow_mut() += lamports_required_for_rent;
-
-    Ok(())
-}
+use anchor_lang::system_program::{create_account, CreateAccount};
 
 #[derive(Accounts)]
 pub struct CreateNewAccount<'info> {
-    /// CHECK: Unchecked
     #[account(mut)]
-    new_account: SystemAccount<'info>,
+    new_account: Signer<'info>,
+
     #[account(
         mut,
         seeds = [
-            RentVault::SEED_PREFIX.as_bytes(),
+            b"rent_vault",
         ],
-        bump = rent_vault.bump,
+        bump,
     )]
-    rent_vault: Account<'info, RentVault>,
+    rent_vault: SystemAccount<'info>,
     system_program: Program<'info, System>,
 }
+
+pub fn create_new_account(ctx: Context<CreateNewAccount>) -> Result<()> {
+    // PDA signer seeds
+    let signer_seeds: &[&[&[u8]]] = &[&[b"rent_vault", &[*ctx.bumps.get("rent_vault").unwrap()]]];
+
+    // The minimum lamports for rent exemption
+    let lamports = (Rent::get()?).minimum_balance(0);
+
+    // Create the new account, transferring lamports from the rent vault to the new account
+    create_account(
+        CpiContext::new(
+            ctx.accounts.system_program.to_account_info(),
+            CreateAccount {
+                from: ctx.accounts.rent_vault.to_account_info(), // From pubkey
+                to: ctx.accounts.new_account.to_account_info(),  // To pubkey
+            },
+        )
+        .with_signer(signer_seeds),
+        lamports,                           // Lamports
+        0,                                  // Space
+        &ctx.accounts.system_program.key(), // Owner Program
+    )?;
+    Ok(())
+}

+ 20 - 24
basics/pda-rent-payer/anchor/programs/anchor-program-example/src/instructions/init_rent_vault.rs

@@ -1,16 +1,29 @@
 use anchor_lang::prelude::*;
-use anchor_lang::system_program;
+use anchor_lang::system_program::{transfer, Transfer};
 
-use crate::state::RentVault;
+#[derive(Accounts)]
+pub struct InitRentVault<'info> {
+    #[account(mut)]
+    payer: Signer<'info>,
+
+    #[account(
+        mut,
+        seeds = [
+            b"rent_vault",
+        ],
+        bump,
+    )]
+    rent_vault: SystemAccount<'info>,
+    system_program: Program<'info, System>,
+}
 
+// When lamports are transferred to a new address (without and existing account),
+// An account owned by the system program is created by default
 pub fn init_rent_vault(ctx: Context<InitRentVault>, fund_lamports: u64) -> Result<()> {
-    ctx.accounts.rent_vault.set_inner(RentVault {
-        bump: *ctx.bumps.get(RentVault::SEED_PREFIX).unwrap(),
-    });
-    system_program::transfer(
+    transfer(
         CpiContext::new(
             ctx.accounts.system_program.to_account_info(),
-            system_program::Transfer {
+            Transfer {
                 from: ctx.accounts.payer.to_account_info(),
                 to: ctx.accounts.rent_vault.to_account_info(),
             },
@@ -19,20 +32,3 @@ pub fn init_rent_vault(ctx: Context<InitRentVault>, fund_lamports: u64) -> Resul
     )?;
     Ok(())
 }
-
-#[derive(Accounts)]
-pub struct InitRentVault<'info> {
-    #[account(
-        init,
-        space = RentVault::ACCOUNT_SPACE,
-        payer = payer,
-        seeds = [
-            RentVault::SEED_PREFIX.as_bytes(),
-        ],
-        bump,
-    )]
-    rent_vault: Account<'info, RentVault>,
-    #[account(mut)]
-    payer: Signer<'info>,
-    system_program: Program<'info, System>,
-}

+ 2 - 6
basics/pda-rent-payer/anchor/programs/anchor-program-example/src/lib.rs

@@ -1,11 +1,7 @@
 #![allow(clippy::result_large_err)]
-
 use anchor_lang::prelude::*;
-
 use instructions::*;
-
 pub mod instructions;
-pub mod state;
 
 declare_id!("7Hm9nsYVuBZ9rf8z9AMUHreZRv8Q4vLhqwdVTCawRZtA");
 
@@ -14,10 +10,10 @@ pub mod pda_rent_payer {
     use super::*;
 
     pub fn init_rent_vault(ctx: Context<InitRentVault>, fund_lamports: u64) -> Result<()> {
-        instructions::init_rent_vault::init_rent_vault(ctx, fund_lamports)
+        init_rent_vault::init_rent_vault(ctx, fund_lamports)
     }
 
     pub fn create_new_account(ctx: Context<CreateNewAccount>) -> Result<()> {
-        instructions::create_new_account::create_new_account(ctx)
+        create_new_account::create_new_account(ctx)
     }
 }

+ 0 - 11
basics/pda-rent-payer/anchor/programs/anchor-program-example/src/state/mod.rs

@@ -1,11 +0,0 @@
-use anchor_lang::prelude::*;
-
-#[account]
-pub struct RentVault {
-    pub bump: u8,
-}
-
-impl RentVault {
-    pub const SEED_PREFIX: &'static str = "rent_vault";
-    pub const ACCOUNT_SPACE: usize = 8 + 8;
-}

+ 43 - 28
basics/pda-rent-payer/anchor/tests/test.ts

@@ -1,43 +1,58 @@
-import * as anchor from "@coral-xyz/anchor";
-import { PdaRentPayer } from "../target/types/pda_rent_payer";
+import * as anchor from "@coral-xyz/anchor"
+import { PdaRentPayer } from "../target/types/pda_rent_payer"
+import { LAMPORTS_PER_SOL, PublicKey, Keypair } from "@solana/web3.js"
+import { assert } from "chai"
 
 describe("PDA Rent-Payer", () => {
-  const provider = anchor.AnchorProvider.env();
-  anchor.setProvider(provider);
-  const wallet = provider.wallet as anchor.Wallet;
-  const program = anchor.workspace.PdaRentPayer as anchor.Program<PdaRentPayer>;
-
-  function deriveRentVaultPda() {
-    const pda = anchor.web3.PublicKey.findProgramAddressSync(
-      [Buffer.from("rent_vault")],
-      program.programId
-    );
-    console.log(`PDA: ${pda[0].toBase58()}`);
-    return pda;
-  }
+  const provider = anchor.AnchorProvider.env()
+  anchor.setProvider(provider)
+  const wallet = provider.wallet as anchor.Wallet
+  const connection = provider.connection
+  const program = anchor.workspace.PdaRentPayer as anchor.Program<PdaRentPayer>
+
+  // PDA for the Rent Vault
+  const [rentVaultPDA] = PublicKey.findProgramAddressSync(
+    [Buffer.from("rent_vault")],
+    program.programId
+  )
 
   it("Initialize the Rent Vault", async () => {
-    const [rentVaultPda, _] = deriveRentVaultPda();
+    // 1 SOL
+    const fundAmount = new anchor.BN(LAMPORTS_PER_SOL)
+
     await program.methods
-      .initRentVault(new anchor.BN(1000000000))
+      .initRentVault(fundAmount)
       .accounts({
-        rentVault: rentVaultPda,
         payer: wallet.publicKey,
+        rentVault: rentVaultPDA,
       })
-      .signers([wallet.payer])
-      .rpc();
-  });
+      .rpc()
+
+    // Check rent vault balance
+    const accountInfo = await program.provider.connection.getAccountInfo(
+      rentVaultPDA
+    )
+    assert(accountInfo.lamports === fundAmount.toNumber())
+  })
 
   it("Create a new account using the Rent Vault", async () => {
-    const newAccount = anchor.web3.Keypair.generate();
-    const [rentVaultPda, _] = deriveRentVaultPda();
+    // Generate a new keypair for the new account
+    const newAccount = new Keypair()
+
     await program.methods
       .createNewAccount()
       .accounts({
+        rentVault: rentVaultPDA,
         newAccount: newAccount.publicKey,
-        rentVault: rentVaultPda,
       })
-      .signers([wallet.payer])
-      .rpc();
-  });
-});
+      .signers([newAccount])
+      .rpc()
+
+    // Minimum balance for rent exemption for new account
+    const lamports = await connection.getMinimumBalanceForRentExemption(0)
+
+    // Check that the account was created
+    const accountInfo = await connection.getAccountInfo(newAccount.publicKey)
+    assert(accountInfo.lamports === lamports)
+  })
+})

+ 1 - 1
basics/processing-instructions/anchor/Anchor.toml

@@ -4,7 +4,7 @@ seeds = false
 processing_instructions = "DgoL5J44aspizyUs9fcnpGEUJjWTLJRCfx8eYtUMYczf"
 
 [registry]
-url = "https://anchor.projectserum.com"
+url = "https://api.apr.dev"
 
 [provider]
 cluster = "localnet"

+ 16 - 18
basics/program-derived-addresses/anchor/programs/anchor-program-example/src/instructions/create.rs

@@ -1,32 +1,30 @@
-use anchor_lang::prelude::*;
-
 use crate::state::PageVisits;
-
-pub fn create_page_visits(ctx: Context<CreatePageVisits>) -> Result<()> {
-    ctx.accounts.page_visits.set_inner(PageVisits::new(
-        0,
-        *ctx.bumps
-            .get(PageVisits::SEED_PREFIX)
-            .expect("Bump not found."),
-    ));
-    Ok(())
-}
+use anchor_lang::prelude::*;
 
 #[derive(Accounts)]
 pub struct CreatePageVisits<'info> {
+    #[account(mut)]
+    payer: Signer<'info>,
+
     #[account(
         init,
-        space = PageVisits::ACCOUNT_SPACE,
+        space = 8 + PageVisits::INIT_SPACE,
         payer = payer,
         seeds = [
-            PageVisits::SEED_PREFIX.as_bytes(),
-            user.key().as_ref(),
+            PageVisits::SEED_PREFIX,
+            payer.key().as_ref(),
         ],
         bump,
     )]
     page_visits: Account<'info, PageVisits>,
-    user: SystemAccount<'info>,
-    #[account(mut)]
-    payer: Signer<'info>,
     system_program: Program<'info, System>,
 }
+
+pub fn create_page_visits(ctx: Context<CreatePageVisits>) -> Result<()> {
+    *ctx.accounts.page_visits = PageVisits {
+        page_visits: 0,
+        bump: *ctx.bumps.get("page_visits").unwrap(),
+    };
+
+    Ok(())
+}

+ 10 - 14
basics/program-derived-addresses/anchor/programs/anchor-program-example/src/instructions/increment.rs

@@ -1,26 +1,22 @@
-use anchor_lang::prelude::*;
-
 use crate::state::PageVisits;
-
-pub fn increment_page_visits(ctx: Context<IncrementPageVisits>) -> Result<()> {
-    let page_visits = &mut ctx.accounts.page_visits;
-    page_visits.increment();
-    Ok(())
-}
+use anchor_lang::prelude::*;
 
 #[derive(Accounts)]
 pub struct IncrementPageVisits<'info> {
+    user: SystemAccount<'info>,
     #[account(
         mut,
         seeds = [
-            PageVisits::SEED_PREFIX.as_bytes(),
+            PageVisits::SEED_PREFIX,
             user.key().as_ref(),
         ],
-        bump,
+        bump = page_visits.bump,
     )]
     page_visits: Account<'info, PageVisits>,
-    user: SystemAccount<'info>,
-    #[account(mut)]
-    payer: Signer<'info>,
-    system_program: Program<'info, System>,
+}
+
+pub fn increment_page_visits(ctx: Context<IncrementPageVisits>) -> Result<()> {
+    let page_visits = &mut ctx.accounts.page_visits;
+    page_visits.increment();
+    Ok(())
 }

+ 2 - 2
basics/program-derived-addresses/anchor/programs/anchor-program-example/src/lib.rs

@@ -14,10 +14,10 @@ pub mod anchor_program_example {
     use super::*;
 
     pub fn create_page_visits(ctx: Context<CreatePageVisits>) -> Result<()> {
-        instructions::create::create_page_visits(ctx)
+        create::create_page_visits(ctx)
     }
 
     pub fn increment_page_visits(ctx: Context<IncrementPageVisits>) -> Result<()> {
-        instructions::increment::increment_page_visits(ctx)
+        increment::increment_page_visits(ctx)
     }
 }

+ 3 - 8
basics/program-derived-addresses/anchor/programs/anchor-program-example/src/state/page_visits.rs

@@ -1,21 +1,16 @@
 use anchor_lang::prelude::*;
 
 #[account]
+#[derive(InitSpace)] // automatically calculate the space required for the struct
 pub struct PageVisits {
     pub page_visits: u32,
     pub bump: u8,
 }
 
 impl PageVisits {
-    pub const ACCOUNT_SPACE: usize = 8 + 32;
-
-    pub const SEED_PREFIX: &'static str = "page_visits";
-
-    pub fn new(page_visits: u32, bump: u8) -> Self {
-        PageVisits { page_visits, bump }
-    }
+    pub const SEED_PREFIX: &[u8; 11] = b"page_visits";
 
     pub fn increment(&mut self) {
-        self.page_visits += 1;
+        self.page_visits = self.page_visits.checked_add(1).unwrap();
     }
 }

+ 27 - 55
basics/program-derived-addresses/anchor/tests/test.ts

@@ -1,80 +1,52 @@
-import * as anchor from "@coral-xyz/anchor";
-import { AnchorProgramExample } from "../target/types/anchor_program_example";
+import * as anchor from "@coral-xyz/anchor"
+import { AnchorProgramExample } from "../target/types/anchor_program_example"
+import { PublicKey } from "@solana/web3.js"
 
 describe("PDAs", () => {
-  const provider = anchor.AnchorProvider.env();
-  anchor.setProvider(provider);
-  const payer = provider.wallet as anchor.Wallet;
+  const provider = anchor.AnchorProvider.env()
+  anchor.setProvider(provider)
+  const payer = provider.wallet as anchor.Wallet
   const program = anchor.workspace
-    .AnchorProgramExample as anchor.Program<AnchorProgramExample>;
+    .AnchorProgramExample as anchor.Program<AnchorProgramExample>
 
-  let testUser = anchor.web3.Keypair.generate();
-
-  it("Create a test user", async () => {
-    let ix = anchor.web3.SystemProgram.createAccount({
-      fromPubkey: payer.publicKey,
-      lamports: await provider.connection.getMinimumBalanceForRentExemption(0),
-      newAccountPubkey: testUser.publicKey,
-      programId: anchor.web3.SystemProgram.programId,
-      space: 0,
-    });
-    await anchor.web3.sendAndConfirmTransaction(
-      provider.connection,
-      new anchor.web3.Transaction().add(ix),
-      [payer.payer, testUser]
-    );
-    console.log(`Local Wallet: ${payer.publicKey}`);
-    console.log(`Created User: ${testUser.publicKey}`);
-  });
-
-  function derivePageVisitsPda(userPubkey: anchor.web3.PublicKey) {
-    return anchor.web3.PublicKey.findProgramAddressSync(
-      [Buffer.from("page_visits"), userPubkey.toBuffer()],
-      program.programId
-    )[0];
-  }
+  // PDA for the page visits account
+  const [pageVisitPDA] = PublicKey.findProgramAddressSync(
+    [Buffer.from("page_visits"), payer.publicKey.toBuffer()],
+    program.programId
+  )
 
   it("Create the page visits tracking PDA", async () => {
     await program.methods
       .createPageVisits()
       .accounts({
-        pageVisits: derivePageVisitsPda(testUser.publicKey),
-        user: testUser.publicKey,
         payer: payer.publicKey,
-        systemProgram: anchor.web3.SystemProgram.programId,
+        pageVisits: pageVisitPDA,
       })
-      .signers([payer.payer])
-      .rpc();
-  });
+      .rpc()
+  })
 
   it("Visit the page!", async () => {
     await program.methods
       .incrementPageVisits()
       .accounts({
-        pageVisits: derivePageVisitsPda(testUser.publicKey),
-        user: testUser.publicKey,
-        payer: payer.publicKey,
+        user: payer.publicKey,
+        pageVisits: pageVisitPDA,
       })
-      .signers([payer.payer])
-      .rpc();
-  });
+      .rpc()
+  })
 
   it("Visit the page!", async () => {
     await program.methods
       .incrementPageVisits()
       .accounts({
-        pageVisits: derivePageVisitsPda(testUser.publicKey),
-        user: testUser.publicKey,
-        payer: payer.publicKey,
+        user: payer.publicKey,
+        pageVisits: pageVisitPDA,
       })
-      .signers([payer.payer])
-      .rpc();
-  });
+      .rpc()
+  })
 
   it("View page visits", async () => {
-    const pageVisits = await program.account.pageVisits.fetch(
-      await derivePageVisitsPda(testUser.publicKey)
-    );
-    console.log(`Number of page visits: ${pageVisits.pageVisits}`);
-  });
-});
+    const pageVisits = await program.account.pageVisits.fetch(pageVisitPDA)
+    console.log(`Number of page visits: ${pageVisits.pageVisits}`)
+  })
+})

+ 8 - 0
basics/realloc/anchor/.gitignore

@@ -0,0 +1,8 @@
+
+.anchor
+.DS_Store
+target
+**/*.rs.bk
+node_modules
+test-ledger
+.yarn

+ 8 - 0
basics/realloc/anchor/.prettierignore

@@ -0,0 +1,8 @@
+
+.anchor
+.DS_Store
+target
+node_modules
+dist
+build
+test-ledger

+ 16 - 0
basics/realloc/anchor/Anchor.toml

@@ -0,0 +1,16 @@
+[features]
+seeds = false
+skip-lint = false
+
+[programs.localnet]
+anchor_realloc = "Fod47xKXjdHVQDzkFPBvfdWLm8gEAV4iMSXkfUzCHiSD"
+
+[registry]
+url = "https://api.apr.dev"
+
+[provider]
+cluster = "Localnet"
+wallet = "~/.config/solana/id.json"
+
+[scripts]
+test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"

+ 13 - 0
basics/realloc/anchor/Cargo.toml

@@ -0,0 +1,13 @@
+[workspace]
+members = [
+    "programs/*"
+]
+
+[profile.release]
+overflow-checks = true
+lto = "fat"
+codegen-units = 1
+[profile.release.build-override]
+opt-level = 3
+incremental = false
+codegen-units = 1

+ 12 - 0
basics/realloc/anchor/migrations/deploy.ts

@@ -0,0 +1,12 @@
+// Migrations are an early feature. Currently, they're nothing more than this
+// single deploy script that's invoked from the CLI, injecting a provider
+// configured from the workspace's Anchor.toml.
+
+const anchor = require("@coral-xyz/anchor");
+
+module.exports = async function (provider) {
+  // Configure client to use the provider.
+  anchor.setProvider(provider);
+
+  // Add your deploy script here.
+};

+ 19 - 0
basics/realloc/anchor/package.json

@@ -0,0 +1,19 @@
+{
+    "scripts": {
+        "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w",
+        "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check"
+    },
+    "dependencies": {
+        "@coral-xyz/anchor": "^0.28.0"
+    },
+    "devDependencies": {
+        "chai": "^4.3.4",
+        "mocha": "^9.0.3",
+        "ts-mocha": "^10.0.0",
+        "@types/bn.js": "^5.1.0",
+        "@types/chai": "^4.3.0",
+        "@types/mocha": "^9.0.0",
+        "typescript": "^4.3.5",
+        "prettier": "^2.6.2"
+    }
+}

+ 19 - 0
basics/realloc/anchor/programs/anchor-realloc/Cargo.toml

@@ -0,0 +1,19 @@
+[package]
+name = "anchor-realloc"
+version = "0.1.0"
+description = "Created with Anchor"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib", "lib"]
+name = "anchor_realloc"
+
+[features]
+no-entrypoint = []
+no-idl = []
+no-log-ix-name = []
+cpi = ["no-entrypoint"]
+default = []
+
+[dependencies]
+anchor-lang = "0.28.0"

+ 2 - 0
basics/realloc/anchor/programs/anchor-realloc/Xargo.toml

@@ -0,0 +1,2 @@
+[target.bpfel-unknown-unknown.dependencies.std]
+features = []

+ 63 - 0
basics/realloc/anchor/programs/anchor-realloc/src/lib.rs

@@ -0,0 +1,63 @@
+use anchor_lang::prelude::*;
+
+declare_id!("Fod47xKXjdHVQDzkFPBvfdWLm8gEAV4iMSXkfUzCHiSD");
+
+#[program]
+pub mod anchor_realloc {
+    use super::*;
+
+    pub fn initialize(ctx: Context<Initialize>, input: String) -> Result<()> {
+        ctx.accounts.message_account.message = input;
+        Ok(())
+    }
+
+    pub fn update(ctx: Context<Update>, input: String) -> Result<()> {
+        ctx.accounts.message_account.message = input;
+        Ok(())
+    }
+}
+
+#[derive(Accounts)]
+#[instruction(input: String)]
+pub struct Initialize<'info> {
+    #[account(mut)]
+    pub payer: Signer<'info>,
+
+    #[account(
+        init,
+        payer = payer,
+        space = Message::required_space(input.len()),
+    )]
+    pub message_account: Account<'info, Message>,
+    pub system_program: Program<'info, System>,
+}
+
+#[derive(Accounts)]
+#[instruction(input: String)]
+pub struct Update<'info> {
+    #[account(mut)]
+    pub payer: Signer<'info>,
+
+    #[account(
+       mut, 
+       realloc = Message::required_space(input.len()),
+       realloc::payer = payer,
+       realloc::zero = true,
+    )]
+    pub message_account: Account<'info, Message>,
+    pub system_program: Program<'info, System>,
+}
+
+#[account]
+pub struct Message {
+    pub message: String,
+}
+
+impl Message {
+    pub fn required_space(input_len: usize) -> usize {
+        8 + // 8 byte discriminator
+        4 + // 4 byte for length of string
+        input_len
+    }
+}
+

+ 75 - 0
basics/realloc/anchor/tests/anchor-realloc.ts

@@ -0,0 +1,75 @@
+import * as anchor from "@coral-xyz/anchor"
+import { Program } from "@coral-xyz/anchor"
+import { AnchorRealloc } from "../target/types/anchor_realloc"
+import { Keypair } from "@solana/web3.js"
+import { assert } from "chai"
+
+describe("anchor-realloc", () => {
+  // Configure the client to use the local cluster.
+  const provider = anchor.AnchorProvider.env()
+  anchor.setProvider(provider)
+  const payer = provider.wallet as anchor.Wallet
+  const connection = provider.connection
+
+  const program = anchor.workspace.AnchorRealloc as Program<AnchorRealloc>
+
+  const messageAccount = new Keypair()
+
+  // helper function to check the account data and message
+  async function checkAccount(publicKey, expectedMessage) {
+    const accountInfo = await connection.getAccountInfo(publicKey)
+    const accountData = await program.account.message.fetch(publicKey)
+
+    // 8 bytes for the discriminator,
+    // 4 bytes for the length of the message,
+    // and the length of the message
+    assert.equal(accountInfo.data.length, 8 + 4 + expectedMessage.length)
+    assert.equal(accountData.message, expectedMessage)
+
+    console.log(`Account Data Length: ${accountInfo.data.length}`)
+    console.log(`Message: ${accountData.message}`)
+  }
+
+  it("Is initialized!", async () => {
+    const input = "hello"
+
+    await program.methods
+      .initialize(input)
+      .accounts({
+        payer: payer.publicKey,
+        messageAccount: messageAccount.publicKey,
+      })
+      .signers([messageAccount])
+      .rpc()
+
+    await checkAccount(messageAccount.publicKey, input)
+  })
+
+  it("Update", async () => {
+    const input = "hello world"
+
+    await program.methods
+      .update(input)
+      .accounts({
+        payer: payer.publicKey,
+        messageAccount: messageAccount.publicKey,
+      })
+      .rpc()
+
+    await checkAccount(messageAccount.publicKey, input)
+  })
+
+  it("Update", async () => {
+    const input = "hi"
+
+    await program.methods
+      .update(input)
+      .accounts({
+        payer: payer.publicKey,
+        messageAccount: messageAccount.publicKey,
+      })
+      .rpc()
+
+    await checkAccount(messageAccount.publicKey, input)
+  })
+})

+ 11 - 0
basics/realloc/anchor/tsconfig.json

@@ -0,0 +1,11 @@
+{
+            "compilerOptions": {
+              "types": ["mocha", "chai"],
+              "typeRoots": ["./node_modules/@types"],
+              "lib": ["es2015"],
+              "module": "commonjs",
+              "target": "es6",
+              "esModuleInterop": true
+            }
+          }
+          

+ 12 - 19
basics/transfer-sol/anchor/programs/transfer-sol/src/lib.rs

@@ -24,41 +24,34 @@ pub mod transfer_sol {
         Ok(())
     }
 
+    // Directly modifying lamports is only possible if the program is the owner of the account
     pub fn transfer_sol_with_program(
         ctx: Context<TransferSolWithProgram>,
         amount: u64,
     ) -> Result<()> {
-        **ctx
-            .accounts
-            .payer
-            .to_account_info()
-            .try_borrow_mut_lamports()? -= amount;
-        **ctx
-            .accounts
-            .recipient
-            .to_account_info()
-            .try_borrow_mut_lamports()? += amount;
-
+        **ctx.accounts.payer.try_borrow_mut_lamports()? -= amount;
+        **ctx.accounts.recipient.try_borrow_mut_lamports()? += amount;
         Ok(())
     }
 }
 
 #[derive(Accounts)]
 pub struct TransferSolWithCpi<'info> {
-    #[account(mut)]
-    recipient: SystemAccount<'info>,
     #[account(mut)]
     payer: Signer<'info>,
+    #[account(mut)]
+    recipient: SystemAccount<'info>,
     system_program: Program<'info, System>,
 }
 
 #[derive(Accounts)]
 pub struct TransferSolWithProgram<'info> {
-    /// CHECK: This is just an example, not checking data
-    #[account(mut)]
-    recipient: UncheckedAccount<'info>,
-    /// CHECK: This is just an example, not checking data
-    #[account(mut)]
+    /// CHECK: Use owner constraint to check account is owned by our program
+    #[account(
+        mut,
+        owner = id() // value of declare_id!()
+    )]
     payer: UncheckedAccount<'info>,
-    system_program: Program<'info, System>,
+    #[account(mut)]
+    recipient: SystemAccount<'info>,
 }

+ 62 - 59
basics/transfer-sol/anchor/tests/test.ts

@@ -1,87 +1,90 @@
-import * as anchor from "@coral-xyz/anchor";
-import { TransferSol } from "../target/types/transfer_sol";
-
+import * as anchor from "@coral-xyz/anchor"
+import { TransferSol } from "../target/types/transfer_sol"
+import {
+  Keypair,
+  PublicKey,
+  LAMPORTS_PER_SOL,
+  SystemProgram,
+  Transaction,
+  sendAndConfirmTransaction,
+} from "@solana/web3.js"
 describe("transfer-sol", () => {
-  const provider = anchor.AnchorProvider.env();
-  anchor.setProvider(provider);
-  const payer = provider.wallet as anchor.Wallet;
-  const program = anchor.workspace.TransferSol as anchor.Program<TransferSol>;
+  const provider = anchor.AnchorProvider.env()
+  anchor.setProvider(provider)
+  const payer = provider.wallet as anchor.Wallet
+  const program = anchor.workspace.TransferSol as anchor.Program<TransferSol>
+
+  // 1 SOL
+  const transferAmount = 1 * LAMPORTS_PER_SOL
 
-  const transferAmount = 1 * anchor.web3.LAMPORTS_PER_SOL;
-  const test1Recipient = anchor.web3.Keypair.generate();
-  const test2Recipient1 = anchor.web3.Keypair.generate();
-  const test2Recipient2 = anchor.web3.Keypair.generate();
+  // Generate a new keypair for the recipient
+  const recipient = new Keypair()
 
-  it("Transfer between accounts using the system program", async () => {
-    await getBalances(payer.publicKey, test1Recipient.publicKey, "Beginning");
+  // Generate a new keypair to create an account owned by our program
+  const programOwnedAccount = new Keypair()
+
+  it("Transfer SOL with CPI", async () => {
+    await getBalances(payer.publicKey, recipient.publicKey, "Beginning")
 
     await program.methods
       .transferSolWithCpi(new anchor.BN(transferAmount))
       .accounts({
         payer: payer.publicKey,
-        recipient: test1Recipient.publicKey,
-        systemProgram: anchor.web3.SystemProgram.programId,
+        recipient: recipient.publicKey,
       })
-      .signers([payer.payer])
-      .rpc();
+      .rpc()
+
+    await getBalances(payer.publicKey, recipient.publicKey, "Resulting")
+  })
 
-    await getBalances(payer.publicKey, test1Recipient.publicKey, "Resulting");
-  });
+  it("Create and fund account owned by our program", async () => {
+    const instruction = SystemProgram.createAccount({
+      fromPubkey: payer.publicKey,
+      newAccountPubkey: programOwnedAccount.publicKey,
+      space: 0,
+      lamports: 1 * LAMPORTS_PER_SOL, // 1 SOL
+      programId: program.programId, // Program Owner, our program's address
+    })
 
-  it("Create two accounts for the following test", async () => {
-    const ix = (pubkey: anchor.web3.PublicKey) => {
-      return anchor.web3.SystemProgram.createAccount({
-        fromPubkey: payer.publicKey,
-        newAccountPubkey: pubkey,
-        space: 0,
-        lamports: 2 * anchor.web3.LAMPORTS_PER_SOL,
-        programId: program.programId,
-      });
-    };
+    const transaction = new Transaction().add(instruction)
 
-    await anchor.web3.sendAndConfirmTransaction(
-      provider.connection,
-      new anchor.web3.Transaction()
-        .add(ix(test2Recipient1.publicKey))
-        .add(ix(test2Recipient2.publicKey)),
-      [payer.payer, test2Recipient1, test2Recipient2]
-    );
-  });
+    await sendAndConfirmTransaction(provider.connection, transaction, [
+      payer.payer,
+      programOwnedAccount,
+    ])
+  })
 
-  it("Transfer between accounts using our program", async () => {
+  it("Transfer SOL with Program", async () => {
     await getBalances(
-      test2Recipient1.publicKey,
-      test2Recipient2.publicKey,
+      programOwnedAccount.publicKey,
+      payer.publicKey,
       "Beginning"
-    );
+    )
 
     await program.methods
       .transferSolWithProgram(new anchor.BN(transferAmount))
       .accounts({
-        payer: test2Recipient1.publicKey,
-        recipient: test2Recipient2.publicKey,
-        systemProgram: anchor.web3.SystemProgram.programId,
+        payer: programOwnedAccount.publicKey,
+        recipient: payer.publicKey,
       })
-      .rpc();
+      .rpc()
 
     await getBalances(
-      test2Recipient1.publicKey,
-      test2Recipient2.publicKey,
+      programOwnedAccount.publicKey,
+      payer.publicKey,
       "Resulting"
-    );
-  });
+    )
+  })
 
   async function getBalances(
-    payerPubkey: anchor.web3.PublicKey,
-    recipientPubkey: anchor.web3.PublicKey,
+    payerPubkey: PublicKey,
+    recipientPubkey: PublicKey,
     timeframe: string
   ) {
-    let payerBalance = await provider.connection.getBalance(payerPubkey);
-    let recipientBalance = await provider.connection.getBalance(
-      recipientPubkey
-    );
-    console.log(`${timeframe} balances:`);
-    console.log(`   Payer: ${payerBalance}`);
-    console.log(`   Recipient: ${recipientBalance}`);
+    let payerBalance = await provider.connection.getBalance(payerPubkey)
+    let recipientBalance = await provider.connection.getBalance(recipientPubkey)
+    console.log(`${timeframe} balances:`)
+    console.log(`   Payer: ${payerBalance / LAMPORTS_PER_SOL}`)
+    console.log(`   Recipient: ${recipientBalance / LAMPORTS_PER_SOL}`)
   }
-});
+})

+ 1 - 1
tokens/pda-mint-authority/anchor/programs/token-minter/src/instructions/create.rs

@@ -24,7 +24,7 @@ pub struct CreateToken<'info> {
         mint::decimals = 9,
         mint::authority = mint_account.key(),
         mint::freeze_authority = mint_account.key(),
-        
+
     )]
     pub mint_account: Account<'info, Mint>,
 

+ 2 - 2
tokens/spl-token-minter/anchor/programs/spl-token-minter/src/instructions/create.rs

@@ -18,7 +18,7 @@ pub struct CreateToken<'info> {
         mint::decimals = 9,
         mint::authority = payer.key(),
         mint::freeze_authority = payer.key(),
-        
+
     )]
     pub mint_account: Account<'info, Mint>,
     /// CHECK: Address validated using constraint
@@ -50,7 +50,7 @@ pub fn create_token(
             CreateMetadataAccountsV3 {
                 metadata: ctx.accounts.metadata_account.to_account_info(),
                 mint: ctx.accounts.mint_account.to_account_info(),
-                mint_authority: ctx.accounts.payer.to_account_info(), 
+                mint_authority: ctx.accounts.payer.to_account_info(),
                 update_authority: ctx.accounts.payer.to_account_info(),
                 payer: ctx.accounts.payer.to_account_info(),
                 system_program: ctx.accounts.system_program.to_account_info(),

+ 2 - 2
tokens/transfer-tokens/anchor/programs/transfer-tokens/src/instructions/create.rs

@@ -18,7 +18,7 @@ pub struct CreateToken<'info> {
         mint::decimals = 9,
         mint::authority = payer.key(),
         mint::freeze_authority = payer.key(),
-        
+
     )]
     pub mint_account: Account<'info, Mint>,
 
@@ -51,7 +51,7 @@ pub fn create_token(
             CreateMetadataAccountsV3 {
                 metadata: ctx.accounts.metadata_account.to_account_info(),
                 mint: ctx.accounts.mint_account.to_account_info(),
-                mint_authority: ctx.accounts.payer.to_account_info(), 
+                mint_authority: ctx.accounts.payer.to_account_info(),
                 update_authority: ctx.accounts.payer.to_account_info(),
                 payer: ctx.accounts.payer.to_account_info(),
                 system_program: ctx.accounts.system_program.to_account_info(),