Pārlūkot izejas kodu

create tokens reworked

jpcaulfi 2 gadi atpakaļ
vecāks
revīzija
5498307f6c
30 mainītis faili ar 111 papildinājumiem un 567 dzēšanām
  1. 0 1
      tokens/create-nft/README.md
  2. 0 14
      tokens/create-nft/anchor/Anchor.toml
  3. 0 14
      tokens/create-nft/anchor/package.json
  4. 0 21
      tokens/create-nft/anchor/programs/create-nft/Cargo.toml
  5. 0 86
      tokens/create-nft/anchor/programs/create-nft/src/lib.rs
  6. 0 63
      tokens/create-nft/anchor/tests/test.ts
  7. 0 8
      tokens/create-nft/native/cicd.sh
  8. 0 165
      tokens/create-nft/native/program/src/lib.rs
  9. 0 108
      tokens/create-nft/native/tests/test.ts
  10. 0 13
      tokens/create-spl-token/anchor/Cargo.toml
  11. 0 2
      tokens/create-spl-token/anchor/programs/create-spl-token/Xargo.toml
  12. 0 10
      tokens/create-spl-token/anchor/tsconfig.json
  13. 0 22
      tokens/create-spl-token/native/package.json
  14. 0 15
      tokens/create-spl-token/native/program/Cargo.toml
  15. 0 10
      tokens/create-spl-token/native/tsconfig.json
  16. 0 0
      tokens/create-token/README.md
  17. 1 1
      tokens/create-token/anchor/Anchor.toml
  18. 0 0
      tokens/create-token/anchor/Cargo.toml
  19. 0 0
      tokens/create-token/anchor/package.json
  20. 0 0
      tokens/create-token/anchor/programs/create-token/Cargo.toml
  21. 0 0
      tokens/create-token/anchor/programs/create-token/Xargo.toml
  22. 9 2
      tokens/create-token/anchor/programs/create-token/src/lib.rs
  23. 42 5
      tokens/create-token/anchor/tests/test.ts
  24. 0 0
      tokens/create-token/anchor/tsconfig.json
  25. 0 0
      tokens/create-token/native/cicd.sh
  26. 0 0
      tokens/create-token/native/package.json
  27. 0 0
      tokens/create-token/native/program/Cargo.toml
  28. 2 1
      tokens/create-token/native/program/src/lib.rs
  29. 57 6
      tokens/create-token/native/tests/test.ts
  30. 0 0
      tokens/create-token/native/tsconfig.json

+ 0 - 1
tokens/create-nft/README.md

@@ -1 +0,0 @@
-# Create an NFT

+ 0 - 14
tokens/create-nft/anchor/Anchor.toml

@@ -1,14 +0,0 @@
-[features]
-seeds = false
-[programs.localnet]
-create_nft = "6UxmhKzsfC71xdSX4TdaZQTRnPeKFsimR6tTWGNjpJSw"
-
-[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"

+ 0 - 14
tokens/create-nft/anchor/package.json

@@ -1,14 +0,0 @@
-{
-    "dependencies": {
-        "@project-serum/anchor": "^0.24.2"
-    },
-    "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"
-    }
-}

+ 0 - 21
tokens/create-nft/anchor/programs/create-nft/Cargo.toml

@@ -1,21 +0,0 @@
-[package]
-name = "create-nft"
-version = "0.1.0"
-description = "Created with Anchor"
-edition = "2021"
-
-[lib]
-crate-type = ["cdylib", "lib"]
-name = "create_nft"
-
-[features]
-no-entrypoint = []
-no-idl = []
-no-log-ix-name = []
-cpi = ["no-entrypoint"]
-default = []
-
-[dependencies]
-anchor-lang = "0.25.0"
-anchor-spl = "0.25.0"
-mpl-token-metadata = { version="1.2.5", features = [ "no-entrypoint" ] }

+ 0 - 86
tokens/create-nft/anchor/programs/create-nft/src/lib.rs

