Przeglądaj źródła

create-system-account init

jpcaulfi 3 lat temu
rodzic
commit
0216acbd14

+ 12 - 0
.gitignore

@@ -0,0 +1,12 @@
+.template
+
+**/*/node_modules
+**/*/package-lock.json
+**/*/Cargo.lock
+
+**/*/.anchor
+**/*/.DS_Store
+**/*/target
+**/*.rs.bk
+**/*/test-ledger
+**/*/yarn.lock

+ 20 - 3
README.md

@@ -2,13 +2,26 @@
 
 ### :space_invader: Welcome, Solana Developer. :space_invader:   
    
-Do you ever look at a bunch of examples of doing things on Solana and think to yourself: *"But how do I do this on-chain?"*   
-   
+Do you ever look at a bunch of examples of doing things on Solana and think to yourself: *"OK, but how do I do this on-chain?"*   
    
 We present to you this list of curated examples for a wide range of use cases implemented using **on-chain programs**.   
    
 ### :link: All on-chain. :crab: All Rust. :muscle: All the time. 
 
+## Some Basic Concepts to Know
+Most system-level operations on Solana involve already-existing Solana programs.   
+   
+For example, to create a **system account** you use the **system program** and to create a **token mint** you use the **token program**.   
+   
+So, you'll notice that these operations are in fact conducting what's called a **cross-program invocation** - which is a fancy way of saying it calls other Solana programs to do business. You can see this in action whenever you see `invoke` or `invoke_signed` in the `native` examples, or `CpiContext` in the `anchor` examples.   
+   
+Deciding when to use cross-program invocation instead of invoking the programs directly from the client is completely up to you as the builder. It depends on how your application is designed.
+- Maybe you want to add some checks - such as minimum balance required, allowed ownership, etc.
+- Maybe you want to assert that an account has a certain data type.
+- Perhaps you want to send only one transaction from your client for a handful of sequential operations.
+- The list goes on.
+Regardless of what you may want to add on top of existing Solana programs, the number one use case for writing your own program is for using accounts with a **Program Derived Address (PDA)**. Crack open the `pdas` folder to see why.
+
 ## Navigating this Repo
 
 This collection is organized into the following sections:
@@ -23,6 +36,10 @@ Each example contains two folders:
 - `native` - Written using Solana's native Rust crates and vanilla Rust.
 - `anchor` - Written using Anchor's `anchor_lang` Rust crate and the associated Anchor framework to build & deploy.
 
+How to build & run:
+- `native` - Use `cicd.sh` to build & deploy the program. Run `npm run test` to test it.
+- `anchor` - Use `anchor build && anchor deploy` to build & deploy the program. Run `anchor run test` to test it.
+
 ## To-Do:
 **Got something you want to see here? Add it to the list. Or better yet, write one & create a PR!*
 - ### Program Basics
@@ -31,7 +48,7 @@ Each example contains two folders:
 - [] 3. Recommended program layout
 - [] 4. Custom instruction data expanded
 - ### Accounts
-- [] 1. Creating an account
+- [] 1. Creating a system account
 - [] 2. Modifying an account's data
 - [] 3. Transferring SOL
 - [] 4. Transferring an account's ownership

+ 11 - 0
accounts/create-system-account/README.md

@@ -0,0 +1,11 @@
+# Create Account
+
+:wrench: We're going to create a Solana account. :wrench:   
+   
+This account is going to be a **system account** - meaning it will be owned by the System Program. In short, this means only the System Program will be allowed to modify it's data.   
+   
+In this example, this account will simply hold some SOL.
+
+### Links:
+- [Solana Cookbook - How to Create a System Account](https://solanacookbook.com/references/accounts.html#how-to-create-a-system-account)
+- [Rust Docs - solana_program::system_instruction::create_account](https://docs.rs/solana-program/latest/solana_program/system_instruction/fn.create_account.html)

+ 14 - 0
accounts/create-system-account/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
accounts/create-system-account/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
accounts/create-system-account/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
accounts/create-system-account/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
accounts/create-system-account/anchor/programs/create-system-account/Xargo.toml

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

+ 15 - 0
accounts/create-system-account/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
accounts/create-system-account/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
accounts/create-system-account/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
accounts/create-system-account/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=./target/so
+solana program deploy /target/so/program.so

+ 17 - 0
accounts/create-system-account/native/package.json

@@ -0,0 +1,17 @@
+{
+  "scripts": {
+    "test": "yarn run ts-mocha -p ./tsconfig.json -t 1000000 ./test.ts"
+  },
+  "dependencies": {
+    "@solana/web3.js": "^1.47.3"
+  },
+  "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"
+  }
+}

+ 10 - 0
accounts/create-system-account/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"]

+ 42 - 0
accounts/create-system-account/native/program/src/lib.rs

@@ -0,0 +1,42 @@
+use solana_program::{
+    account_info::AccountInfo, 
+    entrypoint, 
+    entrypoint::ProgramResult, 
+    msg, 
+    native_token::LAMPORTS_PER_SOL,
+    program::invoke,
+    pubkey::Pubkey,
+    system_instruction,
+    system_program,
+};
+
+
+entrypoint!(process_instruction);
+
+
+fn process_instruction(
+    program_id: &Pubkey,
+    accounts: &[AccountInfo],
+    instruction_data: &[u8],
+) -> ProgramResult {
+
+    let accounts_iter = &mut accounts.iter();
+    let payer = next_account_info(accounts_iter)?;
+    
+    msg!("Program invoked. Creating a system account...");
+    msg!("New public key will be: {}", &new_pubkey);
+    
+    invoke(
+        &system_instruction::create_account(
+            &payer,                 // From pubkey
+            &new_pubkey,            // To pubkey
+            LAMPORTS_PER_SOL,       // Lamports
+            32,                     // Space
+            &system_program::ID,    // Owner
+        ),
+        &[payer]                // Signers
+    )?;
+
+    msg!("Account created succesfully.");
+    Ok(())
+}

+ 0 - 0
accounts/create-system-account/native/test.ts


+ 10 - 0
accounts/create-system-account/native/tsconfig.json

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