lokesh1jha / web-based-wallet

A simple web based wallet where someone can come and create a pneumonic, add multiple wallets and see the public key associated with each wallet.
https://sniff-wallet.vercel.app/
3 stars 3 forks source link

Create Token #15

Open lokesh1jha opened 1 month ago

lokesh1jha commented 1 month ago
zaheer-Khan3260 commented 1 month ago

Can you explain more?

lokesh1jha commented 1 month ago

This platform will allow users to create custom tokens, such as Dogecoin. It is important to note that Dogecoin is not a new blockchain but simply a contract deployed on Solana.

For more information on Solana's token program, refer to the following guide:
Solana Token Program


Backend Logic Example:

const express = require('express');
const bodyParser = require('body-parser');
const { Connection, Keypair, Transaction, sendAndConfirmTransaction } = require('@solana/web3.js');
const { Token, TOKEN_PROGRAM_ID } = require('@solana/spl-token');
require('dotenv').config();

const app = express();
app.use(bodyParser.json());

// Solana Connection Setup
const connection = new Connection(process.env.SOLANA_RPC_URL, 'confirmed');

// Admin Keypair (Backend signing)
const adminKeypair = Keypair.fromSecretKey(new Uint8Array(JSON.parse(process.env.ADMIN_PRIVATE_KEY)));

// Fees in SOL
const TOKEN_CREATION_FEE = 0.002;

/**
 * API to create a new token
 * Expects `name`, `symbol`, `decimals`, `initialSupply`, and `userWalletPubkey` from the frontend
 */
app.post('/create-token', async (req, res) => {
    try {
        const { name, symbol, decimals, initialSupply, userWalletPubkey } = req.body;

        // Create a new token mint
        const mintAccount = Keypair.generate();

        // Transaction to create mint
        const transaction = new Transaction().add(
            Token.createInitMintInstruction(
                TOKEN_PROGRAM_ID,
                mintAccount.publicKey,
                decimals, 
                adminKeypair.publicKey, 
                null 
            )
        );

        // Partially sign the transaction with the backend keypair
        transaction.partialSign(adminKeypair, mintAccount);

        // Send partially signed transaction back to the frontend for final signing
        res.json({
            transaction: transaction.serialize({ requireAllSignatures: false }).toString('base64'),
            mintPubkey: mintAccount.publicKey.toString(),
            message: `Minting token: ${symbol} with initial supply: ${initialSupply}`
        });
    } catch (error) {
        console.error('Error creating token:', error);
        res.status(500).json({ error: 'Failed to create token.' });
    }
});

/**
 * API to finalize token minting
 * Expects `signedTransaction`, `initialSupply`, `userWalletPubkey`
 */
app.post('/finalize-token', async (req, res) => {
    try {
        const { signedTransaction, mintPubkey, initialSupply, userWalletPubkey } = req.body;

        // Deserialize the transaction received from the frontend after wallet signing
        const transaction = Transaction.from(Buffer.from(signedTransaction, 'base64'));

        // Decode mint public key
        const mintPublicKey = new Keypair(mintPubkey);

        // Create an associated token account for the user
        const token = new Token(connection, mintPublicKey.publicKey, TOKEN_PROGRAM_ID, adminKeypair);
        const userTokenAccount = await token.getOrCreateAssociatedAccountInfo(userWalletPubkey);

        // Add instruction to mint the initial supply to the user's token account
        transaction.add(
            Token.createMintToInstruction(
                TOKEN_PROGRAM_ID,
                mintPublicKey.publicKey,
                userTokenAccount.address,  
                adminKeypair.publicKey,   
                [],
                initialSupply * Math.pow(10, token.decimals)
            )
        );

        // Sign with the admin keypair again to finalize
        transaction.sign(adminKeypair);

        // Send and confirm transaction
        const txid = await sendAndConfirmTransaction(connection, transaction, [adminKeypair]);

        res.json({
            success: true,
            message: `Token created and minted to ${userWalletPubkey}`,
            transactionSignature: txid,
        });
    } catch (error) {
        console.error('Error finalizing token minting:', error);
        res.status(500).json({ error: 'Failed to finalize token minting.' });
    }
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Frontend Logic Example:

// Step 1: Create token partially signed by the backend
async function createToken() {
    const response = await fetch('/create-token', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            name: 'TestToken',
            symbol: 'TT',
            decimals: 9,
            initialSupply: 1000,
            userWalletPubkey: wallet.publicKey.toBase58(),
        })
    });

    const { transaction, mintPubkey } = await response.json();

    // Step 2: Ask user to sign the transaction via wallet
    const signedTransaction = await wallet.signTransaction(transaction);

    // Step 3: Send signed transaction back to the backend for finalization
    await fetch('/finalize-token', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            signedTransaction: signedTransaction.serialize().toString('base64'),
            mintPubkey: mintPubkey,
            initialSupply: 1000,
            userWalletPubkey: wallet.publicKey.toBase58(),
        })
    });
}

This backend logic creates a new token on Solana by allowing the user to partially sign the transaction through their wallet, with the backend managing administrative aspects such as minting authority.

zaheer-Khan3260 commented 1 month ago

So, How can i contribute in this?

lokesh1jha commented 1 month ago

Fork this repo, this repo will be created in your GitHub.

Then, clone it. Make changes. Commit and push. Then raise a pr.

You can watch videos on YouTube to contribute to open source.

If you have knowledge of web3 then take this issue else pick some web2 project like devpool.

On Tue, 1 Oct, 2024, 6:36 am Zaheer khan, @.***> wrote:

So, How can i contribute in this?

— Reply to this email directly, view it on GitHub https://github.com/lokesh1jha/web-based-wallet/issues/15#issuecomment-2384581091, or unsubscribe https://github.com/notifications/unsubscribe-auth/AT762WJUU6ZDKL5MG7IUHOLZZHYRPAVCNFSM6AAAAABPCPPIRKVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDGOBUGU4DCMBZGE . You are receiving this because you authored the thread.Message ID: @.***>

am-miracle commented 1 month ago

Anyone can contribute to this or is someone working on this already?

lokesh1jha commented 1 month ago

I have added the logic

lokesh1jha commented 1 month ago

Take master pull Then start working on it

lokesh1jha commented 1 month ago

@am-miracle I have assigned you this issue. Are you working on it?

am-miracle commented 1 month ago

Yes I’m working on it

On Fri, Oct 4, 2024 at 7:40 AM LOKESH KUMAR JHA @.***> wrote:

@am-miracle I have assigned you this issue. Are you working on it?

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you were mentioned.Message ID: @.***>

am-miracle commented 1 month ago

Sorry, I made a little travel, but I'm back now. Will get right to it

am-miracle commented 1 month ago

@lokesh1jha I have fixed the uploadThing error, but each time I try to create a token I get this error

Token creation failed: SendTransactionError: Simulation failed. 
Message: Transaction simulation failed: Attempt to debit an account but found no record of a prior credit

I need help here. Is there something I'm supposed to do?

lokesh1jha commented 1 month ago

Ok. I will look into this and let you know.

On Tue, 8 Oct, 2024, 4:57 am Jude Miracle, @.***> wrote:

@lokesh1jha https://github.com/lokesh1jha I have fixed the uploadThing error, but each time I try to create a token I get this error

Token creation failed: SendTransactionError: Simulation failed. Message: Transaction simulation failed: Attempt to debit an account but found no record of a prior credit

I need help here. Is there something I'm supposed to do?

— Reply to this email directly, view it on GitHub https://github.com/lokesh1jha/web-based-wallet/issues/15#issuecomment-2398142483, or unsubscribe https://github.com/notifications/unsubscribe-auth/AT762WNK4PC3EWAME5G7HW3Z2MKEJAVCNFSM6AAAAABPCPPIRKVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDGOJYGE2DENBYGM . You are receiving this because you were mentioned.Message ID: @.***>

lokesh1jha commented 1 month ago

https://stackoverflow.com/questions/70654438/transaction-simulation-failed-attempt-to-debit-an-account-but-found-no-record-o

Check if your wallet is having sol

in your fork which branch is having your updated code

am-miracle commented 1 month ago

https://stackoverflow.com/questions/70654438/transaction-simulation-failed-attempt-to-debit-an-account-but-found-no-record-o

Check if your wallet is having sol

in your fork which branch is having your updated code

I created a new branch create-token. Also, I have sol, but the balance doesn't reflect, it does show I have sol in Explorer

lokesh1jha commented 1 month ago

image Have you pushed your branch on github : https://github.com/am-miracle/web-based-wallet/branches

I was unable to find your branch

am-miracle commented 1 month ago

@lokesh1jha I just pushed it to GitHub