@@ -1,86 +0,0 @@
-use {
-    anchor_lang::{
-        prelude::*,
-        solana_program::program::invoke,
-    },
-    anchor_spl::token,
-    mpl_token_metadata::instruction as mpl_instruction,
-};
-
-
-declare_id!("6UxmhKzsfC71xdSX4TdaZQTRnPeKFsimR6tTWGNjpJSw");
-
-
-#[program]
-pub mod create_nft {
-    use super::*;
-
-    pub fn create_token_mint(
-        ctx: Context<CreateTokenMint>, 
-        token_title: String, 
-        token_symbol: String, 
-        token_uri: String,
-    ) -> Result<()> {
-    
-        msg!("Creating metadata account...");
-        msg!("Metadata account address: {}", &ctx.accounts.metadata_account.key());
-        invoke(
-            &mpl_instruction::create_metadata_accounts_v2(
-                ctx.accounts.token_metadata_program.key(),      // Program ID (the Token Metadata Program)
-                ctx.accounts.metadata_account.key(),            // Metadata account
-                ctx.accounts.mint_account.key(),                // Mint account
-                ctx.accounts.mint_authority.key(),              // Mint authority
-                ctx.accounts.payer.key(),                       // Payer
-                ctx.accounts.mint_authority.key(),              // Update authority
-                token_title,                                    // Name
-                token_symbol,                                   // Symbol
-                token_uri,                                      // URI
-                None,                                           // Creators
-                0,                                              // Seller fee basis points
-                true,                                           // Update authority is signer
-                false,                                          // Is mutable
-                None,                                           // Collection
-                None,                                           // Uses
-            ),
-            &[
-                ctx.accounts.metadata_account.to_account_info(),
-                ctx.accounts.mint_account.to_account_info(),
-                ctx.accounts.mint_authority.to_account_info(),
-                ctx.accounts.payer.to_account_info(),
-                ctx.accounts.mint_authority.to_account_info(),
-                ctx.accounts.rent.to_account_info(),
-            ]
-        )?;
-    
-        msg!("Token mint created successfully.");
-    
-        Ok(())
-    }
-}
-
-
-// The macros within the Account Context will create our
-//      Mint account and initialize it as a Mint
-//      We just have to do the metadata
-//
-#[derive(Accounts)]
-pub struct CreateTokenMint<'info> {
-    /// CHECK: We're about to create this with Metaplex
-    #[account(mut)]
-    pub metadata_account: UncheckedAccount<'info>,
-    #[account(
-        init,
-        payer = payer,
-        mint::decimals = 0,         // 0 decimals for the NFT standard
-        mint::authority = mint_authority.key(),
-    )]
-    pub mint_account: Account<'info, token::Mint>,
-    pub mint_authority: SystemAccount<'info>,
-    #[account(mut)]
-    pub payer: Signer<'info>,
-    pub rent: Sysvar<'info, Rent>,
-    pub system_program: Program<'info, System>,
-    pub token_program: Program<'info, token::Token>,
-    /// CHECK: Metaplex will check this
-    pub token_metadata_program: UncheckedAccount<'info>,
-}

+ 0 - 63
tokens/create-nft/anchor/tests/test.ts

@@ -1,63 +0,0 @@
-import * as anchor from "@project-serum/anchor";
-import { CreateNft } from "../target/types/create_nft";
-
-
-const TOKEN_METADATA_PROGRAM_ID = new anchor.web3.PublicKey(
-  "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"
-);
-
-
-describe("Create an NFT", () => {
-  
-  const provider = anchor.AnchorProvider.env();
-  anchor.setProvider(provider);
-  const payer = provider.wallet as anchor.Wallet;
-  const program = anchor.workspace.CreateNft as anchor.Program<CreateNft>;
-
-  const tokenTitle = "Solana Gold";
-  const tokenSymbol = "GOLDSOL";
-  const tokenUri = "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json";
-
-  const mintKeypair: anchor.web3.Keypair = anchor.web3.Keypair.generate();
-  console.log(`New token: ${mintKeypair.publicKey}`);
-
-  it("Create!", async () => {
-
-    const [mintAuthorityPda, mintAuthorityPdaBump] = await anchor.web3.PublicKey.findProgramAddress(
-      [
-        Buffer.from("mint_authority_"),
-        mintKeypair.publicKey.toBuffer(),
-      ],
-      program.programId,
-    );
-
-    const metadataAddress = (await anchor.web3.PublicKey.findProgramAddress(
-      [
-        Buffer.from("metadata"),
-        TOKEN_METADATA_PROGRAM_ID.toBuffer(),
-        mintKeypair.publicKey.toBuffer(),
-      ],
-      TOKEN_METADATA_PROGRAM_ID
-    ))[0];
-
-    const sx = await program.methods.createTokenMint(
-      tokenTitle, tokenSymbol, tokenUri
-    )
-      .accounts({
-        metadataAccount: metadataAddress,
-        mintAccount: mintKeypair.publicKey,
-        mintAuthority: mintAuthorityPda,
-        payer: payer.publicKey,
-        rent: anchor.web3.SYSVAR_RENT_PUBKEY,
-        systemProgram: anchor.web3.SystemProgram.programId,
-        tokenProgram: anchor.utils.token.TOKEN_PROGRAM_ID,
-        tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID,
-      })
-      .signers([mintKeypair, payer.payer])
-      .rpc();
-
-    console.log("Success!");
-        console.log(`   Mint Address: ${mintKeypair.publicKey}`);
-        console.log(`   Tx Signature: ${sx}`);
-  });
-});

