13 / 15Module 3: Create the marketplaceAdvanced
Buy a card on the marketplace
Your marketplace can already list NFTs that are for sale. The next piece is an operation that lets a user complete a purchase.
operation buy_nft(id: integer) { val account = auth.authenticate(); val (nft, owner, price) = listed_nft @ { .nft.rowid == rowid(id) } ( .nft, .listed_by, .price ); Unsafe.transfer(account, owner, dapp_meta.asset, price); delete listed_nft @ { .nft.rowid == rowid(id) }; nft.owner = account;}A call to buy_nft first checks that the caller is authenticated. The operation then retrieves the NFT and queries listed_nft to make sure it is up for sale. After that, it moves the amount set by the price from the buyer's account to the seller, who owns the NFT. Finally, it removes the NFT's marketplace listing and records the buyer as the new owner.
With this operation in place, the marketplace handles these features:
- A user buys an NFT, and the dapp mints it.
- An NFT can be put up for sale on the marketplace at a fixed price.
- A user can purchase a listed NFT by paying the asking price.
Written for this site from Chromia’s public course. Code samples are the course’s own.