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

Lazy mint от opensea что это

  • автор:

Lazy minting

Минт NFT в большинстве блокчейнов обычно требует трат на газ. Многим до сих пор снятся эфир минты с комсой по пару k$.

Однако используя несколько методов, можно платить газ за минт в момент первой продажи. Плата происходит только в тот момент, когда нфт присваивается юзером, создателю же платить не придется, просто из цены продажи вычитается часть для оплаты газа

Минт «точно в срок» в момент покупки называют lazy mint, и данный метод был принят такими торговыми площадками, как OpenSea , чтобы снизить барьер для входа создателям NFT, позволяя создавать NFT без каких-либо предварительных затрат.(Многие уже создавали свои коллекции на ОС, не платив комиссии. Если вы этого не делали то попробуйте здесь )

В этой статье будет показан пример на Ethereum с использованием некоторых вспомогательных библиотек и базовых контрактов от OpenZeppelin .

Как это работает

Основная предпосылка ленивого минта заключается в том, что вместо непосредственного создания NFT путем вызова контрактной функции создатель NFT готовит подпись некоторых данных, используя приват кей.

Подписанные данные действуют как «ваучер» или билет, который можно обменять на NFT. Ваучер содержит всю информацию, которая войдет в фактический NFT, и он может дополнительно содержать дополнительные данные, которые не записаны в блокчейне, как мы увидим чуть позже, когда будем говорить о ценах. Подпись подтверждает, что создатель NFT санкционировал создание конкретного NFT, описанного в ваучере.

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

В нашем примере мы используем структуру Solidity для представления нашего ваучера:

struct NFTVoucher

Создание подписанного ваучера

Использование подписей для авторизации может быть сложным, поскольку третья сторона потенциально может взять данные, которые были подписаны в одном контексте, и представить их где-то в другом месте. Как пример, они могут взять подпись, разрешающую создание NFT в тестовой сети Ropsten, и представить ее контракту, развернутому в mainnet. Если подписываемые данные не содержат какой-либо контекстной информации, этот вид «повторной атаки» довольно тривиален для выполнения и от него трудно защититься.

Чтобы устранить эти проблемы, а также обеспечить лучший пользовательский опыт при подписании сообщений, сообщество Ethereum разработало EIP-712, стандарт для подписи типизированных структурированных данных. Подписи, созданные с помощью EIP-712, «привязаны» к определенному экземпляру смарт-контракта, работающего в определенной сети. Они также содержат информацию о типе, так что такие инструменты, как MetaMask, могут предоставлять пользователю более подробную информацию о подписываемых данных вместо непрозрачной строки шестнадцатеричных символов. Однако стандарт является отличной защитой лишь он-чейн, возможность перехвата данных во время их поступления в дапп все так же остается. (Пример, когда использовали кошельки находящиеся в вайтлисте, передавали его на бек проекта и в ответ получали данные для подписи транкзации).

Мы используем класс JavaScript под названием LazyMinter для подготовки подписанных ваучеров с использованием EIP-712. Поскольку подписи привязаны к конкретному контракту, вам необходимо указать адрес развернутого контракта и ethers.js:

const lazyminter = new LazyMinter(< myDeployedContract.address, signerForMinterAccount >) async createVoucher(tokenId, uri, minPrice = 0) < const voucher = < tokenId, uri, minPrice >const domain = await this._signingDomain() const types = < NFTVoucher: [ , , , ] > const signature = await this.signer._signTypedData(domain, types, voucher) return < . voucher, signature, >>

Сначала мы готовим наш неподписанный объект ваучера и получаем домен подписи. Объект types содержит информацию о типе для полей нашего NFTVoucher (исключая саму подпись).

Чтобы создать подпись, мы вызываем метод _signTypedData для нашего объекта Signer, передавая домен, определение типа и неподписанный объект ваучера.

Наконец, мы возвращаем полный объект ваучера с включенной подписью, который можно использовать в нашем смарт-контракте.

Оплата газа при покупке

Чтобы метод работал, нам нужна функция смарт-контракта, которую может вызвать покупатель NFT, чтобы заминтить за одну транзакцию:

