Create Token

Create a Solana SPL token

New Way

import { getCreateAccountInstruction } from "@solana-program/system";
import { getInitializeMintInstruction, getMintSize, TOKEN_PROGRAM_ADDRESS } from "@solana-program/token";
import { createSolanaRpc, createSolanaRpcSubscriptions, generateKeyPairSigner, sendAndConfirmTransactionFactory, pipe, createTransactionMessage, setTransactionMessageLifetimeUsingBlockhash, signTransactionMessageWithSigners, getSignatureFromTransaction, setTransactionMessageFeePayerSigner, appendTransactionMessageInstructions, createKeyPairSignerFromBytes } from "@solana/web3.js";

import walletSecret from '../wallet.json';

async function main() {
    const rpc = createSolanaRpc('http://127.0.0.1:8899');
    const rpcSubscriptions = createSolanaRpcSubscriptions('ws://127.0.0.1:8900');

    const payer = await createKeyPairSignerFromBytes(new Uint8Array(walletSecret));

    const mint = await generateKeyPairSigner();

    const mintSpace = BigInt(getMintSize());
    const mintRent = await rpc.getMinimumBalanceForRentExemption(mintSpace).send();

    const instructions = [
        getCreateAccountInstruction({
            payer,
            newAccount: mint,
            lamports: mintRent,
            space: mintSpace,
            programAddress: TOKEN_PROGRAM_ADDRESS,
        }),
        getInitializeMintInstruction({
            mint: mint.address,
            decimals: 9,
            mintAuthority: payer.address
        }),
    ];

    const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
    const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });

    const transactionMessage = pipe(
        createTransactionMessage({ version: 0 }),
        (tx) => setTransactionMessageFeePayerSigner(payer, tx),
        (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
        (tx) => appendTransactionMessageInstructions(instructions, tx)
    );

    const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);
    try {
        await sendAndConfirmTransaction(signedTransaction, {
            commitment: 'processed',
            skipPreflight: true
        });
        const signature = getSignatureFromTransaction(signedTransaction);
        console.log(`Token created: ${mint.address} Signature: ${signature}`);
    } catch (e) {
        console.error('Transaction failed:', e);
        throw e;
    }
}

main();

Old Way

import { Connection, Keypair } from '@solana/web3.js';
import { createMint } from '@solana/spl-token';
import walletSecret from './wallet.json' assert { type: "json" };

const main = async () => {
    try {
        const wallet = Keypair.fromSecretKey(new Uint8Array(walletSecret));
        const connection = new Connection('http://localhost:8899', 'confirmed');

        const mint = await createMint(
            connection,
            wallet,
            wallet.publicKey, // mint authority
            null,      // freeze authority
            9 // decimals
        );
        console.log(`Mint created: ${mint.toBase58()}`);

        return {
            mintAddress: mint.toBase58(),
        };

    } catch (error) {
        console.error('Token creation failed:', error);
        throw error;
    }
};

main();

To add metadata to a token please follow instructions here https://developers.metaplex.com/guides/javascript/how-to-add-metadata-to-spl-tokens