+ 0 - 8
tokens/create-nft/native/cicd.sh

@@ -1,8 +0,0 @@
-#!/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

+ 0 - 165
tokens/create-nft/native/program/src/lib.rs

@@ -1,165 +0,0 @@
-use {
-    borsh::{ 
-        BorshSerialize, 
-        BorshDeserialize 
-    },
-    solana_program::{
-        account_info::{next_account_info, AccountInfo}, 
-        entrypoint,
-        entrypoint::ProgramResult, 
-        msg, 
-        program::invoke,
-        program_pack::Pack,
-        pubkey::Pubkey,
-        rent::Rent,
-        system_instruction,
-        sysvar::Sysvar,
-    },
-    spl_token::{
-        instruction as token_instruction,
-        state::Mint,
-    },
-    mpl_token_metadata::{
-        instruction as mpl_instruction,
-    },
-};
-
-
-#[derive(BorshSerialize, BorshDeserialize, Debug)]
-pub struct CreateTokenArgs {
-    pub token_title: String,
-    pub token_symbol: String,
-    pub token_uri: String,
-}
-
-
-entrypoint!(process_instruction);
-
-
-fn process_instruction(
-    _program_id: &Pubkey,
-    accounts: &[AccountInfo],
-    instruction_data: &[u8],
-) -> ProgramResult {
-
-    let args = CreateTokenArgs::try_from_slice(instruction_data)?;
-
-    let accounts_iter = &mut accounts.iter();
-
-    let mint_account = next_account_info(accounts_iter)?;
-    let mint_authority = next_account_info(accounts_iter)?;
-    let metadata_account = next_account_info(accounts_iter)?;
-    let payer = next_account_info(accounts_iter)?;
-    let rent = next_account_info(accounts_iter)?;
-    let system_program = next_account_info(accounts_iter)?;
-    let token_program = next_account_info(accounts_iter)?;
-    let token_metadata_program = next_account_info(accounts_iter)?;
-
-    // First create the account for the Mint
-    //
-    msg!("Creating mint account...");
-    msg!("Mint: {}", mint_account.key);
-    invoke(
-        &system_instruction::create_account(
-            &payer.key,
-            &mint_account.key,
-            (Rent::get()?).minimum_balance(Mint::LEN),
-            Mint::LEN as u64,
-            &token_program.key,
-        ),
-        &[
-            mint_account.clone(),
-            payer.clone(),
-            system_program.clone(),
-            token_program.clone(),
-        ]
-    )?;
-
-    // Now initialize that account as a Mint (standard Mint)
-    //
-    msg!("Initializing mint account...");
-    msg!("Mint: {}", mint_account.key);
-    invoke(
-        &token_instruction::initialize_mint(
-            &token_program.key,
-            &mint_account.key,
-            &mint_authority.key,
-            Some(&mint_authority.key),
-            0,                          // 0 Decimals for the NFT standard
-        )?,
-        &[
-            mint_account.clone(),
-            mint_authority.clone(),
-            token_program.clone(),
-            rent.clone(),
-        ]
-    )?;
-
-    // // Now create the account for that Mint's metadata
-    // //
-    // msg!("Creating metadata account...");
-    // msg!("Metadata account address: {}", metadata_account.key);
-    // invoke(
-    //     &mpl_instruction::create_metadata_accounts_v2(
-    //         *token_metadata_program.key,
-    //         *metadata_account.key,
-    //         *mint_account.key,
-    //         *mint_authority.key,
-    //         *payer.key,
-    //         *mint_authority.key,
-    //         args.token_title,
-    //         args.token_symbol,
-    //         args.token_uri,
-    //         None,
-    //         0,
-    //         true,
-    //         false,
-    //         None,
-    //         None,
-    //     ),
-    //     &[
-    //         metadata_account.clone(),
-    //         mint_account.clone(),
-    //         mint_authority.clone(),
-    //         payer.clone(),
-    //         token_metadata_program.clone(),
-    //         rent.clone(),
-    //     ]
-    // )?;
-
-    // // Optionally, we can make this NFT a "Master Edition"
-    // //
-    // msg!("Creating metadata account...");
-    // msg!("Metadata account address: {}", metadata_account.key);
-    // invoke(
-    //     &mpl_instruction::create_metadata_accounts_v2(
-    //         *token_metadata_program.key,
-    //         *metadata_account.key,
-    //         *mint_account.key,
-    //         *mint_authority.key,
-    //         *payer.key,
-    //         *mint_authority.key,
-    //         args.token_title,
-    //         args.token_symbol,
-    //         args.token_uri,
-    //         None,
-    //         0,
-    //         true,
-    //         false,
-    //         None,
-    //         None,
-    //     ),
-    //     &[
-    //         metadata_account.clone(),
-    //         mint_account.clone(),
-    //         mint_authority.clone(),
-    //         payer.clone(),
-    //         token_metadata_program.clone(),
-    //         rent.clone(),
-    //     ]
-    // )?;
-
-    msg!("NFT mint created successfully.");
-
-    Ok(())
-}