function redeem(address redeemer, NFTVoucher calldata voucher) public payable returns (uint256) < // make sure signature is valid and get the address of the signer address signer = _verify(voucher); // make sure that the signer is authorized to mint NFTs require(hasRole(MINTER_ROLE, signer), "Signature invalid or unauthorized"); // make sure that the redeemer is paying enough to cover the buyer's cost require(msg.value >= voucher.minPrice, "Insufficient funds to redeem"); // first assign the token to the signer, to establish provenance on-chain _mint(signer, voucher.tokenId); _setTokenURI(voucher.tokenId, voucher.uri); // transfer the token to the redeemer _transfer(signer, redeemer, voucher.tokenId); // record payment to signer's withdrawal balance pendingWithdrawals[signer] += msg.value; return voucher.tokenId; >

Сначала мы вызываем вспомогательную функцию _verify, которая либо возвращает адрес учетной записи, подготовившей подпись, либо отменяет транзакцию, если подпись недействительна.

Как только у нас есть адрес подписавшего, мы проверяем, что он авторизован для минта с помощью функции hasRole из контракта AccessControl на основе ролей OpenZeppelin .

Мы также следим за тем, чтобы покупатель отправил достаточно ETH, чтобы покрыть минимальную цену. Если это так, мы можем создать новый токен на основе информации в ваучере и перевести его на учетную запись получателя.

Наконец, мы помещаем платеж в сопоставление под названием pendingWithdrawals, чтобы создатель NFT мог позже вывести свой ETH.

Заключение

Данный способ позволяет экономить на газе, однако еще мало используем среди коллеций на евм блокчейне. Минусом данного метода является возможность для злоумышленников создавать фейк или фишинг коллекции, которые многие замечали на своих аккаунтах Opensea в разделе hidden(крайне НЕ РЕКОМЕНДУЮ взаимодействовать с данными объектами).

# Lazy minting

Minting an NFT on a blockchain mainnet generally costs some amount of money, since writing data onto the blockchain requires a fee (often called gas) to pay for the computation and storage. This can be a barrier for NFT creators, especially those new to NFTs who may not want to invest a lot of money up front before knowing whether their work will sell.

Using a few advanced techniques, it’s possible to defer the cost of minting an NFT until the moment it’s sold to its first buyer. The gas fees for minting are rolled into the same transaction that assigns the NFT to the buyer, so the NFT creator never has to pay to mint. Instead, a portion of the purchase price simply goes to cover the additional gas needed to create the initial NFT record.

Minting «just in time» at the moment of purchase is often called lazy minting, and it has been adopted by marketplaces like OpenSea

(opens new window) to lower the barrier to entry for NFT creators by making it possible to create NFTs without any up-front costs.

This guide will show an example of lazy minting on Ethereum, using some helper libraries and base contracts from OpenZeppelin

(opens new window) . If you’re new to minting NFTs in general, our minting service tutorial is a great place to get up to speed on the basics.

Throughout the guide, we’ll be referring to an example project, which lives in the NFT School examples repository

(opens new window) . If you want to dig in, clone the repo and open the example in your favorite editor:

git clone https://github.com/ipfs-shipyard/nft-school-examples cd nft-school-examples/lazy-minting code . # or whichever editor you prefer 

# How it works

The basic premise of lazy minting is that instead of creating an NFT directly by calling a contract function, the NFT creator prepares a cryptographic signature of some data using their Ethereum account’s private key.

The signed data acts as a «voucher» or ticket that can be redeemed for an NFT. The voucher contains all the information that will go into the actual NFT, and it may optionally contain additional data that isn’t recorded in the blockchain, as we’ll see in a bit when we talk about prices. The signature proves that the NFT creator authorized the creation of the specific NFT described in the voucher.

When a buyer wants to purchase the NFT, they call a redeem function to redeem the signed voucher. If the signature is valid and belongs to an account that’s authorized to mint NFTs, a new token is created based on the voucher and transfered to the buyer.

For our example, we’re using a Solidity struct

