Candy machine nft как пользоваться
Перейти к содержимому

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

  • автор:

От идеи создания 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
  • Visual Studio Code — для удобного редактирования кода

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

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

Почему Solana?

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

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

Как деплоил нфт?

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

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

  • Solana-cli — Для создания кошелька
  • 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 НФТ.

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

Опустошение Candy Machine и выход на маркетплейс

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

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

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

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

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

Вот такая получилась статья, возможно она вам поможет!

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

Candy Machine, разработанный Metaplex Studios, представляет собой программу для продажи NFT на блокчейне Solana. Используя интерфейс командной строки Metaplex (CLI), пользователи могут генерировать NFT и настраивать аукционы.

Отличия между Candy Machine v1 и v2

Candy Machine v2 предлагает ряд улучшений по сравнению с предыдущей версией. Он вводит непредсказуемый индекс монетизации, настройки Captcha для ограничения атак ботов, возможность создания белых списков для предварительной продажи и эксклюзивного монетизации, а также поддержку больших коллекций и скрытых выпусков.

Как использовать Candy Machine NFT?

Для успешного использования Candy Machine NFT следует выполнить следующие шаги:

  1. Установите необходимые инструменты и настройте кошелек Solana.
  2. Настройте Candy Machine, подготовьте ваши NFT.
  3. Разверните Candy Machine, начните монетизацию токенов и подпишите монетизацию.
  4. Настройте веб-сайт для продажи ваших NFT.

Candy Machine и Metaplex

Metaplex Protocol Candy Machine является ведущей программой для монетизации и распределения NFT на Solana. Это позволяет создателям безопасно и настраиваемо приводить свои цифровые активы на блокчейн.

FAQ:

  • Что такое candy machine на Solana? Это программа, разработанная Metaplex Studios, для продажи NFT на блокчейне Solana.
  • Что такое крипто candy machine? Это инструмент для монетизации и продажи NFT на блокчейне.
  • Что такое Candy Machine v3? На данный момент информации о версии v3 нет.
  • Что такое Candy Machine v2? Это улучшенная версия Candy Machine с дополнительными функциями и возможностями.

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.

Set up the authority
JavaScript

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.

import  generateSigner > from '@metaplex-foundation/umi' const myCustomAuthority = generateSigner(umi) const candyMachineSettings =   authority: myCustomAuthority, > 

Settings shared by all 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.

Set up shared NFT settings

JavaScript

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.

import  percentAmount, generateSigner, some > from '@metaplex-foundation/umi' import  TokenStandard > from '@metaplex-foundation/mpl-token-metadata' const creatorA = generateSigner(umi).publicKey const creatorB = generateSigner(umi).publicKey const candyMachineSettings =   tokenStandard: TokenStandard.NonFungible, sellerFeeBasisPoints: percentAmount(33.3, 2), symbol: 'MYPROJECT', maxEditionSupply: 0, isMutable: true, creators: [  address: creatorA, percentageShare: 50, verified: false >,  address: creatorB, percentageShare: 50, verified: false >, ], > 

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.

Set up the collection NFT

JavaScript

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.

import  generateSigner, percentAmount > from '@metaplex-foundation/umi' import  createNft > from '@metaplex-foundation/mpl-token-metadata' // Create the Collection NFT. const collectionUpdateAuthority = generateSigner(umi) const collectionMint = generateSigner(umi) await createNft(umi,   mint: collectionMint, authority: collectionUpdateAuthority, name: 'My Collection NFT', uri: 'https://example.com/path/to/some/json/metadata.json', sellerFeeBasisPoints: percentAmount(9.99, 2), // 9.99% isCollection: true, >).sendAndConfirm(umi) // Pass the collection address and its authority in the settings. const candyMachineSettings =   collectionMint: collectionMint.publicKey, collectionUpdateAuthority, > 

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.

Set up the number of items

JavaScript

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

const candyMachineSettings =   itemsAvailable: 500, > 

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:

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.

Set up config line settings

JavaScript

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.

import  some, none > from '@metaplex-foundation/umi' const candyMachineSettings =   hiddenSettings: none(), configLineSettings: some(  prefixName: 'My NFT Project #$ID+1$', nameLength: 0, prefixUri: 'https://arweave.net/', uriLength: 43, isSequential: false, >), > 

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.

Set up hidden settings

JavaScript

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.

import  some, none > from '@metaplex-foundation/umi' const candyMachineSettings =   configLineSettings: none(), hiddenSettings: some(  name: 'My NFT Project #$ID+1$', uri: 'https://example.com/path/to/teaser.json', hash: hashOfTheFileThatMapsUris, >), > 

Guards and Groups

As mentioned in the introduction, this page focuses on the main Candy Machine settings but there is a lot more you can configure on a Candy Machine by using guards.

