Prechádzať zdrojové kódy

counter: add anchor example implementation

ngundotra 3 rokov pred
rodič
commit
30da42281b

+ 7 - 0
basics/counter/anchor/.gitignore

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

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

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

+ 15 - 0
basics/counter/anchor/Anchor.toml

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

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

+ 5 - 0
basics/counter/anchor/README.md

@@ -0,0 +1,5 @@
+# Anchor Counter
+
+Anchor enforces init constraints that enforces good programming paradigms.
+
+This means this program has an additional initialization instruction for `Counter`s that the Solana native program does not.

+ 12 - 0
basics/counter/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("@project-serum/anchor");
+
+module.exports = async function (provider) {
+  // Configure client to use the provider.
+  anchor.setProvider(provider);
+
+  // Add your deploy script here.
+};

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

@@ -0,0 +1,19 @@
+{
+    "scripts": {
+        "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w",
+        "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check"
+    },
+    "dependencies": {
+        "@project-serum/anchor": "^0.25.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/counter/anchor/programs/counter_anchor/Cargo.toml

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

+ 2 - 0
basics/counter/anchor/programs/counter_anchor/Xargo.toml

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

+ 37 - 0
basics/counter/anchor/programs/counter_anchor/src/lib.rs

@@ -0,0 +1,37 @@
+use anchor_lang::prelude::*;
+
+declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
+
+#[program]
+pub mod counter_anchor {
+    use super::*;
+
+    pub fn initialize_counter(ctx: Context<InitializeCounter>) -> Result<()> {
+        Ok(())
+    }
+
+    pub fn increment(ctx: Context<Increment>) -> Result<()> {
+        ctx.accounts.counter.count += 1;
+        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>,
+    pub system_program: Program<'info, System>,
+}
+
+#[derive(Accounts)]
+pub struct Increment<'info> {
+    #[account(mut)]
+    pub counter: Account<'info, Counter>,
+}

+ 44 - 0
basics/counter/anchor/tests/counter_anchor.ts

@@ -0,0 +1,44 @@
+import * as anchor from "@project-serum/anchor";
+import { Program } from "@project-serum/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 program = anchor.workspace.CounterAnchor as Program<CounterAnchor>;
+
+  it("Test increment", async () => {
+    const counterKeypair = Keypair.generate();
+    const counter = counterKeypair.publicKey;
+
+    // Initialize counter
+    await program.methods
+      .initializeCounter()
+      .accounts({ counter, payer: program.provider.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");
+
+    // Increment counter
+    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
+    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");
+  });
+});

+ 10 - 0
basics/counter/anchor/tsconfig.json

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