(opens new window) to represent our voucher:

struct NFTVoucher  uint256 tokenId; uint256 minPrice; string uri; bytes signature; > 

The voucher contains two pieces of information that will be recorded into the blockchain: the unique tokenId , and the uri for the token’s metadata. The minPrice is not recorded, but it is used in our redeem function to allow the creator to set a purchase price. If the minPrice is greater than zero, the buyer will need to send at least that much Ether when they call redeem .

The signature field in our struct contains a signature prepared by the NFT creator as described in the next section.

Setting a purchase price inside the voucher isn’t always necessary, but you will probably need some kind of condition. Otherwise, anyone who has the voucher could claim the NFT for just the gas cost!

For example, if you’re «air-dropping» NFTs to specific accounts and know the recipient addresses up front, your voucher could include an address recipient field instead of a minPrice , and your redeem function could check to make sure that msg.sender == voucher.recipient .

# Creating a signed voucher

Using signatures for authorization can be tricky, since a sneaky third party could potentially take some data that was signed in one context and present it somewhere else. For example, they may take a signature authorizing the creation of an NFT on the Ropsten testnet and present it to a contract deployed on mainnet. Unless the data being signed contains some context information, this kind of «replay attack» is fairly trivial to perform and hard to defend against.

To address these concerns and also provide a better user experience when signing messages, the Ethereum community has developed EIP-712

(opens new window) , a standard for signing typed, structured data. Signatures created with EIP-712 are «bound» to a specific instance of a smart contract running on a specific network. They also contain type information, so that tools like MetaMask

(opens new window) can present more details about the data being signed to the user instead of an opaque string of hex characters.

Our example uses a JavaScript class called LazyMinter to prepare signed vouchers using EIP-712. Because the signatures are bound to a specific contract instance, you need to provide the address of the deployed contract and an ethers.js Signer

(opens new window) for the NFT creator’s private key:

const lazyminter = new LazyMinter( myDeployedContract.address, signerForMinterAccount >) 

Here’s the main createVoucher method that creates signed NFT vouchers:

 async createVoucher(tokenId, uri, minPrice = 0)  const voucher =  tokenId, uri, minPrice > const domain = await this._signingDomain() const types =  NFTVoucher: [ name: "tokenId", type: "uint256">, name: "minPrice", type: "uint256">, name: "uri", type: "string">, ] > const signature = await this.signer._signTypedData(domain, types, voucher) return  . voucher, signature, > > 

First we prepare our unsigned voucher object and get the signing domain to use for EIP-712. The types object contains the type information for our NFTVoucher ‘s fields (excluding the signature itself).

To create the signature, we call the _signTypedData method on our Signer object, passing in the domain, type definition, and the unsigned voucher object.

Finally, we return the full voucher object with the signature included, which can be redeemed in our smart contract.

The _signTypedData method will be renamed to signTypedData in a future version of ethers.js! See the ethers docs for more info

# Redeeming a voucher on-chain

For lazy minting to work, we need a smart contract function that the NFT buyer can call that will both mint the NFT they want and assign it to their account, all in one transaction. Ours is called redeem :

 function redeem(address redeemer, NFTVoucher calldata voucher) public payable returns (uint256)  // make sure signature is valid and get the address of the signer address signer = _verify(voucher); // make sure that the signer is authorized to mint NFTs require(hasRole(MINTER_ROLE, signer), "Signature invalid or unauthorized"); // make sure that the redeemer is paying enough to cover the buyer's cost require(msg.value >= voucher.minPrice, "Insufficient funds to redeem"); // first assign the token to the signer, to establish provenance on-chain _mint(signer, voucher.tokenId); _setTokenURI(voucher.tokenId, voucher.uri); // transfer the token to the redeemer _transfer(signer, redeemer, voucher.tokenId); // record payment to signer's withdrawal balance pendingWithdrawals[signer] += msg.value; return voucher.tokenId; > 

First we call a _verify helper function, which either returns the address of the account that prepared the signature or reverts the transaction if the signature is invalid.

