Перейти к содержимому

Candy machine nft как пользоваться

  • автор:

How to mint an NFT using Candy Machine V2 [includes code]

Scripts and code to make you a pro ape NFT maker in the Solana ecosystem

Shivek Khurana ��

In this tutorial, we will mint NFTs on Solana using the Candy Machine v0.0.2.

Prerequisites

Minting an NFT is the process of creating a token, freezing its maximum supply to 1 and attaching Metaplex NFT standard JSON to it, so a wallet can render it. This process requires you to have:

  • some understanding of bash scripts, and a terminal
  • some knowledge of Git and Node
  • Solana CLI tools [installation guide]

End results

By the end of this tutorial, you will have 5 NFTs on the Solana devnet and a website to run a sale. We will also add a script to mint NFTs to your wallet via the CLI.

The cover image of this article was created using graphics from Candy Machine Vectors by Vecteezy and Monkeys Vector by Brgfx on Freepik.

Step 1: Prep your images

We are going to build an upgradable NFT project on top of the Meta Blocks protocol. We have created these 5 images that can be joined together. This collection will be called "Tara".

true

You use this guide, even if don't plan to be upgradable via Meta Blocks protocol. The process for minting a Meta Blocks compatible collection is the same as minting a normal NFT collection.

You can download these images here.

Step 2: Setup Metaplex locally

Metaplex offers a suite of tools and smart contracts (programs) that will ease the process of creating NFTs. We will use the official CLI to mint our collection.

Step 2.1: Pull CLI from Github

Open the terminal app on your computer. cd into a directory where you want to store the Metaplex related code. In my case this will be

/Desktop . Then clone the repository:

You should see the following files in the newly created metaplex folder:

true

Screenshot of the files inside the Metaplex folder

Step 2.2: Build Metaplex CLI code

We have the code but it's not usable yet. We need to fetch its dependancies and compile it. The Metaplex package comes with multiple packages, but we only care about cli . To do this, goto the js/packages/cli folder inside metaplex , and execute the following commands:

This will create a folder named build in the cli folder. If you run node ./build/candy-machine-v2-cli.js , you should see the following output:

true

Successfully built Candy Machine CLI output

Step 3: Prep Metaplex NFT config

Each asset (image/video etc) that you want to publish as an NFT needs an accompanying Metaplex config. This config is built to comply with Metaplex's Token Metadata Standard. In less technical terms, Metaplex designed a standard that to store NFTs on Solana, an everyone in the ecosystem adopted the standard.

From the point of view of the creator, you can think of this config as a way to specify the attributes, commissions and aspects of your NFT.

Since we have five assets, we need five configuration files. According to Metaplex, the numbering of the files start at 0. So for our 5 NFTs in the "Tara" collection, we will have the following files (total 10):

  • 0.png, 0.json for Tara Base
  • 1.png, 1.json for Tara Right Blue
  • 2.png, 2.json for Tara Right Red
  • 3.png, 3.json for Tara Top Green and
  • 4.png , 4.json for Tara Top Purple

Step 3.1: Create a folder for Tara project

We will create two folders called tara and tara/assets in metaplex/js/packages/cli :

assets folder stores on-chain assets and the tara folder will be used to store keys and config. This is just our personal preference. These folder names can be anything.

Step 3.2: Move 5 "Tara" images to the tara/assets folder

Make sure that you name then 0.png , 1.png and so on.

Step 3.3: Create the file 0.json for the first NFT

This file will have the following content:

In this configuration:

  • You can add as many attributes as you want in attributes array
  • Alternate file types (like video) in the files array
  • For additional files, make sure you use the correct files.type
  • The royalty you get per trade in seller_fee_basis_points (1000 basis = 10% royalty, 10000 basis = 100% royalty)
  • Add your wallet address in creators.address
  • If there are multiple creators, you can specify the share split of royalties
  • Share = 100 signifies that 100% of the royalties for goto this creator

Step 3.4: Create configuration for all NFTs

You can create a script to generate the configuration for you. If you are following along with the example, you can find the 5 json files and images here.

