Procházet zdrojové kódy

cpi basics example with declare_program macro

John před 1 rokem
rodič
revize
3c45a40d12
26 změnil soubory, kde provedl 339 přidání a 18 odebrání
  1. 0 0
      basics/cross-program-invocation/anchor/cpi-crate/Anchor.toml
  2. 0 0
      basics/cross-program-invocation/anchor/cpi-crate/Cargo.toml
  3. 0 0
      basics/cross-program-invocation/anchor/cpi-crate/package.json
  4. 0 0
      basics/cross-program-invocation/anchor/cpi-crate/programs/hand/Cargo.toml
  5. 0 0
      basics/cross-program-invocation/anchor/cpi-crate/programs/hand/Xargo.toml
  6. 0 0
      basics/cross-program-invocation/anchor/cpi-crate/programs/hand/src/lib.rs
  7. 0 0
      basics/cross-program-invocation/anchor/cpi-crate/programs/lever/Cargo.toml
  8. 0 0
      basics/cross-program-invocation/anchor/cpi-crate/programs/lever/Xargo.toml
  9. 0 0
      basics/cross-program-invocation/anchor/cpi-crate/programs/lever/src/lib.rs
  10. 16 18
      basics/cross-program-invocation/anchor/cpi-crate/tests/test.ts
  11. 0 0
      basics/cross-program-invocation/anchor/cpi-crate/tsconfig.json
  12. 7 0
      basics/cross-program-invocation/anchor/cpi-idl/.gitignore
  13. 7 0
      basics/cross-program-invocation/anchor/cpi-idl/.prettierignore
  14. 19 0
      basics/cross-program-invocation/anchor/cpi-idl/Anchor.toml
  15. 14 0
      basics/cross-program-invocation/anchor/cpi-idl/Cargo.toml
  16. 68 0
      basics/cross-program-invocation/anchor/cpi-idl/idls/lever.json
  17. 12 0
      basics/cross-program-invocation/anchor/cpi-idl/migrations/deploy.ts
  18. 19 0
      basics/cross-program-invocation/anchor/cpi-idl/package.json
  19. 20 0
      basics/cross-program-invocation/anchor/cpi-idl/programs/hand/Cargo.toml
  20. 2 0
      basics/cross-program-invocation/anchor/cpi-idl/programs/hand/Xargo.toml
  21. 33 0
      basics/cross-program-invocation/anchor/cpi-idl/programs/hand/src/lib.rs
  22. 20 0
      basics/cross-program-invocation/anchor/cpi-idl/programs/lever/Cargo.toml
  23. 2 0
      basics/cross-program-invocation/anchor/cpi-idl/programs/lever/Xargo.toml
  24. 46 0
      basics/cross-program-invocation/anchor/cpi-idl/programs/lever/src/lib.rs
  25. 44 0
      basics/cross-program-invocation/anchor/cpi-idl/tests/cpi.ts
  26. 10 0
      basics/cross-program-invocation/anchor/cpi-idl/tsconfig.json

+ 0 - 0
basics/cross-program-invocation/anchor/Anchor.toml → basics/cross-program-invocation/anchor/cpi-crate/Anchor.toml


+ 0 - 0
basics/cross-program-invocation/anchor/Cargo.toml → basics/cross-program-invocation/anchor/cpi-crate/Cargo.toml


+ 0 - 0
basics/cross-program-invocation/anchor/package.json → basics/cross-program-invocation/anchor/cpi-crate/package.json


+ 0 - 0
basics/cross-program-invocation/anchor/programs/hand/Cargo.toml → basics/cross-program-invocation/anchor/cpi-crate/programs/hand/Cargo.toml


+ 0 - 0
basics/cross-program-invocation/anchor/programs/hand/Xargo.toml → basics/cross-program-invocation/anchor/cpi-crate/programs/hand/Xargo.toml


+ 0 - 0
basics/cross-program-invocation/anchor/programs/hand/src/lib.rs → basics/cross-program-invocation/anchor/cpi-crate/programs/hand/src/lib.rs


+ 0 - 0
basics/cross-program-invocation/anchor/programs/lever/Cargo.toml → basics/cross-program-invocation/anchor/cpi-crate/programs/lever/Cargo.toml


+ 0 - 0
basics/cross-program-invocation/anchor/programs/lever/Xargo.toml → basics/cross-program-invocation/anchor/cpi-crate/programs/lever/Xargo.toml


