瀏覽代碼

anchor permanent delegate example

John 1 年之前
父節點
當前提交
b2349a6dea

+ 1 - 1
tokens/token-2022/mint-close-authority/anchor/programs/mint-close-authority/src/lib.rs

@@ -20,7 +20,7 @@ pub mod mint_close_authority {
     use super::*;
 
     pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
-        Initialize::check_mint_data(&ctx.accounts)?;
+        ctx.accounts.check_mint_data()?;
         Ok(())
     }
 

+ 7 - 0
tokens/token-2022/permanent-delegate/anchor/.gitignore

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

+ 7 - 0
tokens/token-2022/permanent-delegate/anchor/.prettierignore

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

+ 18 - 0
tokens/token-2022/permanent-delegate/anchor/Anchor.toml

@@ -0,0 +1,18 @@
+[toolchain]
+
+[features]
+resolution = true
+skip-lint = false
+
+[programs.localnet]
+permanent_delegate = "A9rxKS84ZoJVyeTfQbCEfxME2vvAM4uwSMjkmhR5XWb1"
+
+[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
tokens/token-2022/permanent-delegate/anchor/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

+ 12 - 0
tokens/token-2022/permanent-delegate/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("@coral-xyz/anchor");
+
+module.exports = async function (provider) {
+  // Configure client to use the provider.
+  anchor.setProvider(provider);
+
+  // Add your deploy script here.
+};

+ 20 - 0
tokens/token-2022/permanent-delegate/anchor/package.json

@@ -0,0 +1,20 @@
+{
+  "scripts": {
+    "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w",
+    "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check"
+  },
+  "dependencies": {
+    "@coral-xyz/anchor": "^0.30.0",
+    "@solana/spl-token": "^0.4.6"
+  },
+  "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",
+    "prettier": "^2.6.2",
+    "ts-mocha": "^10.0.0",
+    "typescript": "^4.3.5"
+  }
+}

+ 22 - 0
tokens/token-2022/permanent-delegate/anchor/programs/permanent-delegate/Cargo.toml

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

+ 2 - 0
tokens/token-2022/permanent-delegate/anchor/programs/permanent-delegate/Xargo.toml

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

+ 59 - 0
tokens/token-2022/permanent-delegate/anchor/programs/permanent-delegate/src/lib.rs

@@ -0,0 +1,59 @@
+use anchor_lang::prelude::*;
+use anchor_spl::{
+    token_2022::spl_token_2022::extension::permanent_delegate::PermanentDelegate,
+    token_interface::{
+        spl_pod::optional_keys::OptionalNonZeroPubkey,
+        spl_token_2022::{
+            extension::{BaseStateWithExtensions, StateWithExtensions},
+            state::Mint as MintState,
+        },
+        Mint, Token2022,
+    },
+};
+
+declare_id!("A9rxKS84ZoJVyeTfQbCEfxME2vvAM4uwSMjkmhR5XWb1");
+
+#[program]
+pub mod permanent_delegate {
+    use super::*;
+
+    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
+        ctx.accounts.check_mint_data()?;
+        Ok(())
+    }
+}
+
+#[derive(Accounts)]
+pub struct Initialize<'info> {
+    #[account(mut)]
+    pub payer: Signer<'info>,
+
+    #[account(
+        init,
+        payer = payer,
+        mint::decimals = 2,
+        mint::authority = payer,
+        extensions::permanent_delegate::delegate = payer,
+    )]
+    pub mint_account: InterfaceAccount<'info, Mint>,
+    pub token_program: Program<'info, Token2022>,
+    pub system_program: Program<'info, System>,
+}
+
+// helper to check mint data, and demonstrate how to read mint extension data within a program
+impl<'info> Initialize<'info> {
+    pub fn check_mint_data(&self) -> Result<()> {
+        let mint = &self.mint_account.to_account_info();
+        let mint_data = mint.data.borrow();
+        let mint_with_extension = StateWithExtensions::<MintState>::unpack(&mint_data)?;
+        let extension_data = mint_with_extension.get_extension::<PermanentDelegate>()?;
+
+        assert_eq!(
+            extension_data.delegate,
+            OptionalNonZeroPubkey::try_from(Some(self.payer.key()))?
+        );
+
+        msg!("{:?}", extension_data);
+        Ok(())
+    }
+}