After this, your assets are ready (assuming you didn't make any typos). The next step is to prepare the candy machine.

Step 4: Prep Candy Machine Config

The candy machine config lets you set the price, mint date and other attributes of the collection. To configure this, create a file called config.json in js/packages/tara :

The important keys to change are:

  • price : price of each NFT in SOL
  • solTreasuryAccount : public address that receives the funds from sales

To get more info about each key value pair, refer to the official Metaplex documen at https://docs.metaplex.com/candy-machine-v2/configuration

Step 5: Generate a keypair for uploading these assets

We need a Solana wallet to make contract calls to create these NFTs. Let's create one in js/packages/cli/tara :

We are working on the devnet at the moment, so make sure that your network is set to devnet

Finally, you need some SOL to pay gas. You can request some using airdrop:

The above command will give an output similar to:

It's a good idea to test your collection on Devnet first. When done, you can change the network to Mainnet-Beta.

Step 6: Upload the assets

In the js/packages/cli/tara directory, run the following command to upload the assets to Arweave:

On successful completion, you will get an output that looks like this:

Take a not of the candy machine public key. For us, it is AuuLoYV9kx8HKWrpnJCT5whgURqd5MwxckWesL5arqh

At this point, you can check the .cache folder to see the urls of the NFTs on Arweave.

If the command fails, you can run it again. The command is smart enough to resume uploads. If you are uploading a lot of images, you might need more than 2 SOL.

NOTE: If you are not able to upload at all, you can try to clear the cache and try again. The cache folder is hidden and called .cache

Step 7: Verify uploads (optional)

To ensure that the upload process, you can run the verify command as follows:

It's recommended to run the verify command, but it's possible that you like taking risks. Maybe you live life on the edge. In that case you can skip this step.

Step 8: Choose a delivery mechanism

At this point, your NFTs are ready on the chain. Now you can decide to:

  • Mint them to your wallet via the command line or
  • Generate a candy machine website where users can mint their own

The advantage of the latter approach is that the gas fee of the mint is paid by the user.

If you decide to create a website, you can follow the steps outlined here: https://docs.metaplex.com/candy-machine-v2/mint-frontend. The value of the variable REACT_APP_CANDY_MACHINE_PROGRAM_ID is the public key of the candy machine computed in Step 6 (AuuLoYV9kx8HKWrpnJCT5whgURqd5MwxckWesL5arqh).

If you decide to mint the NFTs to your own wallet, you can do it via the CLI:

The above command will try to mint 5 NFTs by reading the taracache . This cache was created in the upload process. You can pass any number in place of 5.

The NFTs will be stored in the wallet related to keypair.json . You can add this keypair to Phantom to check the NFTs.

A successful output will look something like:

After running this command, you should see 5 NFTs in your wallet. Make sure you switch the network to devnet:

true

NFTs show up in Slope wallet

Next steps

Now you have minted your awesome NFT collection. You can sell them, build a community around them, or keep them in your wallet forever.

If you are building a richer application, or want NFTs that can upgrade overtime, checkout the Meta Blocks protocol.

От идеи создания NFT до опустошения Candy Machine

Давным давно в 2020 г. когда я только познавал мир крипты и параллельно торговал на фондовом рынке, я состоял в открытой группе где сидели как и трейдера с стажем, так и такие новички как и я.

В данной группе мне сказали что создавай своё комьюнити, или хотя-бы найди пару человек что-бы иметь больше информации, распределять обязанности. В тот момент я видел свое комьюнити так:

Два-три человека сидят, отбирают стаки для торговли внутри дня, каждому отведено определенной сектор или же, по своим скринерам.

За пару часов до начала торговой сессии все созваниваются и обсуждают какие стаки торговать, а какие нет.

Ну и ходил я с этой идеей очень долго. Потом, когда я уже погрузился с головой в крипту понял что без команды ты никто (Только если ты не торгуешь внутри дня), ведь когда ты понимаешь что хочешь зарабатывать в крипте то ты должен как минимум знать «все» , и захватывать все сферы

Ну а далее время шло и я все продумывал как же организовать это всё

И когда я уже более менее стал стоять на своих двух я понял что лучшего времени не будет, и без каких либо уменний в рисовании и знаний программирования (Хотя я уже изучал Python, и HTML но до конца я так и не дошёл — поэтому базовые знания были) я приступил к реализации проекта…

Зима 2021 — 2022 г.

Возможно вы застали то время, когда стреляли почти-что все коллекции НФТ, многие тогда фармили WL и после чего лутали десятки иксов, и многие коллекции предлагали держателем доступ в DAO, но это было сложно назвать DAO ведь в большинстве случаев вы получали неликвидную НФТ, и грустное комьюнити которое пришло флипануть данную коллекцию, и не более. (Но есть и те кто реализовал все на высшем уровне — их можно пересчитать на пальцах)

В таких DAO люди не получали право голоса где всех просто ставили в известность постфактум

И тогда уже зародилась идея создание своей коллекции, конечно хотелось заскамить кого-то но я понимал что лучше сделать все правильно и красиво, и не залутать десятки тысяч вечно зеленых, а собрать комьюнити. На тот момент в паблике было всего-лишь 150-500 человек и я понимал что если сейчас это все делать то

  • Не наберу свою аудиторию
  • Выпаду из рынка на месяц, и пропущу всю активность с НФТ

Поэтому я стал просто искать инфу как создать свою коллекцию, и готовится к создание коллекции.

Данная НФТ дает доступ в наше закрытое DAO

В апреле 2022 года — я уже начал делать исходники для коллекции

  • Это были бейджи, которые я перерисовывал в Photoshop неделями, но так и не зашло мне это
  • Потом я вспомнил про коллекцию Portals — их коллекция в виде банковской карты, и начал кидать исходники, но тоже понял что это не то что я хотел увидеть
  • Персонажи, сначала начал с идеи персонажа, первые на ум пришли нинзя, но они за один день отвалились, и тут я увидел его странное сушество, немного посидев в Photoshop я отрисовал первого Гуманоида

Сложность была в моих кривых руках, и все что я не рисовал выходило мягко сказать говном, и в один прекрасный день родился мой первый Гуманоид

Конечно в первом варианте он был убожеством, но уже с отрисованным телом, если у него оно вообще есть)