+ 0 - 0
basics/cross-program-invocation/anchor/programs/lever/src/lib.rs → basics/cross-program-invocation/anchor/cpi-crate/programs/lever/src/lib.rs


+ 16 - 18
basics/cross-program-invocation/anchor/tests/test.ts → basics/cross-program-invocation/anchor/cpi-crate/tests/test.ts

@@ -1,16 +1,16 @@
-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"
+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>;
 
   // Generate a new keypair for the power account
-  const powerAccount = new Keypair()
+  const powerAccount = new Keypair();
 
   it("Initialize the lever!", async () => {
     await lever.methods
@@ -20,26 +20,24 @@ describe("CPI Example", () => {
         user: provider.wallet.publicKey,
       })
       .signers([powerAccount])
-      .rpc()
-  })
+      .rpc();
+  });
 
   it("Pull the lever!", async () => {
     await hand.methods
       .pullLever("Chris")
       .accounts({
         power: powerAccount.publicKey,
-        leverProgram: lever.programId,
       })
-      .rpc()
-  })
+      .rpc();
+  });
 
   it("Pull it again!", async () => {
     await hand.methods
       .pullLever("Ashley")
       .accounts({
         power: powerAccount.publicKey,
-        leverProgram: lever.programId,
       })
-      .rpc()
-  })
-})
+      .rpc();
+  });
+});

+ 0 - 0
basics/cross-program-invocation/anchor/tsconfig.json → basics/cross-program-invocation/anchor/cpi-crate/tsconfig.json


+ 7 - 0
basics/cross-program-invocation/anchor/cpi-idl/.gitignore

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

+ 7 - 0
basics/cross-program-invocation/anchor/cpi-idl/.prettierignore

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

+ 19 - 0
basics/cross-program-invocation/anchor/cpi-idl/Anchor.toml

@@ -0,0 +1,19 @@
+[toolchain]
+
+[features]
+resolution = true
+skip-lint = false
+
+[programs.localnet]
+hand = "Bi5N7SUQhpGknVcqPTzdFFVueQoxoUu8YTLz75J6fT8A"
+lever = "E64FVeubGC4NPNF2UBJYX4AkrVowf74fRJD9q6YhwstN"
+
+[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"

+ 14 - 0
basics/cross-program-invocation/anchor/cpi-idl/Cargo.toml

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

+ 68 - 0
basics/cross-program-invocation/anchor/cpi-idl/idls/lever.json

@@ -0,0 +1,68 @@
+{
+  "address": "E64FVeubGC4NPNF2UBJYX4AkrVowf74fRJD9q6YhwstN",
+  "metadata": {
+    "name": "lever",
+    "version": "0.1.0",
+    "spec": "0.1.0",
+    "description": "Created with Anchor"
+  },
+  "instructions": [
+    {
+      "name": "initialize",
+      "discriminator": [175, 175, 109, 31, 13, 152, 155, 237],
+      "accounts": [
+        {
+          "name": "power",
+          "writable": true,
+          "signer": true
+        },
+        {
+          "name": "user",
+          "writable": true,
+          "signer": true
+        },
+        {
+          "name": "system_program",
+          "address": "11111111111111111111111111111111"
+        }
+      ],
+      "args": []
+    },
+    {
+      "name": "switch_power",
+      "discriminator": [226, 238, 56, 172, 191, 45, 122, 87],
+      "accounts": [
+        {
+          "name": "power",
+          "writable": true
+        }
+      ],
+      "args": [
+        {
+          "name": "name",
+          "type": "string"
+        }
+      ]
+    }
+  ],
+  "accounts": [
+    {
+      "name": "PowerStatus",
+      "discriminator": [145, 147, 198, 35, 253, 101, 231, 26]
+    }
+  ],
+  "types": [
+    {
+      "name": "PowerStatus",
+      "type": {
+        "kind": "struct",
+        "fields": [
+          {
+            "name": "is_on",
+            "type": "bool"
+          }
+        ]
+      }
+    }
+  ]
+}

+ 12 - 0
basics/cross-program-invocation/anchor/cpi-idl/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/cross-program-invocation/anchor/cpi-idl/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.30.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"
+  }
+}

+ 20 - 0
basics/cross-program-invocation/anchor/cpi-idl/programs/hand/Cargo.toml

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

+ 2 - 0
basics/cross-program-invocation/anchor/cpi-idl/programs/hand/Xargo.toml

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

+ 33 - 0
basics/cross-program-invocation/anchor/cpi-idl/programs/hand/src/lib.rs

