September 23, 2021

How to Mint An NFT On Solana

Overview

Hello reader! Welcome to another Solana guide. Solana is an up-and-coming blockchain that seeks to solve the scalability issues that Ethereum has been handling. In this guide, you will walk through step-by-step how to create an NFT on Solana.

Prerequisites:

  • NodeJS installed
  • Terminal/CLI familiarity
  • Text editor

What is Solana?

Solana's goal is singular in nature. That goal is to scale the blockchain for global adoption. Solana Labs, the developers of the Solana Protocol, are doing a few different things to achieve that dream.

Blockchain technology has a few knobs when it comes to tuning performance. One of which is the consensus mechanism. This is how nodes communicate together to arrive at an identical conclusion. Bitcoin uses Proof of Work or PoW. Binance Smart Chain, also known as BSC, uses a Proof of Staked Authority or PoSA. And Ethereum is migrating to Proof of Stake aka PoS. As you can tell, consensus is by no means a solved game at this point in time.

Solana uses a consensus called Proof of History. Proof of History works through a time-stamping solution; each transaction has a time stamp allocated to it that allows it to be verified as a legitimate transaction by the rest of the network in mere fractions of a second. Solana has a breakdown of the eight technologies that they believe position themselves as the fastest, most scalable, and most secure blockchain in the game.

Connecting to Solana

We will be using the Solana Devnet in this tutorial. Solana has 3 different networks, the mainnet, the testnet, and the devnet. The devnet is a low-risk environment where you can "air drop" SOL tokens to yourself. Before connecting to the devnet, we need to follow the steps below to create a project directory and install the relevant dependencies.

mkdir SolanaNFT
cd SolanaNFT
touch index.js
npm i @solana/web3.js @solana/spl-token
This command will create a new project directory called SolanaNFT, a file index.js, and then install the JavaScript libraries, "@solana/web3.js" and "@solana/spl-token".

With that done, we can now write some JavaScript to connect to Solana! We can see in the below script how to connect to the Solana network.

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

(async () => {
  // Connect to cluster
  var connection = new web3.Connection(
    web3.clusterApiUrl("devnet"),
    'confirmed',
  );
})
In the first two lines, we are importing the dependencies we installed earlier.

In the function, you can see we are instantiating a new connection instance. This takes two arguments, one of which is a URL endpoint that points to the Solana Network. In our case, web3.clusterApiUrl("devnet") is a convenient method to point to the public endpoint of the Solana Devnet. With a connection established, we can now create the NFT and perform the other associated steps.

Creating the NFT

On to the fun part! The craze that is sweeping the community, the one and only NFT. NFT, short for Non Fungible Token, is a cryptographically unique hash that is unreplicatable. When you create an NFT, it is similar to creating an ERC20 token. However, the critical difference is only one token is ever issued.

To create our own NFT, we will have to complete a bit of a to do list. We can walk through that list right now and then hop into the code.

We will need to:

  1. Create an account with a wallet to mint an NFT
  2. Create an account with a wallet to send the NFT to
  3. Mint the NFT, and send it!

Note: Each of these code blocks should go underneath tne previous block, all within the top-level async function.

Well, the beginning is usually a good place to start. We can walk through creating an account and minting the NFT.

// Generate a new wallet keypair and airdrop SOL
  var fromWallet = web3.Keypair.generate();
  var fromAirdropSignature = await connection.requestAirdrop(
    fromWallet.publicKey,
    web3.LAMPORTS_PER_SOL,
  );
  //wait for airdrop confirmation
  await connection.confirmTransaction(fromAirdropSignature);

  //create new token mint
  let mint = await splToken.Token.createMint(
    connection,
    fromWallet,
    fromWallet.publicKey,
    null,
    9,
    splToken.TOKEN_PROGRAM_ID,
  );

  //get the token account of the fromWallet Solana address, if it does not exist, create it
  let fromTokenAccount = await mint.getOrCreateAssociatedAccountInfo(
    fromWallet.publicKey,
  );
