node.jssolanasolana-web3jsmetaplexsolana-transaction-instruction

Error during metadata creation: Send transaction error: Failed to send transaction on Solana


I am facing this issue in my code, how to fix it?

here is the issue below

Let's mint some tokens! Transaction signature: 4cNLA44PuPgeWqjPNtGDXgCpmhnnhysEVUCh2hyKJGQqaxzSvBmcxZUir7BUV5gCpMrkJGLnuTn8PVFZwvyZpPUu. Mint public key: A9hNLG31b1wHKCKfvksG7TVUup1fdAKnTaJred3YnbAZ. Token account address: Bvw46kEhn4wowgMrRKmSrHPfq6KMPxGv7npYzyTfNoyr.

Let's name some tokens in 2024! Mint address A9hNLG31b1wHKCKfvksG7TVUup1fdAKnTaJred3YnbAZ. Error during metadata creation: SendTransactionError - Failed to send transaction. Transaction simulation failed: Error processing Instruction 0 - Program failed to complete. The error occurred at Connection.sendEncodedTransaction.

Logs: Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s invoke [1]. Program log: IX - Create Metadata Accounts v3. Program 11111111111111111111111111111111 invoke [2]. Program 11111111111111111111111111111111 success. Program log: Panicked at 'range end index 36 out of range for slice of length 0', src/token/utils.rs:50:27. Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s consumed 11330 of 200000 compute units. Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s failed: SBF program panicked.

main.js file

// main.js
const { config } = require("dotenv");
config();

const {
  Connection,
  Keypair,
  SystemProgram,
  Transaction,
  sendAndConfirmTransaction,
} = require("@solana/web3.js");
const {
  TOKEN_PROGRAM_ID,
  MINT_SIZE,
  ASSOCIATED_TOKEN_PROGRAM_ID,
  getMinimumBalanceForRentExemptMint,
  createInitializeMintInstruction,
  createAssociatedTokenAccountInstruction,
  getAssociatedTokenAddress,
  createMintToInstruction,
} = require("@solana/spl-token");

// Import metadata function from metadata.js
const { metadata } = require("./new");

let mint;

// connection endpoint
const connection = new Connection("https://api.devnet.solana.com");

// Load private key from environment variable
const privateKeyBytes = process.env.PRIVATE_KEY.split(",").map(Number);

// Wallet key pair
const walletKeyPair = Keypair.fromSecretKey(Uint8Array.from(privateKeyBytes));

// Function to create a token mint and associated token account and mint tokens
async function createMintAccountAndMintTokens() {
  try {
    console.log("Let's mint some tokens!");
    mint = Keypair.generate();
    const lamports = await getMinimumBalanceForRentExemptMint(connection);

    const associatedTokenAddress = await getAssociatedTokenAddress(
      mint.publicKey,
      walletKeyPair.publicKey,
      false,
      TOKEN_PROGRAM_ID,
      ASSOCIATED_TOKEN_PROGRAM_ID
    );

    const transaction = new Transaction();
    // Add create mint instruction
    transaction.add(
      SystemProgram.createAccount({
        fromPubkey: walletKeyPair.publicKey,
        newAccountPubkey: mint.publicKey,
        space: MINT_SIZE,
        lamports,
        programId: TOKEN_PROGRAM_ID,
      }),
      createInitializeMintInstruction(
        mint.publicKey,
        9, // decimals
        walletKeyPair.publicKey,
        walletKeyPair.publicKey,
        TOKEN_PROGRAM_ID
      ),
      // Add create associated token account instruction
      createAssociatedTokenAccountInstruction(
        walletKeyPair.publicKey,
        associatedTokenAddress,
        walletKeyPair.publicKey,
        mint.publicKey,
        TOKEN_PROGRAM_ID,
        ASSOCIATED_TOKEN_PROGRAM_ID
      ),
      // Add mint tokens instruction
      createMintToInstruction(
        mint.publicKey,
        associatedTokenAddress,
        walletKeyPair.publicKey,
        100000000000000 // Adjust this based on your token's decimal places
      )
    );

    const signature = await sendAndConfirmTransaction(
      connection,
      transaction,
      [walletKeyPair, mint],
      { commitment: "singleGossip", preflightCommitment: "singleGossip" }
    );

    console.log("Transaction Signature:", signature);
    console.log("Mint Public Key:", mint.publicKey.toBase58());
    console.log("Token Account Address:", associatedTokenAddress.toBase58());

    // Export the mint address
    return mint.publicKey.toBase58();
  } catch (error) {
    console.error("Error during minting:", error);
    throw error;
  }
}