Since this is a vast subject with a lot of available default guards to explain, we’ve dedicated an entire section of this documentation to it. The best place to start is the Candy Guards page.

Conclusion

Now that we know about how the main Candy Machine settings, on the next page, we’ll see how we can use them to create and update our own Candy Machines.

Managing Candy Machines

On the previous page, we went through the various settings of a Candy Machine. So now, let’s see how we can use these settings to create and update Candy Machines. We’ll also talk about how to fetch an existing Candy Machine and how to delete it when it has served its purpose. Essentially, we’ll be going through the Create, Read, Update and Delete steps of a Candy Machine. Let’s go!

Create Candy Machines

You may use the settings discussed on the previous page to create a brand-new Candy Machine account. Our SDKs push this even further and will associate every new Candy Machine account with a new Candy Guard account which keeps track of all activated guards affecting the minting process. On this page, we will focus on the Candy Machine account but we’ll dig into Candy Guard accounts and what we can do with them on dedicated pages. Remember that a Candy Machine must be associated with a Collection NFT and its update authority must authorize this operation. If you haven’t got a Collection NFT for your Candy Machine yet, our SDKs can help with that too.

Create a Candy Machine
JavaScript
Here’s how you can create a Candy Machine using a brand new Collection NFT via the Umi library.

import   createNft, TokenStandard, > from '@metaplex-foundation/mpl-token-metadata' import  create > from '@metaplex-foundation/mpl-candy-machine' import  generateSigner, percentAmount > from '@metaplex-foundation/umi' // Create the Collection NFT. const collectionUpdateAuthority = generateSigner(umi) const collectionMint = generateSigner(umi) await createNft(umi,   mint: collectionMint, authority: collectionUpdateAuthority, name: 'My Collection NFT', uri: 'https://example.com/path/to/some/json/metadata.json', sellerFeeBasisPoints: percentAmount(9.99, 2), // 9.99% isCollection: true, >).sendAndConfirm(umi) // Create the Candy Machine. const candyMachine = generateSigner(umi) await create(umi,   candyMachine, collectionMint: collectionMint.publicKey, collectionUpdateAuthority, tokenStandard: TokenStandard.NonFungible, sellerFeeBasisPoints: percentAmount(9.99, 2), // 9.99% itemsAvailable: 5000, creators: [   address: umi.identity.publicKey, verified: true, percentageShare: 100, >, ], configLineSettings: some(  prefixName: '', nameLength: 32, prefixUri: '', uriLength: 200, isSequential: false, >), >).sendAndConfirm(umi) 

As mentioned above, this operation will also take care of creating and associating a new Candy Guard account with the created Candy Machine. That’s because a Candy Machine without a Candy Guard is not very useful and you’ll want to do that most of the time. Still, if you’d like to disable that behaviour, you may use the createCandyMachineV2 method instead.