I've commented on each code block, but we will walk through each method call and go into detail about what the parameters are, and what the function is doing.

  1. fromWallet - Creating a new pair of public and secret keys using the Keypair.generate() method.
  2. fromAirDropSignature - The requestAirdrop() method takes a public Key, and the amount of lamports in SOL you would like to receive. Lamports are Solana's equivalent to wei, the smallest amount that a SOL can be broken into. Most methods that require a number will default to the lamport measurement. In our case, the LAMPORTS_PER_SOL is a constant that represents 1 SOL worth of lamports.
  3. confirmTransaction - This call allows us to pass in a signed transaction as an argument and have the program wait until it has been confirmed before moving on to other portions of the code. This is important as our next step will have to pay a fee, and we will require the airdrop funds.
  4. mint - The createMint function will be what creates our actual token. It takes 6 arguments. 
    • i. The connection to the Solana Network. (connection) 
    • ii. The account that will pay the fee. (fromWallet) 
    • iii. The public key of the account that has the authority to mint tokens of this type. (fromWallet.publicKey) 
    • iv. The public key of the account that has the authority to freeze tokens of this type. This argument is optional. (null)
    • v. Amount of decimal places for your token. Most Solana tokens have 9 decimal places. 
    • vi.The program id of the token. You can read more about what program ids are here.
  5. fromTokenAccount - This creates or fetches the account (mint) associated with the public key (fromWallet.publicKey). You can think about the chain of custody like this: NFT resides in the account, and your wallet owns this account.

Chain of Custody: Keys -> Wallet -> Account

With that out of the way, we can move on to step 2!

We have an account to send the NFT from now we need an account to send the NFT to. Let us hop into the code for that.

// Generate a new wallet to receive newly minted token
 var toWallet = web3.Keypair.generate();

//get the token account of the toWallet Solana address, if it does not exist, create it
var toTokenAccount = await mint.getOrCreateAssociatedAccountInfo(
  toWallet.publicKey,
);

Not quite as much going on for this step. We repeat methods that we have already used above, so I will not go into great detail here. The above code block creates a wallet with a separate set of public/secret keys and then creates an account linking the mint variable to our newly created wallet.

With our first two steps complete, we should be ready to move onto step 3. The time to mint the NFT and send it to someone has come!

//minting 1 new token to the "fromTokenAccount" account we just returned/created
await mint.mintTo(
  fromTokenAccount.address, //who it goes to
  fromWallet.publicKey, // minting authority
  [], // multisig
  1000000000, // how many
);

await mint.setAuthority(
  mint.publicKey,
  null,
  "MintTokens",
  fromWallet.publicKey,
  []
)

// Add token transfer instructions to transaction
var transaction = new web3.Transaction().add(
  splToken.Token.createTransferInstruction(
    splToken.TOKEN_PROGRAM_ID,
    fromTokenAccount.address,
    toTokenAccount.address,
    fromWallet.publicKey,
    [],
    1,
  ),
);

// Sign transaction, broadcast, and confirm
var signature = await web3.sendAndConfirmTransaction(
  connection,
  transaction,
  [fromWallet],
  {commitment: 'confirmed'},
);
console.log('SIGNATURE', signature);

Awesome! Two new methods deal with the logic around creating the NFT and then the permissions around the token. The methods sendAndConfirmTransaction() and Transaction().add() have already been covered in a previous guide. If you are not familiar with how to send a transaction in Solana, you may want to take a peek over there to get a sense of what goes into it.

So with two methods to break down, we can hop right into it.

1. mintTo() - This takes the token mint and creates some. It takes 4 arguments: 
  • i. The destination. This is the address of the account to send it to. (fromTokenAccount.address)
  •  ii. This is the public key of the person that has the minting authority over the token (fromWallet.publicKey)
  •  iii. This is where you would pass multiple signer's addresses if you had set up your token to have multi-signature functionality. We did not in our case, so we pass an empty array. ([]) 
  • iv. How many tokens to send. Since we have 9 decimal places in this particular token, we are sending exactly 1 token to the address. (1000000000)

2. setAuthority() - This is the most crucial part of the process. The setAuthority() function will revoke minting privileges and ensure that we can not create additional tokens of this type. This action can not be undone, and takes 5 arguments:
  •  i. The account of the token (mint.publicKey)
  •  ii. The new authority you want to set. (null)
  •  iii. The type of authority that the account currently has. ("MintTokens")
  •  iv. The public key of the current authority holder. ("fromWallet.publicKey")
  •  v. An array of signers. In our case, we do not have multi-sig enabled. ([])

With all of that covered, the only thing left is to log the signature so you can take a look on the Solana Explorer.

Your signature will look something like the picture below.

Solana Transaction shown in the blockchain explorer


If you continue down the page, you will see that an account now has precisely 1 token, and since we disabled minting of additional tokens, it is now representative of an NFT. It is officially a one-of-a-kind token! If you go to the token address, you should see something like this picture below.

Newly Minted Token on the Solana Blockchain explorer


For posterities sake, I will include the entire block of code right here, just in case you are having any troubles putting things together.

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

(async () => {
  // Connect to cluster
  var connection = new web3.Connection(
    web3.clusterApiUrl("devnet"),
    'confirmed',
  );

  // Generate a new wallet keypair and airdrop SOL
  var fromWallet = web3.Keypair.generate();
  var fromAirdropSignature = await connection.requestAirdrop(
    fromWallet.publicKey,
    web3.LAMPORTS_PER_SOL,
  );
  //wait for airdrop confirmation
  await connection.confirmTransaction(fromAirdropSignature);

  //create new token mint
  let mint = await splToken.Token.createMint(
    connection,
    fromWallet,
    fromWallet.publicKey,
    null,
    9,
    splToken.TOKEN_PROGRAM_ID,
  );

  //get the token account of the fromWallet Solana address, if it does not exist, create it
  let fromTokenAccount = await mint.getOrCreateAssociatedAccountInfo(
    fromWallet.publicKey,
  );

   // Generate a new wallet to receive newly minted token
   var toWallet = web3.Keypair.generate();

  //get the token account of the toWallet Solana address, if it does not exist, create it
  var toTokenAccount = await mint.getOrCreateAssociatedAccountInfo(
    toWallet.publicKey,
  );

  //minting 1 new token to the "fromTokenAccount" account we just returned/created
  await mint.mintTo(
    fromTokenAccount.address, //who it goes to
    fromWallet.publicKey, // minting authority
    [], // multisig
    1000000000, // how many
  );

  await mint.setAuthority(
    mint.publicKey,
    null,
    "MintTokens",
    fromWallet.publicKey,
    []
  )

  // Add token transfer instructions to transaction
  var transaction = new web3.Transaction().add(
    splToken.Token.createTransferInstruction(
      splToken.TOKEN_PROGRAM_ID,
      fromTokenAccount.address,
      toTokenAccount.address,
      fromWallet.publicKey,
      [],
      1,
    ),
  );

  // Sign transaction, broadcast, and confirm
  var signature = await web3.sendAndConfirmTransaction(
    connection,
    transaction,
    [fromWallet],
    {commitment: 'confirmed'},
  );
  console.log('SIGNATURE', signature);
})();

Conclusion

If you made it this far, you learned a few things from this tutorial and some from our other Solana guides, so congratulations! Having gone through this one, you have successfully created an NFT on the Solana blockchain. The next step for you to do would be to link this unique one-of-a-kind token, to some asset. In the market right now, it is typically a picture that has been randomly generated with various properties or a one-off piece of art. If you would like to learn how to do exactly that, you can learn how to do that in this tutorial!

Subscribe to our newsletter for more articles and guides on Ethereum. If you have any feedback, feel free to reach out to us via Twitter. You can always chat with us on our Discord community server, featuring some of the coolest developers you will ever meet :)
Ready to try QuickNode? Start your 7-day free trial

Related articles 32

Jul 3, 2021 The Web3 Developer Stack

A developer stack is a bag of technologies a developer possesses. For example, MEAN (MongoDB, Express.js, AngularJS/Angular, and Node.js) and MERN (MongoDB, Express.js, React, and Node.js) are common web developer stacks. Similarly, today we will learn more about the web3...

Continue reading
Sep 22, 2021 How to do a non-custodial transaction with QuickNode

Private keys are one of the most sensitive pieces of data when it comes to cryptography and the blockchain. However, there has always been debate/confusion about choosing between custodial wallets (where the wallet provider has custody of the user’s private key) and...

Continue reading
Jun 7, 2021 How to integrate IPFS with Ethereum

It can be costly to store massive files on a blockchain mainnet, and this is where decentralized file storing systems like IPFS can come in handy. Sometimes, NFTs use IPFS as well. In this guide, we’ll cover how we can integrate IPFS with...

Continue reading
Jun 8, 2021 How to generate a new Ethereum address in PHP

PHP is very popular in developing the backend of websites or web applications. PHP has a huge crowd of developers trusting it as their go-to language. In this guide, we will see how we can generate a new Ethereum address in...

Continue reading
Jun 8, 2021 Estimating gas price using pending transactions in Python

To send a transaction on the Ethereum network, you need to pay fees for including the transaction in a block as well as the computation necessary in the transaction; this fee is called gas. The transactions are accepted into the block based on the amount of gas they are...

Continue reading
Jun 8, 2021 How to connect to Ethereum network with ethers.js

When someone thinks of developing a dApp the first tool that comes to their mind is web3.js which is pretty common because of its popularity in the community and wide use cases, dApp development has been consistently growing and there are a lot of developers who want to...

Continue reading
Jun 8, 2021 How to connect to the Ethereum network using Ruby

Ruby has a huge fanbase. Ruby was developed by its creator with an intention to create a language people can have fun using. Ruby has been largely accepted by the developers all around the world since it’s launch, in fact, the biggest tech communities in many cities are...

Continue reading
Jun 8, 2021 How to re-send a transaction with higher gas price using ethers.js

Sometimes, you submit a transaction on Ethereum without enough gas due to network congestion or too many pending transactions offering a higher gas price than you have offered on your transaction. If you have a high priority transaction but low gas, you could end up...

Continue reading
Jun 17, 2021 How to get the balance of an ERC-20 token

When a new token is made on the Ethereum network, it usually follows a specification. The most popular of which is the ERC20 specification. To meet this ERC20 standard, one's token must have a multitude of...

Continue reading
Jun 8, 2021 How to connect to Ethereum network with Web3.js

Libraries and frameworks make the development process a lot easier and faster. When it comes to Ethereum development, Web3.js is the go to library. That's because Web3.js is the official library, from the

Continue reading
Jun 8, 2021 How to generate a new Ethereum address in Ruby

With high usage in web applications and straightforward syntax, Ruby is used by a vast number of people. This guide will cover creating an Ethereum address in Ruby using ruby-eth...

Continue reading
Aug 15, 2021 How to Send a Transaction On Solana Using JavaScript

Hello reader! Today is an exhilarating day because we are going on an expedition to the Solana Blockchain. Solana is an up-and-coming blockchain seeking to improve upon the current ecosystem's solutions to the complex problem of providing a secure, scalable, decentralized...

Continue reading
Jun 8, 2021 How to Fork Ethereum Blockchain with Ganache.

Forking and running a local simulated Ethereum environment is essential if you want to work with DeFi or do Ethereum development in general. In this guide, we’ll cover how to fork Ethereum Blockchain with

Continue reading
Jun 8, 2021 How to fetch Ethereum event logs in Ruby

Ethereum log records are very useful to understand and keep track of smart contract events. In this guide, we are going to learn how to fetch ethereum event logs in Ruby using ethereum.rb ruby...

Continue reading
Jun 9, 2021 How to generate a new Ethereum address in Go

Golang is very popular among backend developers for building infrastructures and microservices. Go is a procedural programming language. Developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google, then launched in 2009 as...

Continue reading
Jun 9, 2021 How to generate a new Ethereum address in Python

Python is one of the most versatile programming languages out there with an abundance of use cases; We can build many applications with Python from client-side to back end. In this guide, we will cover creating an Ethereum address in Python using the

Continue reading
Jun 9, 2021 How to generate a new Ethereum address in JavaScript

When it comes to programming, there’s hardly anyone who has not used or heard about JavaScript. JavaScript was initially created for client-side scripting but has become a full-featured Object-Oriented...

Continue reading
Jun 9, 2021 How to connect to Ethereum network using Go