Once we have the signer’s address, we check that they’re authorized to create NFTs using the hasRole function from OpenZeppelin’s role-based AccessControl contract

We also make sure that the buyer has sent enough ETH to cover the minPrice . If so, we can create a new token based on the info in the voucher and transfer it to the redeemer account.

Finally, we tuck the payment into a mapping called pendingWithdrawals , so the NFT creator can get their ETH out later.

That’s it! If you’re curious about the signature verification, see the contract source

# Conclusion

Lazy minting is a powerful technique that can let creators issue new NFTs at no up-front cost.

Although we’ve demonstrated the core technique here, a production platform will need a lot more! For example, you’ll likely need an application for NFT creators to issue signed vouchers, and you’ll probably want some kind of back-end system to keep track of all the «un-minted» NFTs waiting to be redeemed.

Have fun building, and let us know

(opens new window) if there’s anything you’d like to see on this page that we haven’t covered!

What Is Lazy Minting?

GamesPad: What Is Lazy Minting? 1

Minting is the process of creating something. So, when we speak about NFT minting, we mean creating new NFTs.

But NFT minting is not a free process. When you mint NFTs, you have to pay a blockchain fee. High gas fees are the main issue of the most popular blockchains, especially if the network is congested. At times, this minting fee is so high that it inhibits users from minting NFTs and, thus, doesn’t permit them to benefit from many lucrative opportunities such mints offer.

Lazy NFT Minting as a Way to Solve the Minting Fee Issue

Here, the lazy minting process comes to help. It changes the way the standard minting process works and allows ordinary users and artists to avoid paying high gas fees before the NFT can even be sold.

Some History

Most NFTs are never sold, and blockchain fees are constantly growing. These upfront payments in the form of gas fees make the cost of NFT creation too high and, thus, inhibit many talented artists from entering the market.

It was the main reason why lazy minting was adopted in 2020.

Until now, only a limited number of marketplaces (OpenSea and Rarible) offer the option of lazy minting. Artists can lazy-mint NFTs without paying upfront gas fees. Only when somebody buys the NFT the gas fee is charged, and a smarter contract will write operation on a blockchain. All the data about the NFT and, thus, the NFT will be moved to the purchaser’s wallet.

What Is Lazy Minting?

Lazy minting is when an NFT is available off-chain. And only when it is sold is it minted on the chain, and the gas fee is charged.

So, the NFT creators don’t pay anything in advance. The gas fee is charged only when the NFT is sold and goes on-chain, and the payment is made by the NFT purchaser, not by the NFT creator.

NFT Lazy Minting or Ordinary Minting?

When you decide to mint an NFT, you have to choose what you prefer:

  • Ordinary minting is where you pay for minting an NFT.
  • Lazy minting or free minting

If you opt to pay a minting fee on your own, you proceed as follows:

  • You decide which marketplace you are going to use for NFT minting. The most popular NFT marketplaces are OpenSea and Rarible.
  • Pay a gas fee for minting NFTs.
  • Sell the NFT on one of the selected NFT marketplaces.

If you opt for lazy minting, the process is slightly different:

  • Choose a marketplace that offers an option of lazy minting. OpenSea has a smart contract that supports lazy minting, Rarible does it, too.
  • Create an NFT signature signed with your private key.
  • When someone purchases the NFT, he pays its price and the gas fee. Then, the NFT is successfully lazy-minted (recorded in the decentralized database) and passed to the new owner.

Advantages of NFT Lazy Minting

When you are lazy-minting NFTs, you get some benefits.

You eliminate the upfront gas costs. Your NFT exists off-chain, and only when and if it is sold the buyer pays the gas costs along with the purchase price.

It lowers the entry barrier. Gas prices, especially on the Ethereum blockchain, can prevent beginners from entering the NFT market. The cost of minting is not affordable for many users who otherwise could have created amazing digital artwork pieces. Lazy minting eliminated any need to pay upfront costs. Only when the purchase is made, do buyers pay the NFT cost and the cost of minting.