import  createCandyMachineV2 > from '@metaplex-foundation/mpl-candy-machine' await createCandyMachineV2(umi,  // . >).sendAndConfirm(umi) 

In these examples, we only focused on the required parameters but you may want to check out the following API References to see what you can do with this create function. API References: create, createCandyMachineV2.

Candy Machine Account

  • Items Redeemed. This keeps track of the number of NFTs that were minted from the Candy Machine. Note that, as soon as this number goes from 0 to 1, most settings will no longer be updatable.
  • Account Version. This enum is used to keep track of the account version of the Candy Machine. It is used to determine which features are available and how the account should be interpreted. Note that this is not to be confused with «Candy Machine V3» which refers to the third and latest iteration of the Candy Machine programs (including the Candy Machine Core and Candy Guard programs).
  • Feature Flags. This helps the program with backward and forward compatibility as more features get introduced.

Finally, it stores all items inserted in the Candy Machine and whether or not they have been minted. This only applies for Candy Machine using Config Line Settings since Hidden Settings don’t allow you to insert any items. This section contains the following information:

  • The number of items that have been loaded.
  • A list of all items that have been or will be inserted. When an item is not inserted yet, the name and URI of the item at that position are empty.
  • A bitmap — a list of yes or no — that keeps track of which items have been loaded. When this bitmap is full of yeses, all items have been loaded.
  • A list of all items that have not been minted yet when minting using a random order. This allows the program to grab an index at random without having to worry about picking an index that has already been minted and start again.

Note that this last section is purposely not deserialised on the program but our SDKs parse all that data for you in a human-friendly format.

For more detailed information about the Candy Machine account, check out the program’s API References.

Inside Candy Machine accounts

JavaScript

The best way to check how Candy Machines are modelled in the Umi library is by checking the API References of the CandyMachine account. You may also want to check out the API References of the candyGuard account since one is automatically created for each candy machine when using the create function.

Here’s a small code example showcasing some of the Candy Machine attributes.

import   fetchCandyMachine, fetchCandyGuard, > from '@metaplex-foundation/mpl-candy-machine' const candyMachine = await fetchCandyMachine(umi, candyMachineAddress) const candyGuard = await fetchCandyGuard(umi, candyMachine.mintAuthority) candyMachine.publicKey // The public key of the Candy Machine account. candyMachine.mintAuthority // The mint authority of the Candy Machine which, in most cases, is the Candy Guard address. candyMachine.data.itemsAvailable // Total number of NFTs available. candyMachine.itemsRedeemed // Number of NFTs minted. candyMachine.items[0].index // The index of the first loaded item. candyMachine.items[0].name // The name of the first loaded item (with prefix). candyMachine.items[0].uri // The URI of the first loaded item (with prefix). candyMachine.items[0].minted // Whether the first item has been minted. 

Fetch Candy Machines

To fetch an existing Candy Machine, you simply need to provide its address and our SDKs will take care of parsing the account data for you.

Fetch Candy Machines

JavaScript

Here’s how you can fetch a Candy Machine using its address and its associated Candy Guard account if any.

import  publicKey > from '@metaplex-foundation/umi' import   fetchCandyMachine, fetchCandyGuard, > from '@metaplex-foundation/mpl-candy-machine' const candyMachine = await fetchCandyMachine(umi, publicKey('. ')) const candyGuard = await fetchCandyGuard(umi, candyMachine.mintAuthority) 

Update Authorities

Once a Candy Machine is created, you can update most of its settings later on, as long as you are the authority of the Candy Machine. In the next few sections we’ll see how to update these settings but first, let’s see how you can update the Authority and Mint Authority of a Candy Machine.

  • To update the authority, you need to pass the current authority as a signer and the address of the new authority.
  • To update the mint authority, you need to pass both the current authority and the new mint authority as signers. This is because the mint authority is mostly used to associate a Candy Guard with a Candy Machine. Making the mint authority a signer prevents anyone to use someone else Candy Guard as this could create side effects on the original Candy Machine.

Update the authority of a Candy Machine

JavaScript

Here’s how you can update the authority of a Candy Machine using the Umi library. Note that, in most cases, you’ll want to update the authority of the associated Candy Guard account as well.

import  generateSigner > from '@metaplex-foundation/umi' import   setCandyMachineAuthority, setCandyGuardAuthority, > from '@metaplex-foundation/mpl-candy-machine' const newAuthority = generateSigner(umi) await setCandyMachineAuthority(umi,   candyMachine: candyMachine.publicKey, authority: currentAuthority, newAuthority: newAuthority.publicKey, >) .add( setCandyGuardAuthority(umi,   candyGuard: candyMachine.mintAuthority, authority: currentAuthority, newAuthority: newAuthority.publicKey, >) ) .sendAndConfirm(umi) 

Whilst you’d probably never want to update the mintAuthority directly since it would override the associated Candy Guard account, this is how you’d do it.

import  generateSigner > from '@metaplex-foundation/umi' import  setMintAuthority > from '@metaplex-foundation/mpl-candy-machine' const newMintAuthority = generateSigner(umi) await setMintAuthority(umi,   candyMachine: candyMachine.publicKey, authority: currentAuthority, mintAuthority: newMintAuthority, >).sendAndConfirm(umi) 

Update Shared NFT Data

You may also update the attributes shared between all minted NFTs of a Candy Machine. As mentioned in the previous page, these are: Seller Fee Basis Points, Symbol, Max Edition Supply, Is Mutable and Creators.

Note that once the first NFT has been minted, these attributes can no longer be updated.

Update the NFT data of a Candy Machine

JavaScript

Here’s an example of updating some of the shared NFT data on a Candy Machine.

import  percentAmount > from '@metaplex-foundation/umi' import   updateCandyMachine, fetchCandyMachine, > from '@metaplex-foundation/mpl-candy-machine' const candyMachine = await fetchCandyMachine(umi, candyMachineAddress) await updateCandyMachine(umi,   candyMachine: candyMachine.publicKey, data:  . candyMachine.data, symbol: 'NEW', sellerFeeBasisPoints: percentAmount(5.5, 2), creators: [ address: newCreator, verified: false, percentageShare: 100 >], >, >).sendAndConfirm(umi) 

Update Token Standard

The Token Standard and Rule Set attributes can also be updated on a Candy Machine using the «Set Token Standard» instruction. This allows us to switch from regular NFTs to programmable NFTs and vice versa. When switching to programmable NFTs, we can optionally specify or update the Rule Set that minted NFTs should adhere to.

Note that, if you candy machine is using an old account version, this instruction will also automatically upgrade it to the latest account version that supports programmable NFTs as well as regular NFTs. Once upgraded, you will need to use the latest instructions for minting from the candy machine or candy guard.

Update the Token Standard of a Candy Machine

JavaScript

Here’s an example of updating the token standard and rule set on a Candy Machine using Umi.

import  TokenStandard > from '@metaplex-foundation/mpl-token-metadata' import  setTokenStandard > from '@metaplex-foundation/mpl-candy-machine' await setTokenStandard(umi,   candyMachine: candyMachine.publicKey, collectionMint: candyMachine.collectionMint, collectionUpdateAuthority, tokenStandard: TokenStandard.ProgrammableNonFungible, ruleSet: newRuleSetAccount, >).sendAndConfirm(umi) 

Note that if your candy machine is using account version V1 , you will need to explicitly set the collectionAuthorityRecord account as it uses the legacy collection delegate authority record account.

import  findCollectionAuthorityRecordPda > from '@metaplex-foundation/mpl-token-metadata' import  findCandyMachineAuthorityPda > from '@metaplex-foundation/mpl-candy-machine' await setTokenStandard(umi,  // . collectionAuthorityRecord: findCollectionAuthorityRecordPda(umi,   mint: candyMachine.collectionMint, collectionAuthority: findCandyMachineAuthorityPda(umi,   candyMachine: candyMachine.publicKey, >), >), >).sendAndConfirm(umi) 

Update Collection

Changing the Collection NFT associated with a Candy Machine is also possible. You’ll need to provide the address of the Collection NFT’s mint account as well as its update authority as a signer to approve this change.

Note that, here also, once the first NFT has been minted, the collection cannot be changed.

Update the collection of a Candy Machine

JavaScript

To update the Collection NFT of a Candy Machine using the Umi library you may use the setCollectionV2 method like so.

await setCollectionV2(umi,   candyMachine: candyMachine.publicKey, collectionMint: candyMachine.collectionMint, collectionUpdateAuthority: collectionUpdateAuthority.publicKey, newCollectionMint: newCollectionMint.publicKey, newCollectionUpdateAuthority, >).sendAndConfirm(umi) 

Note that if your candy machine is using account version V1 , you will need to explicitly set the collectionDelegateRecord account as it uses the legacy collection delegate authority record account.

import  findCollectionAuthorityRecordPda > from '@metaplex-foundation/mpl-token-metadata' import  findCandyMachineAuthorityPda > from '@metaplex-foundation/mpl-candy-machine' await setCollectionV2(umi,  // . collectionDelegateRecord: findCollectionAuthorityRecordPda(umi,   mint: candyMachine.collectionMint, collectionAuthority: findCandyMachineAuthorityPda(umi,   candyMachine: candyMachine.publicKey, >), >), >).sendAndConfirm(umi) 

Update Item Settings

The item settings of a Candy Machine can also be updated but there are some limitations.

  • The item settings cannot be updated such that we are swapping between Config Line Settings and Hidden Settings. However, if we’re not swapping the modes, the properties inside these settings can be updated.
  • When using Config Line Settings:
    • The Items Available attribute cannot be updated.
    • The Name Length and URI Length properties can only be updated to smaller values as the program will not resize the Candy Machine account during updates.

    Update the item settings of a Candy Machine

    JavaScript

    The following example shows how to update the Config Line Settings of a Candy Machine using the Umi library. The same can be done with Hidden Settings and the Items Available attribute (when using Hidden Settings).

    import   updateCandyMachine, fetchCandyMachine, > from '@metaplex-foundation/mpl-candy-machine' const candyMachine = await fetchCandyMachine(umi, candyMachineAddress) await updateCandyMachine(umi,   candyMachine: candyMachine.publicKey, data:  . candyMachine.data, hiddenSettings: none(), configLineSettings: some(  type: 'configLines', prefixName: 'My New NFT #$ID+1$', nameLength: 0, prefixUri: 'https://arweave.net/', uriLength: 43, isSequential: true, >), >, >).sendAndConfirm(umi) 

    Delete Candy Machines

    Once a Candy Machine has been fully minted, it has served its purpose and can safely be disposed of. This allows its creator to gain back the storage cost of the Candy Machine account and, optionally, the Candy Guard account too.

    Delete a Candy Machine

    JavaScript

    You may delete a Candy Machine account and/or its associated Candy Guard account using the Umi library like so.

    import   deleteCandyMachine, deleteCandyGuard, > from '@metaplex-foundation/mpl-candy-machine' await deleteCandyMachine(umi,   candyMachine: candyMachine.publicKey, >).sendAndConfirm(umi) await deleteCandyGuard(umi,   candyGuard: candyMachine.mintAuthority, >).sendAndConfirm(umi) 

    Conclusion

    We can now create, read, update and delete Candy Machines but we still don’t know how to load them with items. Let’s tackle this on the next page!

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

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