@@ -0,0 +1,33 @@
+use anchor_lang::prelude::*;
+
+declare_id!("Bi5N7SUQhpGknVcqPTzdFFVueQoxoUu8YTLz75J6fT8A");
+
+// automatically generate module using program idl found in ./idls
+declare_program!(lever);
+use lever::accounts::PowerStatus;
+use lever::cpi::accounts::SwitchPower;
+use lever::cpi::switch_power;
+use lever::program::Lever;
+
+#[program]
+pub mod hand {
+    use super::*;
+
+    pub fn pull_lever(ctx: Context<PullLever>, name: String) -> Result<()> {
+        let cpi_ctx = CpiContext::new(
+            ctx.accounts.lever_program.to_account_info(),
+            SwitchPower {
+                power: ctx.accounts.power.to_account_info(),
+            },
+        );
+        switch_power(cpi_ctx, name)?;
+        Ok(())
+    }
+}
+
+#[derive(Accounts)]
+pub struct PullLever<'info> {
+    #[account(mut)]
+    pub power: Account<'info, PowerStatus>,
+    pub lever_program: Program<'info, Lever>,
+}

+ 20 - 0
basics/cross-program-invocation/anchor/cpi-idl/programs/lever/Cargo.toml

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

+ 2 - 0
basics/cross-program-invocation/anchor/cpi-idl/programs/lever/Xargo.toml

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

+ 46 - 0
basics/cross-program-invocation/anchor/cpi-idl/programs/lever/src/lib.rs

@@ -0,0 +1,46 @@
+use anchor_lang::prelude::*;
+
+declare_id!("E64FVeubGC4NPNF2UBJYX4AkrVowf74fRJD9q6YhwstN");
+
+#[program]
+pub mod lever {
+    use super::*;
+
+    pub fn initialize(_ctx: Context<InitializeLever>) -> Result<()> {
+        Ok(())
+    }
+
+    pub fn switch_power(ctx: Context<SetPowerStatus>, name: String) -> Result<()> {
+        let power = &mut ctx.accounts.power;
+        power.is_on = !power.is_on;
+
+        msg!("{} is pulling the power switch!", &name);
+
+        match power.is_on {
+            true => msg!("The power is now on."),
+            false => msg!("The power is now off!"),
+        };
+
+        Ok(())
+    }
+}
+
+#[derive(Accounts)]
+pub struct InitializeLever<'info> {
+    #[account(init, payer = user, space = 8 + 8)]
+    pub power: Account<'info, PowerStatus>,
+    #[account(mut)]
+    pub user: Signer<'info>,
+    pub system_program: Program<'info, System>,
+}
+
+#[derive(Accounts)]
+pub struct SetPowerStatus<'info> {
+    #[account(mut)]
+    pub power: Account<'info, PowerStatus>,
+}
+
+#[account]
+pub struct PowerStatus {
+    pub is_on: bool,
+}

+ 44 - 0
basics/cross-program-invocation/anchor/cpi-idl/tests/cpi.ts

@@ -0,0 +1,44 @@
+import * as anchor from "@coral-xyz/anchor";
+import { Program } from "@coral-xyz/anchor";
+import { Hand } from "../target/types/hand";
+import { Lever } from "../target/types/lever";
+
+describe("cpi", () => {
+  const provider = anchor.AnchorProvider.env();
+  anchor.setProvider(provider);
+
+  const hand = anchor.workspace.Hand as Program<Hand>;
+  const lever = anchor.workspace.Lever as Program<Lever>;
+
+  // Generate a new keypair for the power account
+  const powerAccount = new anchor.web3.Keypair();
+
+  it("Initialize the lever!", async () => {
+    await lever.methods
+      .initialize()
+      .accounts({
+        power: powerAccount.publicKey,
+        user: provider.wallet.publicKey,
+      })
+      .signers([powerAccount])
+      .rpc();
+  });
+
+  it("Pull the lever!", async () => {
+    await hand.methods
+      .pullLever("Chris")
+      .accounts({
+        power: powerAccount.publicKey,
+      })
+      .rpc();
+  });
+
+  it("Pull it again!", async () => {
+    await hand.methods
+      .pullLever("Ashley")
+      .accounts({
+        power: powerAccount.publicKey,
+      })
+      .rpc();
+  });
+});

+ 10 - 0
basics/cross-program-invocation/anchor/cpi-idl/tsconfig.json

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