И далее на основе этого тела я отрисовал

Humanoid — 11 разных гуманоидов, 7 из них похожие по форме, 4 залитых градиентом, и эксклюзив 9 отрисованные полностью с нуля — т.е без генерации

Background — 17 фонов скаченных из интернета с бесплатной лицензией, но не все фоны были скачаны, многие это просто градиент, и один это первая сгенерированная коллекция в размытом виде

Eyes — 5 обычных глаз, и одни в виде Thug очков

Teeth — 6 видов зубов, которые в день генерации нфт в основную сеть были перерисованными ибо они не попадали под гуманоида

Вот так и появились исходники для генерации моей первой НФТ коллекции

Выше вы уже узнали что данная коллекция рисовалась в Photoshop

Все исходники были в формате 2000х2000

Сначала сохранял гуманоидов, а после каждый отдельный атрибут, и далее стал вопрос о генерации нфт с метаданными

Прочитав документации по Ethereum и Solana выбор пал на Solana.

Узнал что все можно сделать без каких-либо знаний, я приступил к генерации нфт.

В данном случае я использовал Hashlips Art Engine — это открытый исходник для генерации нфт

Прочитав их инструкцию я сделал все по шагам, и первая коллекция сгенерирована!

  • Linux — но не обязательно, можно все сделать и в Windows — для удобного редактирования кода

И библиотеки для генерации колекции

Видео гайды есть на этом youtube канале

Ну тут все просто

  • Быстрота блокчейна
  • Дешевые комиссии
  • Не требуется создавать Смарт контракты как в Ethereum

Деплой коллекции происходил через Metaplex

Что мне для этого понадобилось?

    — Для создания кошелька — Основной инструмент деплоя нфт коллекции

Тут все так-же было по детальной инструкции

Да на заметку, опустошать Candy Machine надо после того как: Все НФТ были отчеканены, и не раньше!