Go helps you make faster scalable backends and this guide will show you how to connect your backend to Ethereum (and make it even faster, more reliable, and globally accessible, all thanks to QuickNode’s global infrastructure). What is...

Continue reading
Jun 9, 2021 How to connect to Ethereum network using Java / Web3j

We can say that Java is one of the most versatile languages out there, and it continues to be relevant in today's time. Java is so popular because of its massive user base and use cases. In this guide/tutorial, we'll learn how to connect to the Ethereum Blockchain network...

Continue reading
Sep 24, 2021 How to Mint an NFT on Solana Using Candy Machine

Hello reader! We have had a lot of requests for another Solana NFT guide where we show you how to Mint a 1-of-1 token, or NFT on Solana. In the previous guide we did not quite get to...

Continue reading
Jun 9, 2021 How to connect to Ethereum using .NET (Nethereum)

Dotnet or .NET is very popular for the development of desktop applications, most Windows desktop applications are built using .NET, and it also contributes largely to web application’s tech stack. In this guide, let’s see how we can connect to Ethereum using .NET and

Continue reading
Jun 15, 2021 How to connect to Ethereum using PHP

PHP is a very popular choice among developers and has a vast community due to its long presence in web development. In this guide, we’ll cover how to connect to Ethereum with PHP using the web3.php...

Continue reading
Jul 15, 2021 How to Setup Local Development Environment for Solidity

The success story of blockchain started with Bitcoin and was given wings by Ethereum. Ethereum was the first blockchain to introduce programmable software to the immutable ledger; these programs that live on the blockchain are called smart contracts. Solidity is the...

Continue reading
Jun 9, 2021 How to use Subspace with QuickNode

In this guide, we'll understand a bit about reactive development and how to use Subspace with QuickNode.JavaScript is the programming language behind most of the internet apps and websites. JavaScript today has become one of the most used programming languages,...

Continue reading
Jun 9, 2021 How to connect to the Ethereum network using Python using Web3.py

You can build Ethereum applications in different programming languages. In this article, we will connect to the Ethereum network using Python.PrerequisiteEthereum Node (We will use QuickNode’s free...

Continue reading
Oct 10, 2021 Introduction to Scaffold-ETH 🏗

Developing applications involves juggling several moving pieces like front-ends, back-ends, and databases. But developing a decentralized application on a blockchain adds a few more elements like smart contracts and nodes that allow you to connect to the...

Continue reading
Jul 24, 2021 How to deploy a smart contract with Brownie

Python is one of the most versatile programming languages; from researchers running their test models to developers using it in heavy production environments, it has use cases in every possible technical field. In today's guide, we will learn about Brownie, a Python-based...

Continue reading
Jul 13, 2021 How To Fork Ethereum Mainnet with Hardhat

Forking the chain at an older block of the blockchain is helpful if you want to simulate the blockchain’s state at that block; Hardhat has this functionality built in. In this guide, let’s go through the process of forking the Ethereum Mainnet at an older...

Continue reading
Jun 26, 2021 How to create and deploy a smart contract with Hardhat

Ethereum development environments like Truffle and Hardhat make it easier to work with smart contracts and Ethereum nodes. They provide a set of tools to seamlessly write, test, and deploy...

Continue reading
Jul 2, 2021 How to generate a new Bitcoin address in JavaScript

To do any type of transaction on the Bitcoin blockchain, you’ll need a public key or a Bitcoin address. In this guide, we’ll cover how to generate a new Bitcoin address in JavaScript using CyrptoCoinJS.

Continue reading
Aug 13, 2021 How to create your own DAO with Aragon

Blockchain provides us with the power of decentralization. Decentralization means the transfer of power to users/members rather than having a single centralized authority governing everything; it enables various use cases in finance, governance, voting, fundraising, etc....

Continue reading
Aug 15, 2021 How to Create an Address in Solana using JavaScript

Hello reader! Welcome to QuickNode's first Solana guide. Solana is an up-and-coming blockchain that seeks to solve the scalability issues that Ethereum has been handling. You will walk through step-by-step how to create a Solana address using the @solana/web3.js...

Continue reading