// Call createMintAccountAndMintTokens and get the mint address
createMintAccountAndMintTokens()
  .then((mintAddress) => {
    // Set mint variable
    mint = mintAddress;

    // Call metadata function from metadata.js after minting
    return metadata(mint, mintAddress);
  })
  .catch((error) => {
    console.error(
      "Error creating mint and token account and minting tokens:",
      error
    );
    throw error;
  });

new.js file below

const { config } = require("dotenv");
config();
const {
  Collection,
  CreateMetadataAccountV3InstructionAccounts,
  CreateMetadataAccountV3InstructionDataArgs,
  Creator,
  MPL_TOKEN_METADATA_PROGRAM_ID,
  UpdateMetadataAccountV2InstructionAccounts,
  UpdateMetadataAccountV2InstructionData,
  Uses,
  createMetadataAccountV3,
  updateMetadataAccountV2,
  findMetadataPda,
} = require("@metaplex-foundation/mpl-token-metadata");
const web3 = require("@solana/web3.js");
const {
  PublicKey,
  createSignerFromKeypair,
  none,
  signerIdentity,
  some,
} = require("@metaplex-foundation/umi");
const { createUmi } = require("@metaplex-foundation/umi-bundle-defaults");
const {
  fromWeb3JsKeypair,
  fromWeb3JsPublicKey,
} = require("@metaplex-foundation/umi-web3js-adapters");

function loadWalletKey(privateKeyBytes) {
  return web3.Keypair.fromSecretKey(new Uint8Array(privateKeyBytes));
}

const INITIALIZE = true;

// Modify the function to accept mint public key and mint as arguments
async function metadata(mintAddress, mintPublicKey) {
  try {
    console.log("Let's name some tokens in 2024!");

    // Replace with your mint public key and metadata details
    // Now using the mint public key from main.js
    const metadataDetails = {
      name: "GUDS Coin",
      symbol: "GUDS",
      uri: "https://raw.githubusercontent.com/CHToken/LoomDeployerBot/main/metadata.json",
    };

    console.log("Mint Address", mintAddress);

    const privateKeyBytes = process.env.PRIVATE_KEY.split(",").map(Number);

    const umi = createUmi("https://api.devnet.solana.com");
    const signer = createSignerFromKeypair(
      umi,
      fromWeb3JsKeypair(loadWalletKey(privateKeyBytes))
    );
    umi.use(signerIdentity(signer, true));

    const onChainData = {
      ...metadataDetails,
      sellerFeeBasisPoints: 0,
      creators: none(),
      collection: none(),
      uses: none(),
    };

    if (INITIALIZE) {
      const accounts = {
        mint: mintAddress,
        mintAuthority: signer,
      };
      const data = {
        isMutable: true,
        collectionDetails: null,
        data: onChainData,
      };
      const txid = await createMetadataAccountV3(umi, {
        ...accounts,
        ...data,
      }).sendAndConfirm(umi);

      const signature = txid;
      console.log("Signature", signature);
    } else {
      const data = {
        data: some(onChainData),
        discriminator: 0,
        isMutable: some(true),
        newUpdateAuthority: none(),
        primarySaleHappened: none(),
      };
      const accounts = {
        metadata: findMetadataPda(umi, { mint: mintAddress }),
        updateAuthority: signer,
      };
      const txid = await updateMetadataAccountV2(umi, {
        ...accounts,
        ...data,
      }).sendAndConfirm(umi);
      console.log(txid);
    }
  } catch (error) {
    console.error("Error during metadata creation:", error);
    throw error;
  }
}

// Export the metadata function to be used in main.js
module.exports = { metadata };


Solution

  • The problem is where you are declaring your onChainData

    import {
      DataV2
    } from "@metaplex-foundation/mpl-token-metadata";
    
    //Rest of your code and imports...
    
    const onChainData = {
      ...metadataDetails,
      sellerFeeBasisPoints: 0,
      creators: none(),
      collection: none(),
      uses: none(),
    } as DataV2;
    
    // Rest of your code...

    You need to import DataV2 and specify the onChainData as that type.

    The error you got is an error you receive when you haven't passed the required parameters as it should be.