Przeglądaj źródła

checking accts native

jpcaulfi 3 lat temu
rodzic
commit
347aa8f067

+ 14 - 0
basics/checking-accounts/anchor/Anchor.toml

@@ -0,0 +1,14 @@
+[features]
+seeds = false
+[programs.localnet]
+anchor_program_example = "Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"
+
+[registry]
+url = "https://anchor.projectserum.com"
+
+[provider]
+cluster = "localnet"
+wallet = "~/.config/solana/id.json"
+
+[scripts]
+test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"

+ 13 - 0
basics/checking-accounts/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

+ 14 - 0
basics/checking-accounts/anchor/package.json

@@ -0,0 +1,14 @@
+{
+    "dependencies": {
+        "@project-serum/anchor": "^0.24.2"
+    },
+    "devDependencies": {
+        "@types/bn.js": "^5.1.0",
+        "@types/chai": "^4.3.0",
+        "@types/mocha": "^9.0.0",
+        "chai": "^4.3.4",
+        "mocha": "^9.0.3",
+        "ts-mocha": "^10.0.0",
+        "typescript": "^4.3.5"
+    }
+}

+ 19 - 0
basics/checking-accounts/anchor/programs/anchor-program-example/Cargo.toml

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

+ 2 - 0
basics/checking-accounts/anchor/programs/anchor-program-example/Xargo.toml

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

+ 18 - 0
basics/checking-accounts/anchor/programs/anchor-program-example/src/lib.rs

@@ -0,0 +1,18 @@
+use anchor_lang::prelude::*;
+
+declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
+
+#[program]
+pub mod anchor_program_example {
+    use super::*;
+
+    pub fn hello(ctx: Context<Hello>) -> Result<()> {
+        
+        msg!("Hello, Solana!");
+        
+        Ok(())
+    }
+}
+
+#[derive(Accounts)]
+pub struct Hello {}

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

@@ -0,0 +1,22 @@
+import * as anchor from "@project-serum/anchor";
+import { AnchorProgramExample } from "../target/types/anchor_program_example";
+
+describe("Anchor example", () => {
+  
+  // Configure the Anchor provider & load the program IDL
+  // The IDL gives you a typescript module
+  //
+  const provider = anchor.AnchorProvider.env();
+  anchor.setProvider(provider);
+  const program = anchor.workspace.AnchorProgramExample as anchor.Program<AnchorProgramExample>;
+
+  it("Test our example", async () => {
+    
+    // Just run Anchor's IDL method to build a transaction!
+    //
+    await program.methods.hello()
+    .accounts({})
+    .rpc();
+
+  });
+});

+ 10 - 0
basics/checking-accounts/anchor/tsconfig.json

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

+ 8 - 0
basics/checking-accounts/native/cicd.sh

@@ -0,0 +1,8 @@
+#!/bin/bash
+
+# This script is for quick building & deploying of the program.
+# It also serves as a reference for the commands used for building & deploying Solana programs.
+# Run this bad boy with "bash cicd.sh" or "./cicd.sh"
+
+cargo build-bpf --manifest-path=./program/Cargo.toml --bpf-out-dir=./program/target/so
+solana program deploy ./program/target/so/program.so

+ 18 - 0
basics/checking-accounts/native/package.json

@@ -0,0 +1,18 @@
+{
+  "scripts": {
+    "test": "yarn run ts-mocha -p ./tsconfig.json -t 1000000 ./tests/test.ts"
+  },
+  "dependencies": {
+    "@solana/web3.js": "^1.47.3",
+    "fs": "^0.0.1-security"
+  },
+  "devDependencies": {
+    "@types/bn.js": "^5.1.0",
+    "@types/chai": "^4.3.1",
+    "@types/mocha": "^9.1.1",
+    "chai": "^4.3.4",
+    "mocha": "^9.0.3",
+    "ts-mocha": "^10.0.0",
+    "typescript": "^4.3.5"
+  }
+}

+ 10 - 0
basics/checking-accounts/native/program/Cargo.toml

@@ -0,0 +1,10 @@
+[package]
+name = "program"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+solana-program = "1.10.12"
+
+[lib]
+crate-type = ["cdylib", "lib"]

+ 85 - 0
basics/checking-accounts/native/program/src/lib.rs