Первый анонс своей коллекции был сделан 03.06.2022 в данном посте , т.е от создания первого гуманоида — 16.05 прошло 17 дней!

И уже 03.06 был создан сайт для минта — исходник лежит на github

Сайт был создан очень быстро, был взят исходник, сделал сверху удобное меню, добавил кривой блок с информацией, и в тот же день были отчеканены первые WL НФТ

Далее, я протестировал сайт, он работал нормально, только вот столкнулся с проблемой в виде минта для WL, я создал обычный токен, и данный сайт все не как не хотел брать 1 токен, а брал 0.000000001, перерыв все я понял что проблема была в сайте.

Решил я данную проблему созданием нового WL токена только уже в виде НФТ, и о чудо он берёт 1 нфт и соляну для минта

Определился с датой минта — 07.06.2022, я отправил свою коллекцию в НФТ календари, по итогу только один календарь разместил мою коллекцию.

NFTCALENDAR, а условия разрешения были очень простыми — поставить их баннер у себя на сайте, и сделать превью для своей коллекции

Я сразу ожидал что будет отчеканено не более 5-10 шт.

— Но вы спросите зачем такая большая коллекция?

А ответ будет простым — просто захотел, ибо дальше данная NFT возможно будет сжигаться, для разного рода наград.

В первый час отчеканили почти все кто хотел, далее я просто ждал окончания минта — 08.06.2022.

В день окончания также были отчеканены 1-2 НФТ.

После окончания минта, я сминтил остальные нфт, и принялся за финальные действия…

Коллекция сминчена на 100%, иду подписывать все нфт, и столкнулся с проблемой соль в тот момент не очень быстро работала, и две подряд транзакции у меня идут с фейл, хотя если бы я сразу все чекнул в Exploler то я бы не потратил много времени на эту ошибку

Далее я выдохнув, что это не ошибка и пошёл листится на все маркетплейсы

OpenSea — самый лучший маркетплейс, листинг моментальный

Magic Eden — тут возникла проблема, хотя я так и нечего не понял — Команда отклонила ваш листинг) — но в конце концов коллекция на Magic Eden

Ну и далее я опустошаю Candy Machine на которой лежало 0.2 SOL, и всё данная коллекция была официально запушена

How to Mint NFTs with Solana's CandyMachine V2

If you have used the Solana Candy Machine V1 protocol, using V2 will be far easier to you. If you have never used either before, then this tutorial will help you to do so. It's pretty straightforward and we have you covered.

To get started, we must install the following dependencies to create your NFT’s:

Once installed, you must then install the Phantom Wallet extension. If you are familiar with MetaMask, Phantom is similar but used for Solana’s network. After installing the wallet you must create an account and save the 12 word seed in a secure location.