+ 0 - 108
tokens/create-nft/native/tests/test.ts

@@ -1,108 +0,0 @@
-import { 
-    PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID
-} from '@metaplex-foundation/mpl-token-metadata';
-import {
-    Connection,
-    Keypair,
-    PublicKey,
-    SystemProgram,
-    SYSVAR_RENT_PUBKEY,
-    TransactionInstruction,
-    Transaction,
-    sendAndConfirmTransaction,
-} from '@solana/web3.js';
-import {
-    TOKEN_PROGRAM_ID,
-} from '@solana/spl-token';
-import * as borsh from "borsh";
-import { Buffer } from "buffer";
-
-
-function createKeypairFromFile(path: string): Keypair {
-    return Keypair.fromSecretKey(
-        Buffer.from(JSON.parse(require('fs').readFileSync(path, "utf-8")))
-    )
-};
-
-
-class Assignable {
-    constructor(properties) {
-        Object.keys(properties).map((key) => {
-            return (this[key] = properties[key]);
-        });
-    };
-};
-
-class CreateTokenArgs extends Assignable {
-    toBuffer() {
-        return Buffer.from(borsh.serialize(CreateTokenArgsSchema, this));
-    }
-};
-const CreateTokenArgsSchema = new Map([
-    [
-        CreateTokenArgs, {
-            kind: 'struct',
-            fields: [
-                ['token_title', 'string'],
-                ['token_symbol', 'string'],
-                ['token_uri', 'string'],
-            ]
-        }
-    ]
-]);
-
-
-describe("Create an NFT!", async () => {
-
-    // const connection = new Connection(`https://api.devnet.solana.com/`, 'confirmed');
-    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');
-
-    const mintKeypair: Keypair = Keypair.generate();
-    console.log(`New token: ${mintKeypair.publicKey}`);
-
-    it("Create!", async () => {
-
-        const metadataAddress = (PublicKey.findProgramAddressSync(
-            [
-              Buffer.from("metadata"),
-              TOKEN_METADATA_PROGRAM_ID.toBuffer(),
-              mintKeypair.publicKey.toBuffer(),
-            ],
-            TOKEN_METADATA_PROGRAM_ID
-        ))[0];
-        
-        const metadataInstructionData = new CreateTokenArgs({
-            token_title: "Homer NFT",
-            token_symbol: "HOMR",
-            token_uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json",
-        });
-
-        let ix = new TransactionInstruction({
-            keys: [
-                { pubkey: mintKeypair.publicKey, isSigner: true, isWritable: true },            // Mint account
-                { pubkey: payer.publicKey, isSigner: false, isWritable: true },                 // Mint authority account
-                { pubkey: metadataAddress, isSigner: false, isWritable: true },                 // Metadata account
-                { pubkey: payer.publicKey, isSigner: true, isWritable: true },                  // Payer
-                { pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false },             // Rent account
-                { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },        // System program
-                { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },               // Token program
-                { pubkey: TOKEN_METADATA_PROGRAM_ID, isSigner: false, isWritable: false },      // Token metadata program
-            ],
-            programId: program.publicKey,
-            data: metadataInstructionData.toBuffer(),
-        });
-
-        const sx = await sendAndConfirmTransaction(
-            connection, 
-            new Transaction().add(ix),
-            [payer, mintKeypair]
-        );
-
-        console.log("Success!");
-        console.log(`   Mint Address: ${mintKeypair.publicKey}`);
-        console.log(`   Tx Signature: ${sx}`);
-    });
-  });
-  

