Learn how to create a crowdfunding app, enabling creators to fund their projects without a third party.
In this guide, you will learn how to create an NFT marketplace that allows users to list NFTs for sale. Users can specify the following details for their listings:
The NFT token to sell.
Listing expiry in block height.
The payment asset, either STX or a SIP010 fungible token.
The NFT price in the chosen payment asset.
An optional intended taker. If set, only that principal will be able to fulfil the listing.
This marketplace leverages the following Clarity traits:
nft-trait for handling NFTs.
ft-trait for handling fungible tokens.
Over the course of this guide, you will learn how to:
First, define constants for various errors that may occur during listing, cancelling, or fulfilling NFT transactions. This helps in maintaining clean and readable code.
Create a public function to list an asset along with its contract. This function verifies the contract, checks expiry and price, and transfers the NFT ownership to the marketplace.
(define-public(list-asset
(nft-asset-contract<nft-trait>)
(nft-asset{
taker: (optionalprincipal),
token-id:uint,
expiry:uint,
price:uint,
payment-asset-contract: (optionalprincipal)
})
)
(let((listing-id(var-getlisting-nonce)))
;; Verify that the contract of this asset is whitelisted
Create a public function to cancel a listing. Only the NFT's creator can cancel the listing, and it must use the same asset contract that the NFT uses.
The marketplace requires any contracts used for assets or payments to be whitelisted by the contract owner. Create a map to store whitelisted asset contracts and a function to check if a contract is whitelisted.
Create a private function to validate that a purchase can be fulfilled. This function checks the listing's expiry, the NFT's contract, and the payment's contract.
(define-private(assert-can-fulfil
(nft-asset-contractprincipal)
(payment-asset-contract(optionalprincipal))
(listing{
maker:principal,
taker: (optionalprincipal),
token-id:uint,
nft-asset-contract:principal,
expiry:uint,
price:uint,
payment-asset-contract: (optionalprincipal)
})
)
(begin
;; Verify that the buyer is not the same as the NFT creator
By following this guide, you have created a basic NFT marketplace that allows users to list, buy, and sell NFTs using either STX or fungible tokens. This implementation includes essential functionalities such as whitelisting contracts, validating transactions, and handling errors.