Skip to content

Facing WalletSendTransactionError in react application #215

@Shrey-Vats

Description

@Shrey-Vats

Title: WalletSendTransactionError: Unexpected error while creating token


Description

Hello 👋
While experimenting with a dApp, I encountered the following error:

WalletSendTransactionError: Unexpected error

Steps to Reproduce

Here’s the React + Solana code I’m using:

import {
  Connection,
  Keypair,
  SystemProgram,
  Transaction,
} from "@solana/web3.js";
import {
  createInitializeMetadataPointerInstruction,
  createInitializeMintInstruction,
  ExtensionType,
  getMintLen,
  LENGTH_SIZE,
  TYPE_SIZE,
  TOKEN_2022_PROGRAM_ID,
} from "@solana/spl-token";
import { createInitializeInstruction, pack } from "@solana/spl-token-metadata";
import { useWallet } from "@solana/wallet-adapter-react";
import { useState } from "react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import ShowBalance from "./ShowBalance";

export default function Screen() {
  const [tokenName, setTokenName] = useState("");
  const [tokenSymbol, setTokenSymbol] = useState("");
  const [loading, setLoading] = useState(false);

  const { publicKey, sendTransaction } = useWallet();
  const connection = new Connection("https://api.devnet.solana.com");

  const createToken = async () => {
    try {
      if (!publicKey) {
        alert("⚠️ Please connect your wallet first.");
        return;
      }

      if (!tokenName.trim() || !tokenSymbol.trim()) {
        alert("⚠️ Please enter valid token name and symbol.");
        return;
      }

      setLoading(true);

      const mintKeypair = Keypair.generate();

      const metadata = {
        mint: mintKeypair.publicKey,
        name: tokenName.trim(),
        symbol: tokenSymbol.trim(),
        uri: "https://example.com/metadata.json",
        additionalMetadata: [],
      };

      const mintLen = getMintLen([ExtensionType.MetadataPointer]);
      const metadataLen = TYPE_SIZE + LENGTH_SIZE + pack(metadata).length;
      const totalSpace = mintLen + metadataLen;

      const lamports = await connection.getMinimumBalanceForRentExemption(totalSpace);

      const transaction = new Transaction().add(
        SystemProgram.createAccount({
          fromPubkey: publicKey,
          newAccountPubkey: mintKeypair.publicKey,
          space: totalSpace,
          lamports,
          programId: TOKEN_2022_PROGRAM_ID,
        }),
        createInitializeMetadataPointerInstruction(
          mintKeypair.publicKey,
          publicKey,
          mintKeypair.publicKey,
          TOKEN_2022_PROGRAM_ID
        ),
        createInitializeMintInstruction(
          mintKeypair.publicKey,
          9, // decimals
          publicKey,
          publicKey,
          TOKEN_2022_PROGRAM_ID
        ),
        createInitializeInstruction({
          programId: TOKEN_2022_PROGRAM_ID,
          mint: mintKeypair.publicKey,
          metadata: mintKeypair.publicKey,
          name: metadata.name,
          symbol: metadata.symbol,
          uri: metadata.uri,
          mintAuthority: publicKey,
          updateAuthority: publicKey,
        })
      );

      const block = await connection.getLatestBlockhash();
      transaction.recentBlockhash = block.blockhash;
      transaction.feePayer = publicKey;

      transaction.partialSign(mintKeypair);

      const signature = await sendTransaction(transaction, connection);

      console.log("signature is :- ", signature);

      alert(`✅ Token Created! Mint Address:\n${mintKeypair.publicKey.toBase58()}`);
      console.log("Mint Public Key:", mintKeypair.publicKey.toBase58());
    } catch (error: any) {
      console.error("Error creating token:", error);
      alert(`❌ Error: ${error.message || error}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen flex-col items-center justify-center bg-gradient-to-br from-gray-900 via-gray-800 to-black text-white px-6 py-10">
      <div className="w-full max-w-md rounded-2xl bg-gray-800/60 shadow-xl backdrop-blur-lg p-8 border border-gray-700">
        <h1 className="text-3xl font-bold mb-6 text-center">🪙 Create SPL Token</h1>
        <ShowBalance />
        <div className="space-y-4">
          <div>
            <Label className="text-gray-300 mb-1 block">Token Name</Label>
            <Input
              className="bg-gray-900 text-white border-gray-700 focus:ring-2 focus:ring-indigo-500"
              placeholder="e.g., MyToken"
              value={tokenName}
              onChange={(e) => setTokenName(e.target.value)}
            />
          </div>

          <div>
            <Label className="text-gray-300 mb-1 block">Token Symbol</Label>
            <Input
              className="bg-gray-900 text-white border-gray-700 focus:ring-2 focus:ring-indigo-500"
              placeholder="e.g., MYT"
              value={tokenSymbol}
              onChange={(e) => setTokenSymbol(e.target.value)}
            />
          </div>

          <Button
            onClick={createToken}
            disabled={loading}
            className="w-full mt-6 bg-indigo-600 hover:bg-indigo-500 transition-all duration-200"
          >
            {loading ? "Creating Token..." : "Create Token"}
          </Button>
        </div>
      </div>
    </div>
  );
}

Expected Behavior

The token should be created successfully on Solana Devnet using the provided metadata.


Actual Behavior

I’m receiving the following error when sending the transaction:

WalletSendTransactionError: Unexpected error

Additional Context

  • Network: Devnet
  • Wallet: Phantom
  • Packages:
    • @solana/web3.js: latest
    • @solana/spl-token: latest
    • @solana/spl-token-metadata: latest
    • @solana/wallet-adapter-react: latest

Notes

Any guidance on whether this is a signing issue, a program mismatch, or a missing serialization step would be greatly appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions