create your first nft with metaplex

September 23, 2024 (1w ago)

Hi there!

import {
  createProgrammableNft,
  mplTokenMetadata,
  createNft,
} from "@metaplex-foundation/mpl-token-metadata";
import {
  createGenericFile,
  generateSigner,
  percentAmount,
  sol,
  createSignerFromKeypair,
  signerIdentity,
} from "@metaplex-foundation/umi";
import { createUmi } from "@metaplex-foundation/umi-bundle-defaults";
import { irysUploader } from "@metaplex-foundation/umi-uploader-irys";
import { base58 } from "@metaplex-foundation/umi/serializers";
import fs from "fs";
import bs58 from "bs58";
 
// Create the wrapper function
const createNft1 = async () => {
  // Step 1: Initialize Umi client with devnet connection
  const umi = createUmi("https://api.devnet.solana.com")
    .use(mplTokenMetadata())
    .use(
      irysUploader({
        // The uploader for devnet
        address: "https://devnet.irys.xyz/",
      }),
    );
 
  // Step 2: Decode secret key to use for keypair creation
  const encodedString =
    "DxiLiYyNDjL78yRG3WS8rWSZ12Sa6vnWb4UMYz8UCw3bxpbFwx8Q3Ww9anM7g7axRXNDRUBkBZsHekXgevKvyRd";
  const decodedBytes = bs58.decode(encodedString);
  let keypair = umi.eddsa.createKeypairFromSecretKey(decodedBytes);
 
  // Step 3: Set the keypair as the signer identity
  const signer = createSignerFromKeypair(umi, keypair);
  umi.use(signerIdentity(signer));
 
  // Step 4: Read and upload the image
  const imageFile = fs.readFileSync("test.png");
  const umiImageFile = createGenericFile(imageFile, "test.png", {
    tags: [{ name: "Content-Type", value: "image/png" }],
  });
  const imageUri = await umi.uploader.upload([umiImageFile]).catch((err) => {
    throw new Error(err);
  });
 
  // Step 5: Create metadata for the NFT
  const metadata = {
    name: "2nd place",
    description: "This is an NFT on Solana",
    image: imageUri[0],
    external_url: "https://example.com/my-nft.json",
    attributes: [
      {
        trait_type: "trait1",
        value: "value1",
      },
      {
        trait_type: "trait2",
        value: "value2",
      },
    ],
    properties: {
      files: [
        {
          uri: imageUri[0],
          type: "image/png",
        },
      ],
      category: "image",
    },
  };
 
  // Step 6: Upload metadata to the uploader and get its URI
  const metadataUri = await umi.uploader.uploadJson(metadata).catch((err) => {
    throw new Error(err);
  });
 
  // Step 7: Generate a new signer for the NFT mint
  const nftSigner = generateSigner(umi);
 
  // Step 8: Create the NFT on the blockchain
  const tx = await createNft(umi, {
    mint: nftSigner,
    sellerFeeBasisPoints: percentAmount(5.5),
    name: "My NFT",
    uri: metadataUri,
  }).sendAndConfirm(umi);
 
  // Step 9: Deserialize and log the transaction signature
  console.log(base58.deserialize(tx.signature)[0]);
};
 
// Run the function
createNft1();

Explanation of the Code Initialize Umi: We start by creating a connection to the Solana Devnet. The createUmi function sets up the client, and we add two key plugins:

mplTokenMetadata: Used to handle the NFT metadata. irysUploader: Responsible for uploading the image and metadata to the IRYS service. Decoding the Secret Key: To sign transactions on Solana, we need a keypair. The secret key is decoded from Base58 format using bs58.decode(), and the createKeypairFromSecretKey() method creates a keypair for signing.

Setting the Signer Identity: The decoded keypair is set as the signer identity using the signerIdentity() method.

Uploading the Image: The image (test.png) is read using fs.readFileSync(). It is then converted into a Umi-compatible file format (createGenericFile), and uploaded using the uploader.upload() method. The upload returns a URI which points to the stored image.

Creating Metadata: Metadata for the NFT is defined, which includes fields like name, description, attributes, and properties. The image URI from the previous step is added to this metadata.

Uploading Metadata: The metadata object is uploaded as JSON using uploader.uploadJson(). This returns a URI that can be used when creating the NFT.

Generating a New Signer for the NFT Mint: The generateSigner() method creates a new signer, which is responsible for minting the NFT.

Creating the NFT: The createNft() method creates the NFT on the Solana blockchain. We pass the mint signer, metadata URI, and a seller fee as parameters. Once the transaction is confirmed, the NFT is successfully minted.

Deserializing the Transaction Signature: Finally, the transaction signature is deserialized and logged using base58.deserialize(), allowing us to verify it on the blockchain.

Conclusion This script provides a streamlined way to create an NFT on the Solana blockchain, handling both the image and metadata uploads via the IRYS service. By leveraging Umi and Metaplex, you can create, manage, and mint NFTs with ease.