Once in the wallet, you must change the Solana’s Mainnet to Devnet. This is because to operate in Mainnet, we would need to spend some Sol’s. But, in Devnet, we can fund our wallet with some fictional Sol’s (these Sol’s don't have real value, so trying to use them will have no effect, nice try though).

Solana Wallet

To do this, go to settings, as the image above shows, and scroll down until you see the following:

Change Network

After selecting 'Change Network', Then, select the Devnet option. FYI — you would need to send some Sol to your phantom address to avoid problems when we are ready to Mint. You can get Sol’s to do this from the following faucet.

You are now ready to start coding. To get started, go to the following repository and clone it.

Before we interact with the cloned repository, first we need to do some configurations using the Solana CLI. We should open a terminal to start interacting.

(I highly recommend having a document to save important information for interacting with Solana’s CLI, and later with the Candy Machine Protocol.)

Step 1: Configurate work space

The very first step is to create a folder for our project: mkdir solana-nft and we are going to step into that folder.

Then, you will need to configure the CLI to work on Solana’s Devnet instead of Mainnet, so we should throw this command — $ solana config set. You should receive something like:

The terminal should then respond with something like:

Config File: /Users/tomi/.config/solana/cli/config.yml

RPC URL: https://api.devnet.solana.com

WebSocket URL: wss://api.devnet.solana.com/ (computed)

Keypair Path: /Users/tomi/.config/solana/devnet.json Commitment: confirmed

If you see that you are not on the Devnet, whit this command you could switch from Mainnet to Devnet: $ solana config set —url https://api.devnet.solana.com

And with this command $ solana config get you can get the configuration settings to verify if you are connected to the Devnet.

The next step is creating a wallet for this project using — $ solana-keygen newoutfile

After doing this, the Solana CLI would ask you for a password, put whatever password you like. In my case I would leave an empty space because we are using the Devnet and there is any risk of losing real money.

We should receive something like:

Wrote new keypair to /Users/tomi/solana-nft/key.json

Save this seed phrase and your BIP39 passphrase to recover your new keypair:

NEVER REVEAL YOUR 12 WORD SEED PHRASE

Please write your pubkey in the document.

Then, we should set that key as our predetermined key. In order to reach this, we sould throw this command: $ solana config set —keypair

To verify that we set correctly the pubkey we can use the following command: $ solana address, and we should receive the same address as the one that we wrote on our document.

With this command, we are going to magically airdrop some funds in our address:

$ solana airdrop 5. This should respond with the following:

Signature: 2y7p5wchXuyGtKPHCEchTJ63dU6PKuvMFdoVCwiELAsHCG6Zx3fZDbn3PyGn4X9THmCpevS7j6VDmdVtebAAZFyv

5 SOLIf you are asked with $ solana balance you should receive a response of 5 sols.

Step 2: Use the Metaplex repository

First of all, we should clone this Metaplex repository into our solana-nft folder with $ git clone https://github.com/metaplex-foundation/metaplex/

After cloning that repository we should install it’s dependencies, thats why we should throw the following command with yarn: $ yarn install -cwd

If you are using Windows you can install Metaplex dependencies if you stand over the js folder or writing the whole path.

The installation should take a couple of minutes.

We can test that the installation was successful looking for the version of the Candy-Machine. We should use: $ ts-node

The next step is to create a config.json file, you can find the specifications in the Metaplex documentation. I recommend that for this learning instance we should use the minimal configuration.

So in our folder wi should create the file with: $ touch config.json and then we copy and paste the minimal configuration provided by Metaplex foundation.

For this learning stage I we should only change the “SolTreasuryAccount” and put our pubkey where it says <’YOUR WALLET ADDRESS’> and also the “goLiveDate” with the date and hour that you want your collection to be mintable.

Last but not least, change the “arweave-sol” with “arveave”, this in order to let the storage of our collection can endure in time in the Devnet.

Something like this will work:

Metaplex repository

Step 3: The assets

In the Candy Machine V2 is quite the same as in the Candy Machine V1. We should create a 1-1 mapping between the PNG images and its metadata in the form of a JSON file.

In the folder called solana-nft we should create another folder called “assets” and inside there we are going to create the 1 on 1 mapping.

It should look like this:

Solana assets

In the JSON files you should use the Metaplex uri schema that you can find in the following Medium post.

Please remember to use your pubkey address in the section of the JSON schema called address.

Now it is the time of truth. We are going to upload our Candy Machine with the assets ��.

For doing this we should use the following command:

$ npx ts-node

-e devnet \

It should take a little and you should receive a response in where you will find the Candy Machine Address, please save it in your important info paper.

If you want to verify that everything is ok, you can use the following command:

$ npx ts-node

-e devnet \

-c example

Step 4: Minting Website

This may be the easiest step.

We only need to move inside the Metaplex directory and go to solana-nft/metaplex/js/packages/candy-machine-ui

There we should select the .env.example file and rename it to .env.

Inside the file we should put our Candy Machine address here:

Put your Candy Machine address here

And then in the console you should use the following commands:

$ yarn install

$ yarn build

After the build, automatically the browser will open in the local host and you will see a minting button.

Solana minting button

If you click it, your Phantom wallet will open and will ask you to sign the transaction, you can approve it, and in a couple of minutes you will see your NFT in the wallet.

Candy Machine Settings

On this page, we’re going to dig into all the settings available on a Candy Machine. We will focus on settings that affect the Candy Machine itself and the NFTs it generates rather than the settings that affect the minting process known as Guards. We will tackle the latter in dedicated pages.

The authority​

One of the most important pieces of information when creating accounts on Solana is the wallet that is allowed to manage them, known as the Authority. Thus, when creating a new Candy Machine, you will need to provide the address of the authority that will, later on, be able to update it, insert items to it, delete it, etc.

There is an additional authority specifically for the minting process called the Mint Authority. When a Candy Machine is created without a Candy Guard, this authority is the only wallet that is allowed to mint from the Candy Machine. No one else can mint. However, in practice, this mint authority is set to the address of a Candy Guard which controls the minting process based on some preconfigured sets of rules known as guards.

It is important to note that, when using our SDKs, Candy Machines will always be created with an associated Candy Guard by default so you do not need to worry about this mint authority.

JavaScript — Umi library (recommended)

When creating a new Candy Machine, the authority will default to the Umi identity. You may explicitly set this authority by providing a valid signer to the authority property.

When using the JS SDK, the authority of a Candy Machine will always default to the current identity. You may explicitly set this authority by providing a valid signer to the authority property.

Settings shared by all NFTs​

A big chunk of the Candy Machine settings is used to define the NFTs that will be minted from them. This is because many of the NFT attributes will be the same for all minted NFTs. Therefore, instead of having to repeat these attributes every time we load an item in the Candy Machine, we set them up once on the Candy Machine settings.

Note that the only attributes that can distinguish one minted NFT from another are the Name of the NFT and the URI pointing to its JSON metadata. See Inserting Items for more information.

Here is the list of attributes shared between all minted NFTs.

  • Seller Fee Basis Points: The secondary sale royalties that should be set on minted NFTs in basis points. For instance 250 means 2.50% royalties.
  • Symbol: The symbol to use on minted NFTs — e.g. "MYPROJECT". This can be any text up to 10 characters and can be made optional by providing an empty text.
  • Max Edition Supply: The maximum number of editions that can be printed from the minted NFTs. For most use cases, you will want to set this to 0 to prevent minted NFTs to be printed multiple times. Note that you cannot set this to null which means unlimited editions are not supported in Candy Machines.
  • Is Mutable: Whether the minted NFTs should be mutable or not. We recommend setting this to true unless you have a specific reason. You can always make NFTs immutable in the future but you cannot make immutable NFTs mutable ever again.
  • Creators: A list of creators that should be set on minted NFTs. It includes their address and their shares of the royalties in percent — i.e. 5 is 5% . Note that the Candy Machine address will always be set as the first creator of all minted NFTs and will automatically be verified. This makes it possible for anyone to verify that an NFT was minted from a trusted Candy Machine. All other provided creators will be set after that and will need to be verified manually by these creators.
  • Token Standard: The token standard to use on minted NFTs. So far only two token standards are supported: "NonFungible)" and "ProgrammableNonFungible". Note that this is only available for Candy Machines whose account version is 2 and above.
  • Rule Set: If a candy machine uses the "ProgrammableNonFungible" token standard, it can provide an explicit rule set that will be assigned to every minted programmable NFT. If no rule set is provided, it will default to using the rule set on the collection NFT, if any. Otherwise programmable NFTs will be minted without a rule set. Note that this is only available for Candy Machines whose account version is 2 and above.

JavaScript — Umi library (recommended)

From the attributes listed above, only the sellerFeeBasisPoints , creators and tokenStandard attributes are required. The other attributes have the following default values:

  • symbol defaults to an empty string — i.e. minted NFTs don’t use symbols.
  • maxEditionSupply defaults to zero — i.e. minted NFTs are not printable.
  • isMutable defaults to true .

You may explicitly provide any of these attributes like so.

The JS SDK is only compatible with Candy Machine V3 accounts whose account version is 1. That means, it does not support minting programmable NFTs and it is not compatible with Candy Machines created with the latest version of Sugar.

You may consider using the Umi library instead which supports all account versions of Candy Machine V3. Alternatively, you may downgrade you Sugar version to 2.0.0 or use the Solita-generated library.

See Programmable NFTs for more details.

When creating a Candy Machine, only the sellerFeeBasisPoints attribute is required out of the attributes listed above. The other attributes have the following default values:

  • symbol defaults to an empty string — i.e. minted NFTs don’t use symbols.
  • maxEditionSupply defaults to zero — i.e. minted NFTs are not printable.
  • isMutable defaults to true .
  • creators defaults to the current identity with 100% of the shares.

You may explicitly provide any of these attributes like so.

Metaplex Certified Collections​

Each Candy Machine must be associated with a special NFT known as a Metaplex Certified Collection (MCC). This Collection NFT enables minted NFTs to be grouped together and for that information to be verified on-chain.

To ensure no one else can use your Collection NFT on their Candy Machine, the Collection's Update Authority is required to sign any transaction that changes the Collection on a Candy Machine. As a result, the Candy Machine can safely verify the Collection of all minted NFTs automatically.

JavaScript — Umi library (recommended)

When creating a new candy machine or when updating its collection NFT, you will need to provide the following attributes:

  • collectionMint : The address of the mint account of the Collection NFT.
  • collectionUpdateAuthority : The update authority of the Collection NFT as a signer.

Here’s an example.

When creating a new Candy Machine or updating the collection of a Candy Machine, you will need to provide the collection attribute as an object containing the following properties:

  • address : The address of the mint account of the Collection NFT.
  • updateAuthority : The update authority of the Collection NFT as a signer.

Here’s an example.

Item Settings​

Candy Machine settings also contain information regarding the items that are or will be loaded inside it. The Items Available attribute falls in that category and stores the maximum amount of NFTs that will be minted from the Candy Machine.

JavaScript — Umi library (recommended)

When creating a new Candy Machine, the itemsAvailable attribute is required and may be a number or a native bigint for large integers.

When creating a new Candy Machine, the itemsAvailable attribute is required and must be passed like so.

On top of the Items Available attribute, two other attributes define how items are loaded in the Candy Machine. You must choose exactly one of these attributes and leave the other one empty. These attributes are:

  • The Config Line Settings.
  • The Hidden Settings.

Note that once a Candy Machine is created using one of these two modes, it cannot be updated to use the other mode. Additionally, when Config Line Settings are used, it is no longer possible to update the Items Available attribute.

Let’s go through both of them in a bit more detail.

Config Line Settings​

The Config Line Settings attribute allows us to describe the items that are or will be inserted inside our Candy Machine. It enables us to keep the size of the Candy Machine to a minimum by providing exact lengths for the Names and URIs of our items as well as providing some shared prefixes to reduce that length. The Config Line Settings attribute is an object containing the following properties:

  • Name Prefix: A name prefix shared by all inserted items. This prefix can have a maximum of 32 characters.
  • Name Length: The maximum length for the name of each inserted item excluding the name prefix.
  • URI Prefix: A URI prefix shared by all inserted items. This prefix can have a maximum of 200 characters.
  • URI Length: The maximum length for the URI of each inserted item excluding the URI prefix.
  • Is Sequential: Indicates whether to mint NFTs sequentially — true — or in random order — false . We recommend setting this to false to prevent buyers from predicting which NFT will be minted next. Note that our SDKs will default to using Config Line Settings with Is Sequential set to false when creating new Candy Machines.

To understand these Name and URI properties a bit better, let’s go through an example. Say you want to create a Candy Machine with the following characteristics:

  • It contains 1000 items.
  • The name of each item is “My NFT Project #X” where X is the item’s index starting from 1.
  • Each item’s JSON metadata has been uploaded to Arweave so their URIs start with “https://arweave.net/” and finish with a unique identifier with a maximum length of 43 characters.

In this example, without prefixes, we would end up with:

  • Name Length = 20. 16 characters for “My NFT Project #” and 4 characters for the highest number which is “1000”.
  • URI Length = 63. 20 characters for “https://arweave.net/” and 43 characters for the unique identifier.

When inserting 1000 items, that’s a total of 83’000 characters that will be required just for storing items. However, if we use prefixes, we can significantly reduce the space needed to create our Candy Machine and, therefore, the cost of creating it on the blockchain.

  • Name Prefix = “My NFT Project #”
  • Name Length = 4
  • URI Prefix = “https://arweave.net/”
  • URI Length = 43

With 1000 items, we now only need 47’000 characters to store our items.

But that’s not it! You may use two special variables within your name or URI prefixes to reduce that size even further. These variables are:

  • $ID$ : This will be replaced by the index of the item starting at 0.
  • $ID+1$ : This will be replaced by the index of the item starting at 1.

In our above example, we could leverage the $ID+1$ variable for the name prefix so we wouldn’t need to insert it on every item. We end up with the following Config Line Settings:

  • Name Prefix = “My NFT Project #$ID+1$”
  • Name Length = 0
  • URI Prefix = “https://arweave.net/”
  • URI Length = 43

That’s right, our name length is now zero and we’ve reduced the characters needed down to 43’000 characters.

JavaScript — Umi library (recommended)

When using Umi, you can use the some and none helper functions to tell the library whether to use Config Line Settings or Hidden Settings via the configLineSettings and hiddenSettings attributes respectively. Only one of these settings must be used, thus, one of them must be configured and the other one must be set to none() .

Here’s a code snippet showing how you can set up the above example using the Umi library.

When using the JS SDK, both Config Line Settings and Hidden Settings live under the same object attribute called itemSettings . It contains a type property used to distinguish the two modes. This ensures exactly one of these settings is used on a Candy Machine.

  • When type is equal to "configLines" , Config Line Settings are used.
  • When type is equal to "hidden" , Hidden Settings are used.

Here’s a code snippet showing how you can set up the above example using the SDK.

Hidden Settings​

Another way of preparing items is by using Hidden Settings. This is a completely different approach than Config Line Settings as, using Hidden Settings, you do not need to insert any items to the Candy Machine as every single minted NFT will share the same name and the same URI. You might be wondering: why would someone want to do that? The reason for that is to create a hide-and-reveal NFT drop that reveals all NFTs after they have been minted. So how does that work?

  • First, the creator configures the name and the URI of every minted NFTs using the Hidden Settings. The URI usually points to a “teaser” JSON metadata that makes it clear that a reveal is about to happen.
  • Then, buyers mint all these NFTs with the same URI and therefore the same “teaser” JSON metadata.
  • Finally, when all NFTs have been minted, the creator updates the URI of every single minted NFT to point to the real URI which is specific to that NFT.

The issue with that last step is that it allows creators to mess with which buyer gets which NFTs. To avoid that and allow buyers to verify the mapping between NFTs and JSON metadata was not tampered with, the Hidden Settings contains a Hash property which should be filled with a 32-character hash of the file that maps NFT indices with their real JSON metadata. That way, after the reveal, the creator can make that file public and buyers and verify that its hash corresponds to the hash provided in the Hidden Settings.

Therefore, we end up with the following properties on the Hidden Settings attribute:

  • Name: The “hidden” name for all minted NFTs. This can have a maximum of 32 characters.
  • URI: The “hidden” URI for all minted NFTs. This can have a maximum of 200 characters.
  • Hash: The 32-character hash of the file that maps NFT indices with their real JSON metadata allowing buyers to verify it was not tampered with.

Note that, just like for the prefixes of the Config Line Settings, special variables can be used for the Name and URI of the Hidden Settings. As a reminder, these variables are:

  • $ID$ : This will be replaced by the index of the minted NFT starting at 0.
  • $ID+1$ : This will be replaced by the index of the minted NFT starting at 1.

Also note that, since we are not inserting any item to the Candy Machine, Hidden Settings make it possible to create very large drops. The only caveat is that there is a need for an off-chain process to update the name and URI of each NFT after the mint.

JavaScript — Umi library (recommended)

When using Umi, you can use the some and none helper functions to tell the library whether to use Config Line Settings or Hidden Settings via the configLineSettings and hiddenSettings attributes respectively. Only one of these settings must be used, thus, one of them must be configured and the other one must be set to none() .

Here’s a code snippet showing how you can set up the above example using the Umi library.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *