我想在 solana 上铸造一个新的代币。我如何使用 solana-web3.js 来做到这一点?

I would like to mint a new token on solana. How can I do this using solana-web3.js?

我正在使用 solana-web3.js,但找不到有关如何创建和铸造我自己的代币的任何示例。执行此操作的最佳方法是什么?

为此,您还需要使用我们的令牌程序 js 绑定。您可以通过 npm 导入它们,如下面的示例代码所示。

const web3 =  require('@solana/web3.js');
const splToken = require('@solana/spl-token');

(async () => {

    //create connection to devnet
    const connection = new web3.Connection(web3.clusterApiUrl("devnet"));

    //generate keypair and airdrop 1000000000 Lamports (1 SOL)
    const myKeypair = web3.Keypair.generate();
    await connection.requestAirdrop(myKeypair.publicKey, 1000000000);

    console.log('solana public address: ' + myKeypair.publicKey.toBase58());

    //set timeout to account for airdrop finalization
    let mint;
    var myToken
    setTimeout(async function(){ 

        //create mint
        mint = await splToken.Token.createMint(connection, myKeypair, myKeypair.publicKey, null, 9, splToken.TOKEN_PROGRAM_ID)

        console.log('mint public address: ' + mint.publicKey.toBase58());

        //get the token accont of this solana address, if it does not exist, create it
        myToken = await mint.getOrCreateAssociatedAccountInfo(
            myKeypair.publicKey
        )

        console.log('token public address: ' + myToken.address.toBase58());

        //minting 100 new tokens to the token address we just created
        await mint.mintTo(myToken.address, myKeypair.publicKey, [], 1000000000);

        console.log('done');

    }, 20000);

})();

下面是一个如何做到这一点的例子。 假设:

  1. 您 (mintRequester) 有一个 Phantom 钱包。
  2. 铸币将从一个单独的铸币钱包进行,而不是您的 Phantom 钱包。
  3. 一些 SOL 被空投到这个新创建的铸币钱包中以处理铸币费用。
  4. 您的新代币有 6 位小数,您正在铸造 1 个代币。
  5. 代币最终从您的 minting 钱包 转移到您的 Phantom 钱包。

代码

import * as web3 from '@solana/web3.js';
import * as splToken from '@solana/spl-token';
 
 const getProvider = async () => {
    if ("solana" in window) {
      const provider = window.solana;
      if (provider.isPhantom) {
        console.log("Is Phantom installed?  ", provider.isPhantom);
        return provider;
      }
    } else {
      window.open("https://www.phantom.app/", "_blank");
    }
  };

const mintingTest = async () => {
    const phantomProvider = await getProvider();
    const mintRequester = await phantomProvider.publicKey;
    console.log("Public key of the mint Requester: ", mintRequester.toString());

    //To connect to the mainnet, write mainnet-beta instead of devnet
    const connection = new web3.Connection(
      web3.clusterApiUrl('devnet'),
      'confirmed',
    );

    //This fromWallet is your minting wallet, that will actually mint the tokens
    var fromWallet = web3.Keypair.generate();
     
    // Associate the mintRequester with this wallet's publicKey and privateKey
    // This is basically the credentials that the mintRequester (creator) would require whenever they want to mint some more tokens
   // Testing the parameters of the minting wallet
   
    console.log("Creator's Minting wallet public key: ",fromWallet.publicKey.toString());
    console.log(fromWallet.secretKey.toString());
    
    // Airdrop 1 SOL to the minting wallet to handle the minting charges
    var fromAirDropSignature = await connection.requestAirdrop(
      fromWallet.publicKey,
      web3.LAMPORTS_PER_SOL,
    );

    await connection.confirmTransaction(fromAirDropSignature);
    console.log("Airdropped (transferred) 1 SOL to the fromWallet to carry out minting operations");

    // This createMint function returns a Promise <Token>
    let mint = await splToken.Token.createMint(
      connection,
      fromWallet,
      fromWallet.publicKey,
      null,
      6, // Number of decimal places in your token
      splToken.TOKEN_PROGRAM_ID,
    );

    // getting or creating (if doens't exist) the token address in the fromWallet address
    // fromTokenAccount is essentially the account *inside* the fromWallet that will be able to handle the              new token that we just minted
    let fromTokenAccount = await mint.getOrCreateAssociatedAccountInfo(
      fromWallet.publicKey,
    );

    // getting or creating (if doens't exist) the token address in the toWallet address
    // toWallet is the creator: the og mintRequester
    // toTokenAmount is essentially the account *inside* the mintRequester's (creator's) wallet that will be able to handle the new token that we just minted
    let toTokenAccount = await mint.getOrCreateAssociatedAccountInfo(
      mintRequester,
    );
    
    // // Minting 1 token
    await mint.mintTo(
      fromTokenAccount.address,
      fromWallet.publicKey,
      [],
      1000000 // 1 followed by decimals number of 0s // You'll ask the creator ki how many decimals he wants in his token. If he says 4, then 1 token will be represented as 10000
    );
    
    console.log("Initial mint successful");

    
    // This transaction is sending of the creator tokens(tokens you just created) from their minting wallet to their Phantom Wallet
    var transaction = new web3.Transaction().add(
      splToken.Token.createTransferInstruction(
        splToken.TOKEN_PROGRAM_ID,
        fromTokenAccount.address,
        toTokenAccount.address,
        fromWallet.publicKey,
        [],
        1000000, // This is transferring 1 token, not 1000000 tokens
      ),
    );
        
    var signature = await web3.sendAndConfirmTransaction(
      connection,
      transaction,
      [fromWallet],
      {commitment: 'confirmed'},
    );

    const creatorTokenAddress = mint.publicKey;
    const creatorTokenAddressString = mint.publicKey.toString();

    console.log("SIGNATURE: ", signature); //Signature is basically like the paying party signs a transaction with their key.
    console.log("Creator Token Address: ", creatorTokenAddressString);
    console.log("Creator Minting Wallet Address: ", mint.payer.publicKey.toString());
    
    let creatorTokenBalance = await toTokenAccount.amount;
    console.log("Creator's Token Balance: ", creatorTokenBalance);
  };