@@ -0,0 +1,85 @@
+use solana_program::{
+    account_info::{ AccountInfo, next_account_info }, 
+    entrypoint, 
+    entrypoint::ProgramResult, 
+    msg, 
+    program_error::ProgramError,
+    pubkey::Pubkey,
+    system_program,
+};
+
+
+entrypoint!(process_instruction);
+
+
+fn print_account_info(account_info: AccountInfo) {
+    msg!("  key: {:?}", account_info.key);
+    msg!("  is_signer: {:?}", account_info.is_signer);
+    msg!("  is_writable: {:?}", account_info.is_writable);
+    msg!("  lamports: {:?}", account_info.lamports());
+    msg!("  data: {:?}", account_info.data);
+    msg!("  owner: {:?}", account_info.owner);
+    msg!("  executable: {:?}", account_info.executable);
+    msg!("  rent_epoch: {:?}", account_info.rent_epoch);
+}
+
+
+fn process_instruction(
+    program_id: &Pubkey,
+    accounts: &[AccountInfo],
+    _instruction_data: &[u8],
+) -> ProgramResult {
+
+    // You can verify the program ID from the instruction is in fact 
+    //      the program ID of your program.
+    if system_program::check_id(program_id) {
+        return Err(ProgramError::IncorrectProgramId)
+    };
+    
+    // You can verify the list has the correct number of accounts.
+    // This error will get thrown by default if you 
+    //      try to reach past the end of the iter.
+    if accounts.len() < 4 {
+        msg!("This instruction requires 4 accounts:");
+        msg!("  payer, account_to_create, account_to_change, system_program");
+        return Err(ProgramError::NotEnoughAccountKeys)
+    };
+
+    // Accounts passed in a vector must be in the expected order.
+    let accounts_iter = &mut accounts.iter();
+    let _payer = next_account_info(accounts_iter)?;
+    let account_to_create = next_account_info(accounts_iter)?;
+    let account_to_change = next_account_info(accounts_iter)?;
+    let system_program = next_account_info(accounts_iter)?;
+
+    // You can make sure an account has NOT been initialized.
+    
+    msg!("New account: {}", account_to_create.key);
+    print_account_info(account_to_create.clone());
+    if account_to_create.lamports() != 0 {
+        msg!("The program expected the account to create to not yet be initialized.");
+        return Err(ProgramError::AccountAlreadyInitialized)
+    };
+    // (Create account...)
+
+    // You can also make sure an account has been initialized.
+    msg!("Account to change: {}", account_to_change.key);
+    print_account_info(account_to_change.clone());
+    if account_to_change.lamports() == 0 {
+        msg!("The program expected the account to change to be initialized.");
+        return Err(ProgramError::UninitializedAccount)
+    };
+
+    // If we want to modify an account's data, it must be owned by our program.
+    if account_to_change.owner != program_id {
+        msg!("Account to change does not have the correct program id.");
+        return Err(ProgramError::IncorrectProgramId)
+    };
+
+    // You can also check pubkeys against constants.
+    if system_program.key != &system_program::ID {
+        return Err(ProgramError::IncorrectProgramId)
+    };
+
+    Ok(())
+}

+ 71 - 0
basics/checking-accounts/native/tests/test.ts

@@ -0,0 +1,71 @@
+import {
+    Connection,
+    Keypair,
+    PublicKey,
+    sendAndConfirmTransaction,
+    SystemProgram,
+    Transaction,
+    TransactionInstruction,
+} from '@solana/web3.js';
+
+
+function createKeypairFromFile(path: string): Keypair {
+    return Keypair.fromSecretKey(
+        Buffer.from(JSON.parse(require('fs').readFileSync(path, "utf-8")))
+    )
+};
+
+
+describe("Checking accounts", async () => {
+
+    const connection = new Connection(`http://localhost:8899`, 'confirmed');
+    const payer = createKeypairFromFile(require('os').homedir() + '/.config/solana/id.json');
+    
+    const PROGRAM_ID: PublicKey = new PublicKey(
+        "AE653DEBtNWr2VcU3FhVtFPc7rUf4z2Km8s5TnSwiiaW"
+    );
+
+    // We'll create this ahead of time.
+    // Our program will try to modify it.
+    const accountToChange = Keypair.generate();
+    // Our program will create this.
+    const accountToCreate = Keypair.generate();
+  
+    it("Create an account owned by our program", async () => {
+
+        let ix = SystemProgram.createAccount({
+            fromPubkey: payer.publicKey,
+            newAccountPubkey: accountToChange.publicKey,
+            lamports: await connection.getMinimumBalanceForRentExemption(0),
+            space: 0,
+            programId: PROGRAM_ID, // Our program
+        });
+
+        await sendAndConfirmTransaction(
+            connection, 
+            new Transaction().add(ix),
+            [payer, accountToChange]
+        );
+    });
+    
+    it("Check accounts", async () => {
+
+        let ix = new TransactionInstruction({
+            keys: [
+                {pubkey: payer.publicKey, isSigner: true, isWritable: true},
+                {pubkey: accountToCreate.publicKey, isSigner: true, isWritable: true},
+                {pubkey: accountToChange.publicKey, isSigner: true, isWritable: true},
+                {pubkey: SystemProgram.programId, isSigner: false, isWritable: false}
+            ],
+            programId: PROGRAM_ID,
+            data: Buffer.alloc(0),
+        }); 
+
+        await sendAndConfirmTransaction(
+            connection, 
+            new Transaction().add(ix),
+            [payer, accountToCreate, accountToChange]
+        );
+    });
+  });
+  

+ 10 - 0
basics/checking-accounts/native/tsconfig.json

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