+ 86 - 0
tokens/token-2022/permanent-delegate/anchor/tests/permanent-delegate.ts

@@ -0,0 +1,86 @@
+import * as anchor from "@coral-xyz/anchor";
+import { Program } from "@coral-xyz/anchor";
+import { PermanentDelegate } from "../target/types/permanent_delegate";
+import {
+  TOKEN_2022_PROGRAM_ID,
+  burnChecked,
+  createAccount,
+  getAccount,
+  mintTo,
+} from "@solana/spl-token";
+
+describe("permanent-delegate", () => {
+  const provider = anchor.AnchorProvider.env();
+  const connection = provider.connection;
+  const wallet = provider.wallet as anchor.Wallet;
+  anchor.setProvider(provider);
+
+  const program = anchor.workspace
+    .PermanentDelegate as Program<PermanentDelegate>;
+
+  const mintKeypair = new anchor.web3.Keypair();
+
+  it("Create Mint with Permanent Delegate", async () => {
+    const transactionSignature = await program.methods
+      .initialize()
+      .accounts({ mintAccount: mintKeypair.publicKey })
+      .signers([mintKeypair])
+      .rpc({ skipPreflight: true });
+    console.log("Your transaction signature", transactionSignature);
+  });
+
+  it("Create Token Account, Mint Tokens, and burn with Permanent Delegate", async () => {
+    const amount = 100;
+
+    // Random keypair to use as owner of Token Account
+    const randomKeypair = new anchor.web3.Keypair();
+
+    // Create Token Account owned by random keypair
+    const sourceTokenAccount = await createAccount(
+      connection,
+      wallet.payer, // Payer to create Token Account
+      mintKeypair.publicKey, // Mint Account address
+      randomKeypair.publicKey, // Token Account owner
+      undefined, // Optional keypair, default to Associated Token Account
+      undefined, // Confirmation options
+      TOKEN_2022_PROGRAM_ID // Token Extension Program ID
+    );
+
+    // Mint tokens to sourceTokenAccount
+    await mintTo(
+      connection,
+      wallet.payer, // Transaction fee payer
+      mintKeypair.publicKey, // Mint Account address
+      sourceTokenAccount, // Mint to
+      wallet.publicKey, // Mint Authority address
+      amount, // Amount
+      undefined, // Additional signers
+      undefined, // Confirmation options
+      TOKEN_2022_PROGRAM_ID // Token Extension Program ID
+    );
+
+    // Burn tokens from sourceTokenAccount, using Permanent Delegate
+    // The permanent delegate can burn / transfer tokens from all token account for the mint account
+    const transactionSignature = await burnChecked(
+      connection,
+      wallet.payer, // Transaction fee payer
+      sourceTokenAccount, // Tranfer from
+      mintKeypair.publicKey, // Mint Account address
+      wallet.publicKey, // Use Permanent Delegate as owner
+      amount, // Amount
+      2, // Mint Account decimals
+      undefined, // Additional signers
+      undefined, // Confirmation options
+      TOKEN_2022_PROGRAM_ID // Token Extension Program ID
+    );
+    console.log("Your transaction signature", transactionSignature);
+
+    const tokenAccount = await getAccount(
+      connection,
+      sourceTokenAccount,
+      null,
+      TOKEN_2022_PROGRAM_ID
+    );
+    console.log("Token Account Balance:", Number(tokenAccount.amount));
+  });
+});

+ 10 - 0
tokens/token-2022/permanent-delegate/anchor/tsconfig.json

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

+ 1 - 2
tokens/token-2022/transfer-fees/anchor/programs/transfer-fee/src/instructions/initialize.rs

@@ -88,8 +88,7 @@ pub fn process_initialize(
         Some(&ctx.accounts.payer.key()), // freeze authority
     )?;
 
-    Initialize::check_mint_data(&ctx.accounts)?;
-
+    ctx.accounts.check_mint_data()?;
     Ok(())
 }
 

+ 0 - 5
tokens/token-2022/transfer-fees/anchor/tests/transfer-fee.ts

@@ -110,11 +110,6 @@ describe("transfer-fee", () => {
           isSigner: false,
           isWritable: true,
         },
-        {
-          pubkey: new anchor.web3.Keypair().publicKey,
-          isSigner: false,
-          isWritable: true,
-        },
       ])
       .rpc({ skipPreflight: true });
     console.log("Your transaction signature", transactionSignature);