Solana NFT Development Metaplex Complete Guide
NFT development on Solana is primarily powered by the Metaplex protocol. This guide covers comprehensive NFT development including candy machines, token metadata, collections, and compressed NFTs.
Token Metadata Standard
The Metaplex Token Metadata standard defines how NFTs are created and managed on Solana.
Metadata Structure
use anchor_lang::prelude::*;
use anchor_spl::token::{self, Mint, Token, TokenAccount};
declare_id!("MetaP11111111111111111111111111111111111111111");
#[account]
pub struct TokenMetadata {
pub name: String,
pub symbol: String,
pub uri: String,
pub seller_fee_basis_points: u16,
pub creators: Option<Vec<Creator>>,
pub collection: Option<Collection>,
pub uses: Option<Uses>,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct Creator {
pub address: Pubkey,
pub verified: bool,
pub share: u8,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct Collection {
pub verified: bool,
pub key: Pubkey,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct Uses {
pub use_method: UseMethod,
pub remaining: u64,
pub total: u64,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub enum UseMethod {
Burn,
Multiple,
Single,
}
Metadata Account Derivation
Metadata accounts are derived using PDA seeds:
pub fn find_metadata_account(mint: &Pubkey) -> (Pubkey, u8) {
Pubkey::find_program_address(
&[
b"metadata",
&crate::id().to_bytes(),
&mint.to_bytes(),
],
&crate::id(),
)
}
Candy Machine
Candy machines are the primary tool for minting NFT collections on Solana.
Candy Machine Configuration
use anchor_lang::prelude::*;
#[account]
pub struct CandyMachine {
pub authority: Pubkey,
pub wallet: Pubkey,
pub token_mint: Option<Pubkey>,
pub items_available: u64,
pub items_redeemed: u64,
pub price: u64,
pub go_live_date: i64,
pub end_settings: Option<EndSettings>,
pub hidden_settings: Option<HiddenSettings>,
pub whitelist_mint_settings: Option<WhitelistMintSettings>,
pub gatekeeper: Option<GatekeeperConfig>,
pub retain_authority: bool,
pub is_active: bool,
pub bump: u8,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct EndSettings {
pub end_setting_type: EndSettingType,
pub number: u64,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub enum EndSettingType {
Date,
Amount,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct HiddenSettings {
pub name: String,
pub uri: String,
pub hash: [u8; 32],
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct WhitelistMintSettings {
pub mode: WhitelistMintMode,
pub mint: Pubkey,
pub presale: bool,
pub discount_price: Option<u64>,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub enum WhitelistMintMode {
Either,
Hold,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct GatekeeperConfig {
pub gatekeeper_network: Pubkey,
pub expire_on_use: bool,
}
Mint from Candy Machine
pub fn mint_from_candy_machine(ctx: Context<MintNFT>) -> Result<()> {
let candy_machine = &mut ctx.accounts.candy_machine;
let mint = &ctx.accounts.mint;
let user = &ctx.accounts.user;
require!(candy_machine.is_active, ErrorCode::CandyMachineNotActive);
require!(
candy_machine.items_redeemed < candy_machine.items_available,
ErrorCode::SoldOut
);
let current_time = Clock::get()?.unix_timestamp;
require!(
current_time >= candy_machine.go_live_date,
ErrorCode::NotLiveYet
);
// Check whitelist if enabled
if let Some(whitelist) = &candy_machine.whitelist_mint_settings {
if whitelist.presale {
// Verify whitelist token
}
}
// Calculate metadata URI
let metadata_uri = if let Some(hidden) = &candy_machine.hidden_settings {
format!("{}.{}", hidden.name, hidden.uri)
} else {
// Derive from index
format!("https://arweave.net/{}", candy_machine.items_redeemed)
};
// Create metadata
create_metadata(
&ctx.accounts.metadata,
&mint.key(),
&user.key(),
&user.key(),
&metadata_uri,
)?;
candy_machine.items_redeemed += 1;
emit!(Minted {
candy_machine: candy_machine.key(),
mint: mint.key(),
buyer: user.key(),
index: candy_machine.items_redeemed - 1,
});
Ok(())
}
fn create_metadata(
metadata: &AccountInfo,
mint: &Pubkey,
authority: &Pubkey,
payer: &Pubkey,
uri: &str,
) -> Result<()> {
// Create metadata account using Metaplex CPI
Ok(())
}
#[derive(Accounts)]
pub struct MintNFT<'info> {
#[account(mut)]
pub user: Signer<'info>,
#[account(mut)]
pub candy_machine: Account<'info, CandyMachine>,
#[account(mut)]
pub mint: Account<'info, Mint>,
#[account(mut)]
pub metadata: AccountInfo<'info>,
pub token_program: Program<'info, Token>,
pub system_program: Program<'info, System>,
pub rent: Sysvar<'info, Rent>,
}
#[event]
pub struct Minted {
pub candy_machine: Pubkey,
pub mint: Pubkey,
pub buyer: Pubkey,
pub index: u64,
}
#[error_code]
pub enum ErrorCode {
#[msg("Candy machine is not active")]
CandyMachineNotActive,
#[msg("Sold out")]
SoldOut,
#[msg("Not live yet")]
NotLiveYet,
#[msg("Insufficient funds")]
InsufficientFunds,
}
Candy Machine Configuration Options
| Setting | Description | Default |
|---|---|---|
| price | Mint price in lamports | Required |
| items_available | Total NFTs in collection | Required |
| go_live_date | When minting starts | Required |
| end_settings | When minting ends | None |
| hidden_settings | Hidden metadata reveal | None |
| whitelist_mint | Whitelist token requirement | None |
NFT Collections
Collections group NFTs together and enable verification of authenticity.
Collection Manager
use anchor_lang::prelude::*;
#[account]
pub struct Collection {
pub authority: Pubkey,
pub name: String,
pub symbol: String,
pub uri: String,
pub size: u64,
pub verified: bool,
pub bump: u8,
}
#[account]
pub struct CollectionNFT {
pub collection: Pubkey,
pub mint: Pubkey,
pub verified: bool,
pub bump: u8,
}
pub fn verify_collection(ctx: Context<VerifyCollection>) -> Result<()> {
let collection = &ctx.accounts.collection;
let collection_nft = &mut ctx.accounts.collection_nft;
require!(
ctx.accounts.authority.key() == collection.authority,
ErrorCode::Unauthorized
);
collection_nft.verified = true;
emit!(CollectionVerified {
collection: collection.key(),
mint: collection_nft.mint,
});
Ok(())
}
#[derive(Accounts)]
pub struct VerifyCollection<'info> {
#[account(mut)]
pub authority: Signer<'info>,
#[account(seeds = [b"collection", authority.key().as_ref()], bump = collection.bump)]
pub collection: Account<'info, Collection>,
#[account(mut, seeds = [b"collection_nft", collection.key().as_ref(), collection_nft.mint.as_ref()], bump = collection_nft.bump)]
pub collection_nft: Account<'info, CollectionNFT>,
}
#[error_code]
pub enum ErrorCode {
#[msg("Unauthorized")]
Unauthorized,
}
Collection Verification Flow
ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ
β Creator ββββββΆβ Verify ββββββΆβ Update β
β Wallet β β Collection β β Metadata β
ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ
β β β
β β β
βΌ βΌ βΌ
ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ
β Signature β β CPI Call β β On-chain β
β Check β β to Metaplexβ β State β
ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ
Auction House
Auction houses enable peer-to-peer NFT trading with escrow services.
Auction House Program
use anchor_lang::prelude::*;
use anchor_spl::token::{self, Mint, Token, TokenAccount, Transfer};
declare_id!("AuctionHouse11111111111111111111111111111111");
#[account]
pub struct AuctionHouse {
pub authority: Pubkey,
pub fee_account: Pubkey,
pub treasury_mint: Pubkey,
pub treasury_fee: u16,
pub treasury_withdrawal_dest: Pubkey,
pub seller_fee_basis_points: u16,
pub requires_sign_off: bool,
pub can_change_sale_fee: bool,
pub bump: u8,
pub treasury_bump: u8,
pub fee_payer_bump: u8,
}
#[account]
pub struct Listing {
pub auction_house: Pubkey,
pub seller: Pubkey,
pub metadata: Pubkey,
pub price: u64,
pub token_size: u64,
pub bump: u8,
}
#[account]
pub struct Purchase {
pub auction_house: Pubkey,
pub buyer: Pubkey,
pub seller: Pubkey,
pub metadata: Pubkey,
pub price: u64,
pub token_size: u64,
pub bump: u8,
}
pub fn create_listing(ctx: Context<CreateListing>, price: u64) -> Result<()> {
let listing = &mut ctx.accounts.listing;
listing.auction_house = ctx.accounts.auction_house.key();
listing.seller = ctx.accounts.seller.key();
listing.metadata = ctx.accounts.metadata.key();
listing.price = price;
listing.token_size = 1;
listing.bump = ctx.bumps.listing;
emit!(ListingCreated {
auction_house: listing.auction_house,
seller: listing.seller,
metadata: listing.metadata,
price,
});
Ok(())
}
pub fn buy(ctx: Context<Buy>, token_size: u64) -> Result<()> {
let purchase = &mut ctx.accounts.purchase;
let listing = &ctx.accounts.listing;
let auction_house = &ctx.accounts.auction_house;
purchase.auction_house = listing.auction_house;
purchase.buyer = ctx.accounts.buyer.key();
purchase.seller = listing.seller;
purchase.metadata = listing.metadata;
purchase.price = listing.price;
purchase.token_size = token_size;
purchase.bump = ctx.bumps.purchase;
// Calculate fees
let fee = (listing.price as f128)
.checked_mul(auction_house.seller_fee_basis_points as f128)
.unwrap()
.checked_div(10000.0)
.unwrap() as u64;
let seller_amount = listing.price.checked_sub(fee).unwrap();
// Transfer payment
token::transfer(
CpiContext::new(
ctx.accounts.token_program.to_account_info(),
Transfer {
from: ctx.accounts.buyer_token_account.to_account_info(),
to: ctx.accounts.seller_token_account.to_account_info(),
authority: ctx.accounts.buyer.to_account_info(),
},
),
seller_amount,
)?;
// Transfer fee
token::transfer(
CpiContext::new(
ctx.accounts.token_program.to_account_info(),
Transfer {
from: ctx.accounts.buyer_token_account.to_account_info(),
to: ctx.accounts.treasury_account.to_account_info(),
authority: ctx.accounts.buyer.to_account_info(),
},
),
fee,
)?;
emit!(PurchaseMade {
auction_house: purchase.auction_house,
buyer: purchase.buyer,
seller: purchase.seller,
metadata: purchase.metadata,
price: listing.price,
});
Ok(())
}
#[derive(Accounts)]
pub struct CreateListing<'info> {
#[account(mut)]
pub seller: Signer<'info>,
#[account(seeds = [b"auction_house", auction_house.authority.as_ref()], bump = auction_house.bump)]
pub auction_house: Account<'info, AuctionHouse>,
#[account(mut)]
pub listing: Account<'info, Listing>,
pub metadata: AccountInfo<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct Buy<'info> {
#[account(mut)]
pub buyer: Signer<'info>,
#[account(seeds = [b"auction_house", auction_house.authority.as_ref()], bump = auction_house.bump)]
pub auction_house: Account<'info, AuctionHouse>,
#[account(mut)]
pub listing: Account<'info, Listing>,
#[account(mut)]
pub purchase: Account<'info, Purchase>,
#[account(mut)]
pub buyer_token_account: Account<'info, TokenAccount>,
#[account(mut)]
pub seller_token_account: Account<'info, TokenAccount>,
#[account(mut)]
pub treasury_account: Account<'info, TokenAccount>,
pub token_program: Program<'info, Token>,
}
#[event]
pub struct ListingCreated {
pub auction_house: Pubkey,
pub seller: Pubkey,
pub metadata: Pubkey,
pub price: u64,
}
#[event]
pub struct PurchaseMade {
pub auction_house: Pubkey,
pub buyer: Pubkey,
pub seller: Pubkey,
pub metadata: Pubkey,
pub price: u64,
}
#[error_code]
pub enum ErrorCode {
#[msg("Invalid price")]
InvalidPrice,
#[msg("Insufficient funds")]
InsufficientFunds,
#[msg("Unauthorized")]
Unauthorized,
}
Auction House Fee Structure
| Fee Type | Basis Points | Description |
|---|---|---|
| Seller Fee | 200-1000 | Goes to treasury |
| Buyer Fee | 0-500 | Optional |
| Withdrawal Fee | 0-250 | For quick sales |
Compressed NFTs (Bubblegum)
Compressed NFTs use state compression to dramatically reduce storage costs.
State Compression
use anchor_lang::prelude::*;
use spl_account_compression::{Node, MerkleTree};
declare_id!("CompressedNFT111111111111111111111111111111");
#[account]
pub struct CompressedCollection {
pub authority: Pubkey,
pub merkle_tree: Pubkey,
pub max_size: u64,
pub current_size: u64,
pub uri: String,
pub name: String,
pub symbol: String,
pub bump: u8,
}
pub fn create_compressed_nft(
ctx: Context<CreateCompressedNFT>,
name: String,
uri: String,
seller_fee_basis_points: u16,
) -> Result<()> {
let collection = &mut ctx.accounts.collection;
let mint = &ctx.accounts.mint;
// Create compressed NFT data
let data = CompressedNFTData {
name,
uri,
seller_fee_basis_points,
creators: vec![Creator {
address: ctx.accounts.creator.key(),
verified: true,
share: 100,
}],
};
// Append to merkle tree
let leaf = create_leaf_node(&mint.key(), &data);
spl_account_compression::append(
&ctx.accounts.merkle_tree,
&ctx.accounts.authority,
vec![leaf],
)?;
collection.current_size += 1;
emit!(CompressedNFTCreated {
collection: collection.key(),
mint: mint.key(),
index: collection.current_size - 1,
});
Ok(())
}
#[derive(Accounts)]
pub struct CreateCompressedNFT<'info> {
#[account(mut)]
pub creator: Signer<'info>,
#[account(mut)]
pub authority: Signer<'info>,
#[account(mut)]
pub collection: Account<'info, CompressedCollection>,
#[account(mut)]
pub mint: AccountInfo<'info>,
pub merkle_tree: AccountInfo<'info>,
pub token_program: Program<'info, Token>,
pub system_program: Program<'info, System>,
}
#[event]
pub struct CompressedNFTCreated {
pub collection: Pubkey,
pub mint: Pubkey,
pub index: u64,
}
Compression Cost Comparison
| NFT Type | Cost per NFT | Storage | Use Case |
|---|---|---|---|
| Standard NFT | 0.05+ SOL | Full metadata | High-value collectibles |
| Compressed NFT | 0.0005 SOL | Merkle proof | Large collections |
| Bulk Compressed | 0.0001 SOL | Shared tree | Gaming items |
Metaplex JS SDK Integration
Initialize Candy Machine
import { Metaplex, keypairIdentity } from '@metaplex-foundation/js';
import { Connection, Keypair, PublicKey } from '@solana/web3.js';
const connection = new Connection('https://api.mainnet-beta.solana.com');
const wallet = Keypair.fromSecretKey(/* secret key */);
const metaplex = Metaplex.make(connection)
.use(keypairIdentity(wallet));
async function createCandyMachine() {
const { candyMachine } = await metaplex
.candyMachines()
.create({
itemsAvailable: 1000,
sellerFeeBasisPoints: 500,
price: 0.1,
goLiveDate: new Date('2024-01-01'),
items: [
{ name: 'NFT #1', uri: 'https://arweave.net/1' },
{ name: 'NFT #2', uri: 'https://arweave.net/2' },
],
});
console.log('Candy Machine:', candyMachine.address);
return candyMachine;
}
Mint from Candy Machine
async function mintFromCandyMachine(candyMachineAddress: PublicKey) {
const { nft, response } = await metaplex
.candyMachines()
.mint({
candyMachine: candyMachineAddress,
});
console.log('Minted NFT:', nft.address);
console.log('Transaction:', response.signature);
return nft;
}
Fetch and Display NFTs
async function fetchNFTs(owner: PublicKey) {
const nfts = await metaplex
.nfts()
.findAllByOwner({ owner });
for (const nft of nfts) {
console.log('NFT:', nft.name);
console.log('Mint:', nft.mint.address);
console.log('URI:', nft.uri);
}
return nfts;
}
NFT Metadata Best Practices
Metadata JSON Structure
{
"name": "My NFT #1",
"symbol": "MNFT",
"description": "A unique digital collectible",
"seller_fee_basis_points": 500,
"image": "https://arweave.net/image.png",
"animation_url": "https://arweave.net/video.mp4",
"external_url": "https://example.com",
"attributes": [
{ "trait_type": "Color", "value": "Blue" },
{ "trait_type": "Rarity", "value": "Rare" },
{ "trait_type": "Power", "value": 85 }
],
"properties": {
"files": [
{ "uri": "https://arweave.net/image.png", "type": "image/png" }
],
"category": "image",
"creators": [
{ "address": "CreatorPubkey11111111111111111111111111111", "share": 100 }
]
}
}
Metadata Standards
| Field | Required | Description |
|---|---|---|
| name | Yes | NFT name |
| symbol | Yes | Token symbol |
| description | No | Detailed description |
| image | Yes | Image URL |
| attributes | No | Traits and properties |
| external_url | No | Website link |
| animation_url | No | Video/animation |
Trade-offs
NFT Development Trade-offs
| Decision | Pros | Cons |
|---|---|---|
| Standard NFTs | Full control | Higher costs |
| Compressed NFTs | Low cost | Complex transfer |
| Candy Machine | Easy minting | Limited customization |
| Custom Program | Full flexibility | Development time |
| Arweave storage | Permanent | Upload costs |
| IPFS storage | Decentralized | May pin fees |
Metaplex vs Custom Implementation
| Aspect | Metaplex | Custom |
|---|---|---|
| Development Time | Fast | Slow |
| Cost | Standard | Variable |
| Features | Pre-built | Custom |
| Support | Community | Self-managed |
| Flexibility | Limited | Full |
Interview Questions
-
Explain the difference between standard and compressed NFTs on Solana.
-
How does the Candy Machine whitelist feature work?
-
What are the benefits of using Metaplex for NFT development?
Quiz Questions
-
What is the primary benefit of compressed NFTs?
- a) Better image quality
- b) Lower storage costs
- c) Faster minting
- d) More metadata fields
-
What does the seller_fee_basis_points field control?
- a) Mint price
- b) Royalty percentage
- c) Collection size
- d) Metadata validity
-
How are NFT metadata accounts derived?
- a) Random generation
- b) Sequential numbering
- c) PDA with mint address
- d) User specification
Conclusion
Solana NFT development with Metaplex provides powerful tools for creating digital assets. Understanding token metadata, candy machines, collections, and compressed NFTs is essential for building successful NFT projects on Solana.