15 min read
Esta guía utiliza Sugar V2 con Candy Machine V3, que ya ha quedado obsoleta. Para nuevos proyectos de NFT, consulta «Cómo lanzar una colección de NFT con Metaplex Core Candy Machine». Esta guía tiene únicamente fines educativos y de carácter histórico.
Resumen
Are you ready to launch your NFT collection on Solana? Metaplex's Candy Machine CLI, Sugar, is the tool for you to launch in no time. If you have used previous versions of Candy Machine, you will notice that Sugar has a few significant improvements:
- mejor rendimiento en la subida de archivos
- experiencia de usuario simplificada
- mejora en la gestión de errores
Tus funciones
In this guide, you will create a new wallet using Solana CLI, airdrop some SOL, and deploy a Candy Machine on Solana's devnet using Sugar. You'll then deploy your Candy Machine to the web using the Solana dApp Scaffold and Metaplex's new modular JS framework, Umi.
Lo que necesitarás
- Node.js installed (version 16.15 or higher)
- Solana CLI instalado
- Extensión Phantom Wallet o Solflare instalada
- Metaplex Sugar installed (**Latest Version, V2.x+ **) (installation instructions below)
- Un editor de texto
- npm or yarn installed (We will use yarn to initialize our project and install the necessary packages. Feel free to use npm instead if that's your preferred package manager.)
Configura tu proyecto
Create a new project directory in your terminal with the following:
mkdir sugar-demo
cd sugar-demo
Instalar Sugar
During installation, you will be asked which version you want to use. V1.x is for Candy Machine v2, V2.x is for Candy Machine v3. This guide assumes you are using V2.x. (Candy Machine v3). If you are using an older version, check out our guide here.
Instalación en Mac
In your terminal, enter:
bash <(curl -sSf https://sugar.metaplex.com/install.sh)
Nota: Es posible que tengas que reiniciar el terminal tras la instalación.
Instalación de Windows
- Download the Windows installer here.
- Ejecuta el instalador como administrador (clic con el botón derecho del ratón -->Ejecutar como administrador). If you get a warning about an untrusted binary, try clicking Más información y luego Corre de todos modos. Si no dispones de esta opción, sigue estos pasos:
- Haz clic con el botón derecho del ratón en el archivo ejecutable y selecciona «Propiedades».
- If you trust the Metaplex developer team, check the Unblock button as shown in the image below. This will allow you to run this binary on your computer since Microsoft does not trust it automatically.
- Haz clic en «Aplicar » y en «Aceptar».
- Vuelve a ejecutar el instalador
Si todo funciona correctamente, deberías ver algo como esto:

You should be able to verify your sugar installation by entering sugar --version in your terminal. You should see something like this:
Quicknode % sugar --version
sugar-cli 2.5.0
Configurar un monedero nuevo
One of the cool new features of Sugar is that it will allow you to set your wallet and RPC configs using Solana CLI so that you don't need to re-enter them in each of your Sugar commands.
En primer lugar, debemos crear un nuevo monedero destinado específicamente a las pruebas en devnet con el siguiente comando:
solana-keygen new --no-bip39-passphrase --outfile ./wallet.json
We can confirm that the wallet we just generated is the wallet that the Solana CLI will use by running the following:
Configuración de Solana configurar --keypair ./wallet.json
Note: we are using a relative path to our wallet in this example as we will not be changing directories, but you may include a full path if you prefer.
Establecer una conexión con tu RPC de Quicknode
Conéctate a un clúster de Solana con tu punto de conexión de Quicknode
Para desarrollar en Solana, necesitarás un punto final de API para conectarte a la red. Puedes utilizar nodos públicos o implementar y gestionar tu propia infraestructura; sin embargo, si quieres tiempos de respuesta 8 veces más rápidos, puedes dejarnos a nosotros el trabajo pesado.
Descubre por qué más del 50 % de los proyectos en Solana Elige Quicknode y empieza tu prueba gratuita aquí. Vamos a utilizar un Solana Devnet punto final.
Copia el HTTP Enlace del proveedor:
Una vez configurado tu punto final en la red de desarrollo de Solana, ya puedes ejecutar este comando, sustituyendo TU_URL_DE_QUICKNODE con la URL HTTP que has copiado:
Configuración de Solana establecer --url TU_URL_DE_QUICKNODE
Now to fund your wallet, you can run the command:
Airdrop de Solana 1
If the command is successful, you should see something like this:

También puedes ejecutar saldo de Solana en tu terminal y comprueba que aparece 1 SOL.
Preparar activos NFT
If you have used Candy Machine before, this process will be familiar. We must create a .json file corresponding to each digital asset using a simple number format starting with 0 and increasing sequentially, never skipping a number (e.g., 0.json maps to 0.png, then 1.json maps to 1.png). We can also create an optional collection.json and collection.png to enable Sugar to create an on-chain collection automatically.
Metaplex dispone de un conjunto de ejemplos de recursos que podemos descargar y utilizar para mantener la coherencia. Puedes editar el archivo JSON para incluir los valores que desees, siempre y cuando se ajuste al esquema JSON de URI.
Download the sample set and extract the contents to ./assets/ in your project directory (the default directory that Sugar will look for your files).
Configurar la máquina de golosinas
Create a new file, config.json, in your root project folder:
echo > config.json
Abre el archivo y pega esta configuración:
{
"number": 10,
"symbol": "NB",
"sellerFeeBasisPoints": 500,
"isMutable": true,
"isSequential": false,
"ruleSet": null,
"creators": [
{
"address": "YOUR_WALLET_ADDRESS",
"share": 100
}
],
"uploadMethod": "bundlr",
"awsS3Bucket": null,
"retainAuthority": true,
"awsConfig": null,
"nftStorageAuthToken": null,
"shdwStorageAccount": null,
"pinataConfig": null,
"hiddenSettings": null,
"guards": {
"default": {
"solPayment": {
"value": 0.01,
"destination": "YOUR_WALLET_ADDRESS"
},
"startDate": {
"date": "2022-10-23T20:00:00Z"
}
}
}
}
Make sure to replace YOUR_WALLET_ADDRESS with the wallet address you created earlier.
NOTA: puedes ejecutar «solana address» en tu terminal para obtener la dirección del monedero que acabas de crear.
Now, we should be all set. If you're following along to this point, you should have a directory structure like this:
sugar-demo/
├── wallet.json
├── config.json
└── assets/
├── [0-9].png
├── [0-9].json
├── collection.png
└── collection.json
Sugar has a built-in validation tool that will let us check for errors before proceeding. In the terminal, run:
validar azúcar

Note: You may see a warning, "missing properties.category". This is fine as the attribute is not included in the Metaplex sample files.
¡Ya estamos en marcha! Buen trabajo. Vamos a construir nuestra máquina de caramelos.
Create a Candy Machine
Because we have set our RPC and wallet using Solana CLI and saved our assets y config.json to Sugar's default directories, our commands will be pretty simple!
Sube tus recursos
In your terminal, enter:
subida de azúcar
Deberías ver algo como esto:

Instalar una máquina expendedora de caramelos
In your terminal, enter:
sugar deploy
Deberías ver algo como esto:

If you get a "Blockhash not found" error, try rerunning the command.
Make sure to store the Candy Machine ID provided in your terminal locally. We will need this later.
Comprobar la máquina de golosinas
Let's make sure everything has worked as we'd expected. In your terminal, enter:
verificar el azúcar
Deberías ver algo como esto:

¡Buen trabajo!
Pon a prueba tu máquina de golosinas
Try minting an NFT using sugar. In your terminal, enter:
menta azucarada
Deberías ver algo como esto:

Add Your Candy Guards
By default, when you deploy your Candy Machine, only you can mint NFTs. You must implement candy guards to define the criteria by which others can mint your NFTs (e.g., start time, payment amount, payment token, whitelist tokens, etc.). Since we already defined our guards in our config.json, we can run the following:
sugar guard add

Excellent! Let's create a mint page to share this project with the world!
Crear un sitio de acuñación
For a speedy deployment, we will be using the Solana dApp Scaffold, a handy tool that includes a Next.JS app with Solana Wallet Adapter already integrated.
Clone the dApp Scaffold
From your project directory, in your terminal, enter:
git clone https://github.com/solana-labs/dapp-scaffold ./candy-machine-ui/
cd candy-machine-ui
Instalar las dependencias
Install the included dependencies. In your terminal, enter:
yarn
We will need a few additional metaplex packages to get our minting site up and running. In your terminal, enter:
yarn add @metaplex-foundation/mpl-candy-machine@alpha @metaplex-foundation/mpl-token-metadata@alpha @metaplex-foundation/mpl-toolbox @metaplex-foundation/umi @metaplex-foundation/umi-bundle-defaults @metaplex-foundation/umi-signer-wallet-adapters
Create a .env File
Create a file, .env in the candy-machine-ui folder:
echo > .env
Add the following values in the new .env file (replacing the values with your own):
NEXT_PUBLIC_RPC=<YOUR_QUICKNODE_URL>
NEXT_PUBLIC_CANDY_MACHINE_ID=<YOUR_CANDY_MACHINE_PUBKEY>
NEXT_PUBLIC_TREASURY=<YOUR_WALLET_ADDRESS>
If you don't remember your Candy Machine ID, you should be able to find it in cache.json in the program.candyMachine field.
With all that information plugged in, you can save the file.
Add Mint NFT Button
We must add a button to our minting site to allow users to mint an NFT. First, duplicate the RequestAirdrop component and rename it to CandyMint. In your terminal, copy the file by entering the following:
cp ./src/components/RequestAirdrop.tsx ./src/components/CandyMint.tsx
Open CandyMint.tsx and change the exported component name from RequestAirdrop a CandyMint. You should also change the text in the button from <span>Airdrop 1 </span> a <span>Mint NFT </span>.
Finally, let's update our constant declarations and clear the contents of the onClick function, so we have a clean slate to work with. Your file should look like this:
//...Default Imports (we will replace these later)
export const CandyMint: FC = () => {
// 👇 Update these constant declarations
const { connection } = useConnection();
const wallet = useWallet();
const { getUserSOLBalance } = useUserSOLBalanceStore();
// TODO - Create an Umi instance
// 👇 Update this onClick function
const onClick = useCallback(async () => {
if (!publicKey) {
console.log('error', 'Wallet not connected!');
notify({ type: 'error', message: 'error', description: 'Wallet not connected!' });
return;
}
// TODO - Add minting logic here
}, []);
return (
<div className="flex flex-row justify-center">
<div className="relative group items-center">
<div className="m-1 absolute -inset-0.5 bg-gradient-to-r from-indigo-500 to-fuchsia-500
rounded-lg blur opacity-20 group-hover:opacity-100 transition duration-1000 group-hover:duration-200 animate-tilt"></div>
<button
className="px-8 m-2 btn animate-pulse bg-gradient-to-br from-indigo-500 to-fuchsia-500 hover:from-white hover:to-purple-300 text-black"
onClick={onClick}
>
<span>Mint NFT </span>
</button>
</div>
</div>
);
};
We need to add the CandyMint component to our Home View. Open ./sugar-demo/candy-machine-ui/src/views/home/index.tsx and add the following import statement:
// Components
import { RequestAirdrop } from '../../components/RequestAirdrop';
// 👇 Add this line
import { CandyMint } from '../../components/CandyMint';
And add the CandyMint component to the HomeView component:
<RequestAirdrop />
{/* 👇 Add this line */}
<CandyMint />
Great job! You should now have a new button, but before we test it, we need to add mint functionality. Let's do that.
Add Mint Functionality
Return to ./sugar-demo/candy-machine-ui/src/components/CandyMint.tsx and replace the default imports with the following:
import { useConnection, useWallet } from '@solana/wallet-adapter-react';
import { FC, useCallback, useMemo } from 'react';
import { notify } from "../utils/notifications";
import useUserSOLBalanceStore from '../stores/useUserSOLBalanceStore';
import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
import { generateSigner, transactionBuilder, publicKey, some } from '@metaplex-foundation/umi';
import { fetchCandyMachine, mintV2, mplCandyMachine, safeFetchCandyGuard } from "@metaplex-foundation/mpl-candy-machine";
import { walletAdapterIdentity } from '@metaplex-foundation/umi-signer-wallet-adapters';
import { mplTokenMetadata } from '@metaplex-foundation/mpl-token-metadata';
import { setComputeUnitLimit } from '@metaplex-foundation/mpl-toolbox';
import { clusterApiUrl } from '@solana/web3.js';
import * as bs58 from 'bs58';
// These access the environment variables we defined in the .env file
const quicknodeEndpoint = process.env.NEXT_PUBLIC_RPC || clusterApiUrl('devnet');
const candyMachineAddress = publicKey(process.env.NEXT_PUBLIC_CANDY_MACHINE_ID);
const treasury = publicKey(process.env.NEXT_PUBLIC_TREASURY);
Create a Umi Instance
Let's create a memoized Umi instance using our Quicknode Endpoint and the mplCandyMachine and mplTokenMetadata plugins. We will use this to mint our NFTs. Replace // TODO - Create Umi instance con:
const umi = useMemo(() =>
createUmi(quicknodeEndpoint)
.use(walletAdapterIdentity(wallet))
.use(mplCandyMachine())
.use(mplTokenMetadata()),
[wallet, mplCandyMachine, walletAdapterIdentity, mplTokenMetadata, quicknodeEndpoint, createUmi]
);
This will create a Umi instance that uses our wallet connected via the wallet adapter, our Quicknode endpoint, and a couple of Metaplex plugins.
Add Minting Logic
Let's update our onClick function to mint an NFT using Umi's transaction builder. Replace the onClick function with the following code, and then we will walk through what is happening:
const onClick = useCallback(async () => {
if (!wallet.publicKey) {
console.log('error', 'Wallet not connected!');
notify({ type: 'error', message: 'error', description: 'Wallet not connected!' });
return;
}
// Fetch the Candy Machine.
const candyMachine = await fetchCandyMachine(
umi,
candyMachineAddress,
);
// Fetch the Candy Guard.
const candyGuard = await safeFetchCandyGuard(
umi,
candyMachine.mintAuthority,
);
try {
// Mint from the Candy Machine.
const nftMint = generateSigner(umi);
const transaction = await transactionBuilder()
.add(setComputeUnitLimit(umi, { units: 800_000 }))
.add(
mintV2(umi, {
candyMachine: candyMachine.publicKey,
candyGuard: candyGuard?.publicKey,
nftMint,
collectionMint: candyMachine.collectionMint,
collectionUpdateAuthority: candyMachine.authority,
mintArgs: {
solPayment: some({ destination: treasury }),
},
})
);
const { signature } = await transaction.sendAndConfirm(umi, {
confirm: { commitment: "confirmed" },
});
const txid = bs58.encode(signature);
console.log('success', `Mint successful! ${txid}`)
notify({ type: 'success', message: 'Mint successful!', txid });
getUserSOLBalance(wallet.publicKey, connection);
} catch (error: any) {
notify({ type: 'error', message: `Error minting!`, description: error?.message });
console.log('error', `Mint failed! ${error?.message}`);
}
}, [wallet, connection, getUserSOLBalance, umi, candyMachineAddress, treasury]);
Let's walk through what is happening here:
- First, we check to make sure the wallet is connected. If it is not, we notify the user and return.
- Next, we fetch the Candy Machine and Candy Guard using the
fetchCandyMachineysafeFetchCandyGuardfunctions from the mpl-candy-machine package. We need these for our minting transaction. - Next, we generate a signer using Umi's
generateSignerfunction. This will be used to mint our NFT. - Next, we create a transaction using Umi's
transactionBuilderfunction. This will be used to mint our NFT:
- We add a
setComputeUnitLimitinstruction to the transaction. This safety measure prevents the transaction from failing due to exceeding the compute unit limit. - We add a
mintV2instruction to the transaction. This is the instruction that will mint our NFT. We pass our umi instance and an object with the following properties:candyMachine: The candy machine's public key.candyGuard: The candy guard's public key.nftMint: The signer we generated earlier.collectionMint: The collection mint's public key.collectionUpdateAuthority: The collection update authority's public key.mintArgs: An object containing the mint arguments associated with your Candy Guard (this may be different depending on your Candy Guard). For thesolPaymentguard, we must pass thedestinoof the payment (the treasury's public key).
- We send the transaction and notify the user of the result. Note that umi returns transaction signatures as a Unit8Array, so we must encode it to base58 before displaying it to the user.
- Finally, we call
getUserSOLBalance(a store action built into the scaffold) to update the user's SOL balance.
Nice job! Our site should now be able to mint NFTs.
Mint an NFT
Now that we have added the minting logic, let's start and test the site. In your terminal, run the following:
yarn dev
Esto abrirá un navegador en localhost:3000, donde podrás conectar tu monedero y acuñar un NFT. Asegúrate de que tu monedero Phantom esté configurado en devnet y no en mainnet antes de continuar.
Necesitarás SOL de devnet en tu monedero Phantom para acuñar un NFT. Puedes utilizar la CLI de Solana para recibir un airdrop en tu monedero Phantom introduciendo este comando en tu terminal:
Airdrop de Solana 1 TU_DIRECCIÓN_DE_CARTERA_PHANTOM
Cuando estés listo, haz clic en «Mint». Si se ha realizado correctamente, deberías ver una página web como esta:

If you see an error that says “Mint Failed,” you might not have enough funds. Try again once you have added funds. You can view the NFT in your wallet after purchasing. Phantom may take a moment before rendering the NFT in your wallet. Ours looks like this:

¡Vaya, qué dulce! Buen trabajo.
Conclusión
Congrats! You created a Candy Machine using Metaplex Sugar and Umi. You now have all the tools needed to run your own NFT mint. We're excited to see what NFTs you're creating! Join us on Discord or reach out to us via Twitter to share your NFT project.
¡Nos encanta recibir comentarios!
Si tienes algún comentario o sugerencia sobre nuevos temas, no dudes en hacérnoslo saber. Nos encantaría saber tu opinión.