Increase liquidity. Lazy minting prevents situations when creators are left with plenty of minted NFTs, huge sums paid in gas fees, and unable to sell the minted NFTs. In the case of lazy minting, non-fungible tokens are available off-chain, and only when there are buyers for them, the fees are charged, and the assets are recorded on a blockchain.

Reduces the computational power used for minting NFTs. Only a small part of NFTs is sold, and the majority just stays on a blockchain. In the case of lazy minting, only if an NFT is purchased the minting process happens. Thus, if there is nobody willing to get an NFT, the computational power is not used, and gas fees are not paid.

Disadvantages of Lazy Minting

Even though lazy minting looks like a perfect solution for digital art creators, it has some drawbacks.

Partial loss of control. When choosing to lazy mint NFTs, the artist cannot decide to whom he wants to sell the asset.

Higher risk of fraud. What if someone sells an NFT without an opportunity to mint it? Then, the buyer will basically pay for the asset but won’t be able to use the mint function to get the NFT to his wallet.

Hacking risks. When you sign a smart contract without recording the NFT on a blockchain, you are more vulnerable to hacks. An NFT that is not minted yet is not recorded on a blockchain. therefore, if it is stolen, there is not much you can do to get the token back to your wallet address or the money for which you would have sold it.

Gas fees still have to be paid. While the buyer pays the fee for lazy minting work, the creator pays a fee for the NFT sale. The required money is deducted from the final NFT sale price. It may result in much lower returns than one expects; thus, always check the price to create an NFT and sell it and calculate all the numbers and prices very carefully.

Fees on Popular NFT Marketplaces

Now, when you know there is an opportunity to lazy-mint your NFT instead of paying all the gas prices associated with the NFT creation and recording it on a blockchain, you may wonder what the fees are. Are they so high, indeed?

First of all, not all marketplaces support the lazy minting functionality. Three marketplaces where you can use the lazy minting option are:

Rarible

Along with the function of lazy minting, the platform offers a paid minting service for all NFT sellers. For each NFT sale, the Rarible minting fees charge a 2.5% fee.

OpenSea

OpenSea charges their users two fee types before they are permitted to sell on the platform. The first fee is for setting up an account. It may vary from 70 USD and higher up to 300 USD. The second fee is paid for accessing the marketplace. It may vary from 10 USD to 30 USD.

How to Lazy Mint on OpenSea: a Guide

How to Lazy Mint on OpenSea

If you have decided to opt for lazy minting, here is a guide on how you can lazy mint your NFTS on OpenSea.

Lazy Minting on OpenSea

Step.1

Register an OpenSea account and connect your wallet.

Step.2

In the upper corner, click on the Create option.

Step.3

Upload the content to create your NFT.

Step.4

Click on the Create button to create the NFTs.

Step.5

Click on the created NFT, you will be moved to its page.

Step.6

Click on the Sell option and set the listing duration and price.

Step.7

Click on the Complete listing option.

Step.8

Sign the message from your wallet.

When your NFT is purchased, a smart contract mints it to your wallet and sends it to the purchaser. All the fees are paid by the person who purchased the token, and all the information will be recorded on a blockchain.

How to Lazy Mint on Rarible: a Guide

GamesPad: What Is Lazy Minting? 4

To use the lazy mint NFTs function on Rarible, perform the following actions.

Step.1

Open the Rarible website, register an account, and connect your wallet.

Step.2

Click on Create and provide the required information about your NFT.

Step.3

From the suggested options to mint NFTs, pick Free Minting.

Step.4

Click on Create item and sign free authorizations with your wallet.

Step.5

That’s it, just wait till somebody buys your NFT. Then, the NFT will be minted to your wallet, and respective smart contracts will transfer the lazy minted NFT to the account of a purchaser, and the gas fees will be paid by the buyer, too.

Can Lazy Minting Be Considered Buying an NFT?

When you mint an NFT, you record something completely new, all the information about the NFT on a blockchain. But when you buy an NFT, you get an NFT recorded on a blockchain to your wallet address. Thus, lazy minting differs from buying. In the first case, you have to mint an NFT and thus record it on-chain, and in the latter case, an NFT is available on-chain, and you just purchase it.