+ 0 - 13
tokens/create-spl-token/anchor/Cargo.toml

@@ -1,13 +0,0 @@
-[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

+ 0 - 2
tokens/create-spl-token/anchor/programs/create-spl-token/Xargo.toml

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

+ 0 - 10
tokens/create-spl-token/anchor/tsconfig.json

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

+ 0 - 22
tokens/create-spl-token/native/package.json

@@ -1,22 +0,0 @@
-{
-  "scripts": {
-    "test": "yarn run ts-mocha -p ./tsconfig.json -t 1000000 ./tests/test.ts"
-  },
-  "dependencies": {
-    "@metaplex-foundation/mpl-token-metadata": "^2.5.2",
-    "@solana/spl-token": "^0.2.0",
-    "@solana/web3.js": "^1.47.3",
-    "borsh": "^0.7.0",
-    "buffer": "^6.0.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"
-  }
-}

+ 0 - 15
tokens/create-spl-token/native/program/Cargo.toml

@@ -1,15 +0,0 @@
-[package]
-name = "program"
-version = "0.1.0"
-edition = "2021"
-
-[dependencies]
-borsh = "0.9.3"
-borsh-derive = "0.9.1"
-solana-program = "1.10.26"
-spl-token = { version="3.3.0", features = [ "no-entrypoint" ] }
-spl-associated-token-account = { version="1.0.5", features = [ "no-entrypoint" ] }
-mpl-token-metadata = { version="1.2.5", features = [ "no-entrypoint" ] }
-
-[lib]
-crate-type = ["cdylib", "lib"]

+ 0 - 10
tokens/create-spl-token/native/tsconfig.json

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

+ 0 - 0
tokens/create-spl-token/README.md → tokens/create-token/README.md


+ 1 - 1
tokens/create-spl-token/anchor/Anchor.toml → tokens/create-token/anchor/Anchor.toml

@@ -1,7 +1,7 @@
 [features]
 seeds = false
 [programs.devnet]
-create_token = "2kPgnE1vA3LLJWwAW7MpVWw25mH5bc893FmfPH92ka1K"
+create_token = "5yRmjtx87UJMJF4NEeqjpmgAu7MBJZACW6ksiCYqQxVh"
 
 [registry]
 url = "https://anchor.projectserum.com"

+ 0 - 0
tokens/create-nft/anchor/Cargo.toml → tokens/create-token/anchor/Cargo.toml


+ 0 - 0
tokens/create-spl-token/anchor/package.json → tokens/create-token/anchor/package.json


+ 0 - 0
tokens/create-spl-token/anchor/programs/create-spl-token/Cargo.toml → tokens/create-token/anchor/programs/create-token/Cargo.toml


+ 0 - 0
tokens/create-nft/anchor/programs/create-nft/Xargo.toml → tokens/create-token/anchor/programs/create-token/Xargo.toml


+ 9 - 2
tokens/create-spl-token/anchor/programs/create-spl-token/src/lib.rs → tokens/create-token/anchor/programs/create-token/src/lib.rs

@@ -8,7 +8,7 @@ use {
 };
 
 
-declare_id!("2kPgnE1vA3LLJWwAW7MpVWw25mH5bc893FmfPH92ka1K");
+declare_id!("5yRmjtx87UJMJF4NEeqjpmgAu7MBJZACW6ksiCYqQxVh");
 
 
 #[program]
@@ -20,6 +20,7 @@ pub mod create_token {
         token_title: String, 
         token_symbol: String, 
         token_uri: String,
+        _token_decimals: u8,
     ) -> Result<()> {
     
         msg!("Creating metadata account...");
@@ -64,6 +65,12 @@ pub mod create_token {
 //      We just have to do the metadata
 //
 #[derive(Accounts)]
+#[instruction(
+    token_title: String, 
+    token_symbol: String, 
+    token_uri: String,
+    token_decimals: u8,
+)]
 pub struct CreateTokenMint<'info> {
     /// CHECK: We're about to create this with Metaplex
     #[account(mut)]
@@ -71,7 +78,7 @@ pub struct CreateTokenMint<'info> {
     #[account(
         init,
         payer = payer,
-        mint::decimals = 9,         // 9 decimals for the default SPL Token standard
+        mint::decimals = token_decimals,
         mint::authority = mint_authority.key(),
     )]
     pub mint_account: Account<'info, token::Mint>,

