Browse Source

hello solana

jpcaulfi 3 years ago
parent
commit
67f8642646

+ 34 - 0
program-basics/hello-solana/README.md

@@ -0,0 +1,34 @@
+# Hello Solana
+
+This is it: our first Solana program.   
+   
+Naturally, we're going to start with "hello, world", but we'll take a look at some of the key things going on here.   
+   
+## Transactions
+
+First thing's first, we have to understand what's in a Solana transaction.   
+   
+> For a closer look at transactions, check out the [Solana Core Docs](https://docs.solana.com/developing/programming-model/transactions) or the [Solana Cookbook](https://solanacookbook.com/core-concepts/transactions.html#facts).
+
+The anatomy of a transaction is as follows, but here's the keys:   
+:key: **Transactions** are for **the Solana runtime**. They contain information that Solana uses to allow or deny a transaction (signers, blockhash, etc.) and choose whether to process instructions in parallel.   
+:key: **Instructions** are for **Solana programs**. They tell the program what to do.   
+:key: Our program receives one instruction at a time (`program_id`, `accounts`, `instruction_data`).
+#### Transaction
+```shell
+signatures: [ s, s ]
+message:
+    header: 000
+    addresses: [ aaa, aaa ]
+    recent_blockhash: int
+    instructions: [ ix, ix ]
+```
+#### Instruction
+```shell
+program_id: xxx
+accounts: [ aaa, aaa ]
+instruction_data: b[]
+```
+
+>[!Note]
+> You can

+ 14 - 0
program-basics/hello-solana/anchor/Anchor.toml

@@ -0,0 +1,14 @@
+[features]
+seeds = false
+[programs.localnet]
+anchor = "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
program-basics/hello-solana/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
program-basics/hello-solana/anchor/package.json

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

+ 19 - 0
program-basics/hello-solana/anchor/programs/create-system-account/Cargo.toml

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

+ 2 - 0
program-basics/hello-solana/anchor/programs/create-system-account/Xargo.toml

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

+ 15 - 0
program-basics/hello-solana/anchor/programs/create-system-account/src/lib.rs

@@ -0,0 +1,15 @@
+use anchor_lang::prelude::*;
+
+declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
+
+#[program]
+pub mod anchor {
+    use super::*;
+
+    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
+        Ok(())
+    }
+}
+
+#[derive(Accounts)]
+pub struct Initialize {}

+ 16 - 0
program-basics/hello-solana/anchor/tests/anchor.ts

@@ -0,0 +1,16 @@
+import * as anchor from "@project-serum/anchor";
+import { Program } from "@project-serum/anchor";
+import { CreateSystemAccount } from "../target/types/create_system_account";
+
+describe("anchor", () => {
+  // Configure the client to use the local cluster.
+  anchor.setProvider(anchor.AnchorProvider.env());
+
+  const program = anchor.workspace.Anchor as Program<CreateSystemAccount>;
+
+  it("Is initialized!", async () => {
+    // Add your test here.
+    const tx = await program.methods.initialize().rpc();
+    console.log("Your transaction signature", tx);
+  });
+});

+ 10 - 0
program-basics/hello-solana/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
program-basics/hello-solana/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
program-basics/hello-solana/native/package.json

@@ -0,0 +1,18 @@
+{
+  "scripts": {
+    "test": "yarn run ts-mocha -p ./tsconfig.json -t 1000000 ./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
program-basics/hello-solana/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"]

+ 29 - 0
program-basics/hello-solana/native/program/src/lib.rs

@@ -0,0 +1,29 @@
+use solana_program::{
+    account_info::AccountInfo, 
+    entrypoint, 
+    entrypoint::ProgramResult, 
+    msg, 
+    pubkey::Pubkey,
+};
+
+
+// Tells Solana that the entrypoint to this program
+//  is the "process_instruction" function.
+//
+entrypoint!(process_instruction);
+
+
+// Our entrypoint's parameters have to match the
+//  anatomy of a transaction instruction (see README).
+//
+fn process_instruction(
+    program_id: &Pubkey,
+    accounts: &[AccountInfo],
+    instruction_data: &[u8],
+) -> ProgramResult {
+
+    
+    msg!("Hello, Solana!");
+
+    Ok(())
+}

+ 47 - 0
program-basics/hello-solana/native/test.ts

@@ -0,0 +1,47 @@
+import {
+    Connection,
+    Keypair,
+    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("hello-solana", () => {
+
+    // Loading these from local files for development
+    //
+    const connection = new Connection(`http://localhost:8899`, 'confirmed');
+    const payer = createKeypairFromFile(require('os').homedir() + '/.config/solana/id.json');
+    const program = createKeypairFromFile('./program/target/so/program-keypair.json');
+  
+    it("Say hello!", async () => {
+
+        // We set up our instruction first.
+        //
+        let ix = new TransactionInstruction({
+            keys: [
+                {pubkey: payer.publicKey, isSigner: true, isWritable: true},
+                {pubkey: SystemProgram.programId, isSigner: false, isWritable: false},
+            ],
+            programId: program.publicKey,
+            data: Buffer.alloc(0), // No data
+        });
+
+        // Now we send the transaction over RPC
+        //
+        await sendAndConfirmTransaction(
+            connection, 
+            new Transaction().add(ix), // Add our instruction (you can add more than one)
+            [payer]
+        );
+    });
+  });
+  

+ 10 - 0
program-basics/hello-solana/native/tsconfig.json

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