Is the Lazy Minting Process Worth the Effort?

If you are a creator, have some funds to invest, and believe that your NFT will be purchased, you can mint them. It eliminates many risks associated with keeping your NFT off-chain. But if you want to try the market and aren’t ready to invest in minting, you can record the data required for your NFT, and pick the lazy minting option.

Conclusion: Lazy Minting Is Worth the Effort

Now, you know what is lazy minting and why it was introduced. Every creator can now choose whether he wants to pay or he prefers to wait till somebody wants to buy his NFT and mint it. The more choices you have, the better!

Would you like to start investing in the most impactful crypto gaming, NFT and metaverse projects with GamesPad? Learn how in this comprehensive tutorial!

Disclaimer. This material should not be construed as a basis for making investment decisions or as a recommendation to participate in investment transactions. Trading digital assets may involve significant risks and can result in the loss of invested capital. Therefore, you must ensure that you fully understand the risk involved, consider your level of experience, investment objectives, and seek independent financial advice if necessary.

Lazy Minting NFTs: How Does Lazy Minting Work?

Minting an NFT, or non-fungible token, is the process of publishing a one-of-a-kind digital asset on a blockchain so that it can be bought, sold, and traded.

Usually represented by a graphic, audio, or video, NFTs contain ownership, transaction details, and other information embedded in a block of data. They can also represent real-world assets like designer clothing, art, collectibles, and property. Each NFT has its own unique serial number that’s stored on the blockchain, making it extremely difficult to counterfeit.

Usually, when you mint an NFT, you are charged a gas fee to cover the cost of computing energy to perform an on-chain transaction, plus various account and marketplace fees.

Example of gas fee screen on MetaMask:

These fees can be a hurdle for NFT creators, who may hesitate to invest a lot of money upfront before knowing if their work will sell. One of the solutions that can help these creators is called lazy minting.

What is lazy minting?

Marketplaces like OpenSea have adopted lazy minting in order to lower the cost of entry for NFT creators.

It’s a form of NFT creation that defers the costs of minting an NFT until it’s sold on the market. The gas fee for minting is included in the sale transaction that assigns the NFT to the buyer so the seller doesn’t have to pay anything upfront.

Here’s how it works. Instead of creating an NFT directly—technically called “calling a contract”—and paying for that call to the blockchain, the NFT creator makes a «voucher» or ticket that can be redeemed for the NFT during the sale. The «voucher» contains all the data that will go into the actual NFT, a smart contract, and a signature. The signature is public data that confirms the authenticity of the NFT and verifies that the NFT creator had authorized it for sale.

To provide a better user experience when dealing with signed vouchers, the Ethereum community developed EIP-712—a standard for signing digital claim tickets. Signatures created with EIP-712 are proof of confirmation from a smart contract running on a specific network.

What are the pros and cons of lazy minting?

Lazy minting is a powerful tool for NFT creators who want to minimize upfront costs, however there are some drawbacks to consider:

  • Lazy minting can have higher overall costs depending on the fee taken by the marketplace upon sale.
  • When you’re signing a smart contract before it is officially immortalized on the blockchain (often called an “off-chain” transaction), you’re more vulnerable to fraud and hacking. To minimize risk, we recommend using reputable marketplaces like Opensea and Rarible to lazy mint your NFTs.
  • You might not have a say in who purchases your NFT.

Example of fee for committing smart contract to blockchain, instead of lazy minting:

How to get started with lazy minting?

Although we’ve covered some basics here, NFT marketplaces offer excellent services to help you through the complex parts, such as creating smart contracts. If you are looking to lazy mint an NFT—we suggest using a popular NFT marketplace called Rarible.

Just follow these four simple steps below:

  1. Go to Rarible.com and connect your wallet
  2. Click the “Create” button and fill in all the information about the NFT you are creating
  3. Choose “Free minting” option
  4. Click on “Create item” and sign free authorizations with your wallet

You should be all set after completing the authorization. Then, once someone purchases it, your NFT will be minted to your wallet and subsequently transferred to the new owner automatically.

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

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