12 / 15Module 3: Create the marketplaceAdvanced
Put a card up for sale on the marketplace
Users can now buy mystery cards, each of which mints a random collector card for them.
Next, you will extend the marketplace so cards can be listed for sale and users can buy and sell them.
Begin by defining the listed_nft entity.
entity listed_nft { key nft: nft; mutable price: big_integer; index listed_by: account; listed_date: timestamp = op_context.last_block_time;}Each listed_nft record stands for an NFT offered on the marketplace. It stores the asking price and the date the NFT was put up for sale. With the entity in place, add an operation that lets a user list a card NFT they own.
operation list_nft(id: integer, price: big_integer) { val account = auth.authenticate(); val (nft, owner) = nft @ { .rowid == rowid(id) } ( $, .owner ); require(owner == account, "User must be owner of NFT"); create listed_nft ( nft, price, owner );}To list a card, the user submits a transaction to list_nft, passing the card's NFT ID and a price. The operation then does the following:
- It calls the authenticate method to confirm that an FT4 account signed the transaction.
- It looks up who owns the NFT and retrieves the NFT entity.
- It checks that the account doing the listing is the NFT's owner.
- If all checks pass, it creates a new
listed_nftinstance that records the NFT, the price, and the owner.
With this operation, users can put their NFTs up for sale. To retrieve the listings, add a query as well.
enum card_sorting { NONE, PRICE_HIGH, PRICE_LOW }query get_cards(amount: integer, card_sorting) = (listed_nft, nft_card) @* { listed_nft.nft == nft_card.nft} ( @omit @sort_desc when (card_sorting) { PRICE_HIGH -> .price; PRICE_LOW -> -.price; else -> nft_card.rowid.to_integer() }, listed_nft_card_dto ( price = listed_nft.price, id = nft_card.nft.rowid.to_integer(), card = nft_card.to_struct() )) limit amount;struct listed_nft_card_dto { id: integer; price: big_integer; card: struct<nft_card>;}Here is how the query works.
It returns the NFTs currently listed on the marketplace, and you can sort them by price. Each result is shaped by listed_nft_card_dto, which defines the attributes included in the returned data.