+ 42 - 5
tokens/create-spl-token/anchor/tests/test.ts → tokens/create-token/anchor/tests/test.ts

@@ -5,7 +5,7 @@ import * as anchor from "@project-serum/anchor";
 import { CreateToken } from "../target/types/create_token";
 
 
-describe("Create an SPL Token", () => {
+describe("Create Tokens", () => {
   
   const provider = anchor.AnchorProvider.env();
   anchor.setProvider(provider);
@@ -16,10 +16,9 @@ describe("Create an SPL Token", () => {
   const tokenSymbol = "GOLDSOL";
   const tokenUri = "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json";
 
-  const mintKeypair: anchor.web3.Keypair = anchor.web3.Keypair.generate();
-  console.log(`New token: ${mintKeypair.publicKey}`);
+  it("Create an SPL Token!", async () => {
 
-  it("Create!", async () => {
+    const mintKeypair: anchor.web3.Keypair = anchor.web3.Keypair.generate();
 
     const metadataAddress = (await anchor.web3.PublicKey.findProgramAddress(
       [
@@ -30,8 +29,46 @@ describe("Create an SPL Token", () => {
       TOKEN_METADATA_PROGRAM_ID
     ))[0];
 
+    // SPL Token default = 9 decimals
+    //
     const sx = await program.methods.createTokenMint(
-      tokenTitle, tokenSymbol, tokenUri
+      tokenTitle, tokenSymbol, tokenUri, 9
+    )
+      .accounts({
+        metadataAccount: metadataAddress,
+        mintAccount: mintKeypair.publicKey,
+        mintAuthority: payer.publicKey,
+        payer: payer.publicKey,
+        rent: anchor.web3.SYSVAR_RENT_PUBKEY,
+        systemProgram: anchor.web3.SystemProgram.programId,
+        tokenProgram: anchor.utils.token.TOKEN_PROGRAM_ID,
+        tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID,
+      })
+      .signers([mintKeypair, payer.payer])
+      .rpc();
+
+    console.log("Success!");
+        console.log(`   Mint Address: ${mintKeypair.publicKey}`);
+        console.log(`   Tx Signature: ${sx}`);
+  });
+
+  it("Create an NFT!", async () => {
+    
+    const mintKeypair: anchor.web3.Keypair = anchor.web3.Keypair.generate();
+
+    const metadataAddress = (await anchor.web3.PublicKey.findProgramAddress(
+      [
+        Buffer.from("metadata"),
+        TOKEN_METADATA_PROGRAM_ID.toBuffer(),
+        mintKeypair.publicKey.toBuffer(),
+      ],
+      TOKEN_METADATA_PROGRAM_ID
+    ))[0];
+
+    // NFT default = 0 decimals
+    //
+    const sx = await program.methods.createTokenMint(
+      tokenTitle, tokenSymbol, tokenUri, 0
     )
       .accounts({
         metadataAccount: metadataAddress,

+ 0 - 0
tokens/create-nft/anchor/tsconfig.json → tokens/create-token/anchor/tsconfig.json


+ 0 - 0
tokens/create-spl-token/native/cicd.sh → tokens/create-token/native/cicd.sh


+ 0 - 0
tokens/create-nft/native/package.json → tokens/create-token/native/package.json


+ 0 - 0
tokens/create-nft/native/program/Cargo.toml → tokens/create-token/native/program/Cargo.toml


+ 2 - 1
tokens/create-spl-token/native/program/src/lib.rs → tokens/create-token/native/program/src/lib.rs

@@ -30,6 +30,7 @@ pub struct CreateTokenArgs {
     pub token_title: String,
     pub token_symbol: String,
     pub token_uri: String,
+    pub token_decimals: u8,
 }
 
 
@@ -85,7 +86,7 @@ fn process_instruction(
             &mint_account.key,
             &mint_authority.key,
             Some(&mint_authority.key),
-            9,                          // 9 Decimals for the default SPL Token standard
+            args.token_decimals,
         )?,
         &[
             mint_account.clone(),

+ 57 - 6
tokens/create-spl-token/native/tests/test.ts → tokens/create-token/native/tests/test.ts

@@ -46,23 +46,23 @@ const CreateTokenArgsSchema = new Map([
                 ['token_title', 'string'],
                 ['token_symbol', 'string'],
                 ['token_uri', 'string'],
+                ['token_decimals', 'u8'],
             ]
         }
     ]
 ]);
 
 
-describe("Create an SPL Token!", async () => {
+describe("Create Tokens!", async () => {
 
     // const connection = new Connection(`http://localhost:8899`, 'confirmed');
     const connection = new Connection(`https://api.devnet.solana.com/`, 'confirmed');
     const payer = createKeypairFromFile(require('os').homedir() + '/.config/solana/id.json');
     const program = createKeypairFromFile('./program/target/deploy/program-keypair.json');
 
-    const mintKeypair: Keypair = Keypair.generate();
-    console.log(`New token: ${mintKeypair.publicKey}`);
+    it("Create an SPL Token!", async () => {
 
-    it("Create!", async () => {
+        const mintKeypair: Keypair = Keypair.generate();
 
         const metadataAddress = (PublicKey.findProgramAddressSync(
             [
@@ -73,10 +73,13 @@ describe("Create an SPL Token!", async () => {
             TOKEN_METADATA_PROGRAM_ID
         ))[0];
         
-        const metadataInstructionData = new CreateTokenArgs({
+        // SPL Token default = 9 decimals
+        //
+        const instructionData = new CreateTokenArgs({
             token_title: "Solana Gold",
             token_symbol: "GOLDSOL",
             token_uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json",
+            token_decimals: 9,
         });
 
         let ix = new TransactionInstruction({
@@ -91,7 +94,55 @@ describe("Create an SPL Token!", async () => {
                 { pubkey: TOKEN_METADATA_PROGRAM_ID, isSigner: false, isWritable: false },      // Token metadata program
             ],
             programId: program.publicKey,
-            data: metadataInstructionData.toBuffer(),
+            data: instructionData.toBuffer(),
+        });
+
+        const sx = await sendAndConfirmTransaction(
+            connection, 
+            new Transaction().add(ix),
+            [payer, mintKeypair]
+        );
+
+        console.log("Success!");
+        console.log(`   Mint Address: ${mintKeypair.publicKey}`);
+        console.log(`   Tx Signature: ${sx}`);
+    });
+
+    it("Create an NFT!", async () => {
+
+        const mintKeypair: Keypair = Keypair.generate();
+
+        const metadataAddress = (PublicKey.findProgramAddressSync(
+            [
+              Buffer.from("metadata"),
+              TOKEN_METADATA_PROGRAM_ID.toBuffer(),
+              mintKeypair.publicKey.toBuffer(),
+            ],
+            TOKEN_METADATA_PROGRAM_ID
+        ))[0];
+        
+        // NFT default = 0 decimals
+        //
+        const instructionData = new CreateTokenArgs({
+            token_title: "Homer NFT",
+            token_symbol: "HOMR",
+            token_uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json",
+            token_decimals: 9,
+        });
+
+        let ix = new TransactionInstruction({
+            keys: [
+                { pubkey: mintKeypair.publicKey, isSigner: true, isWritable: true },            // Mint account
+                { pubkey: payer.publicKey, isSigner: false, isWritable: true },                 // Mint authority account
+                { pubkey: metadataAddress, isSigner: false, isWritable: true },                 // Metadata account
+                { pubkey: payer.publicKey, isSigner: true, isWritable: true },                  // Payer
+                { pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false },             // Rent account
+                { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },        // System program
+                { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },               // Token program
+                { pubkey: TOKEN_METADATA_PROGRAM_ID, isSigner: false, isWritable: false },      // Token metadata program
+            ],
+            programId: program.publicKey,
+            data: instructionData.toBuffer(),
         });
 
         const sx = await sendAndConfirmTransaction(

+ 0 - 0
tokens/create-nft/native/tsconfig.json → tokens/create-token/native/tsconfig.json