8. Marketplace

In this tutorial, we're going to create a marketplace that uses both the fungible and non-fungible token (NFTs) contracts that we have learned about in previous tutorials. This is only for educational purposes and is not meant to be used in production See a production-ready marketplace in the NFT storefront repo. This contract is already deployed to testnet and mainnet and can be used by anyone for any generic NFT sale!


Open the starter code for this tutorial in the Flow Playground:

https://play.onflow.org/49ec2856-1258-4675-bac3-850b4bae1929


The tutorial will be asking you to take various actions to interact with this code. The marketplace setup guide shows you how to get the playground set up to do this tutorial.

Instructions that require you to take action are always included in a callout box like this one. These highlighted actions are all that you need to do to get your code running, but reading the rest is necessary to understand the language's design.

Marketplaces are a popular application of blockchain technology and smart contracts. When there are NFTs in existence, users usually want to be able to buy and sell them with their fungible tokens.

Now that there is an example for both fungible and non-fungible tokens, we can build a marketplace that uses both. This is referred to as composability: the ability for developers to leverage shared resources, such as code or userbases, and use them as building blocks for new applications. Flow is designed to enable composability because of the way that interfaces, resources and capabilities are designed. Interfaces allow projects to support any generic type as long as it supports a standard set of functionality specified by an interface. Resources can be passed around and owned by accounts, contracts or even other resources, unlocking different use-cases depending on where the resource is stored. Capabilities allow exposing user-defined sets of functionality through special objects that enforce strict security with Cadence's type system. The combination of these allows developers to do more with less, re-using known safe code and design patterns to create new, powerful, and unique interactions!

At some point before or after this tutorial, you should definitely check out the formal documentation linked above about interfaces, resources, and capabilities. It will help complete your understanding of these complex, but powerful features.

To create a marketplace, we need to integrate the functionality of both fungible and non-fungible tokens into a single contract that gives users control over their money and assets. To accomplish this, we're going to take you through these steps to create a composable smart contract and get comfortable with the marketplace:

  1. Ensure that your fungible token and non-fungible token contracts are deployed and set up correctly.
  2. Deploy the marketplace type declarations to account 0x03.
  3. Create a marketplace object and store it in your account storage, putting an NFT up for sale and publishing a public capability for your sale.
  4. Use a different account to purchase the NFT from the sale.
  5. Run a script to verify that the NFT was purchased.

Before proceeding with this tutorial, you need to complete the Fungible Tokens and Non-Fungible Token tutorials to understand the building blocks of this smart contract.

Marketplace Design


One way to implement a marketplace is to have a central smart contract that users deposit their NFTs and their price into, and have anyone come by and be able to buy the token for that price. This approach is reasonable, but it centralizes the process and takes away options from the owners. We want users to be able to maintain ownership of the NFTs that they are trying to sell while they are trying to sell them.

Instead of taking this centralized approach, each user can list a sale from within their own account.

Then, users could either provide a link to their sale to an application that can list it centrally on a website, or to a central sale aggregator smart contract if they want the entire transaction to stay on-chain. This way, the owner of the token keeps custody of their token while it is on sale.

Before we start, we need to confirm the state of your accounts.
If you haven't already, please perform the steps in the marketplace setup guide to ensure that the Fungible Token and Non-Fungible Token contracts are deployed to account 1 and 2 and own some tokens. Your accounts should look like this:

You can run the 1. CheckSetupScript.cdc script to ensure that your accounts are correctly set up:

1
// CheckSetupScript.cdc
2
3
import ExampleToken from 0x01
4
import ExampleNFT from 0x02
5
6
// This script checks that the accounts are set up correctly for the marketplace tutorial.
7
//
8
// Account 0x01: Vault Balance = 40, NFT.id = 1
9
// Account 0x02: Vault Balance = 20, No NFTs
10
pub fun main() {
11
// Get the accounts' public account objects
12
let acct1 = getAccount(0x01)
13
let acct2 = getAccount(0x02)
14
15
// Get references to the account's receivers
16
// by getting their public capability
17
// and borrowing a reference from the capability
18
let acct1ReceiverRef = acct1.getCapability(/public/CadenceFungibleTokenTutorialReceiver)
19
.borrow<&ExampleToken.Vault{ExampleToken.Balance}>()
20
?? panic("Could not borrow acct1 vault reference")
21
22
let acct2ReceiverRef = acct2.getCapability(/public/CadenceFungibleTokenTutorialReceiver)
23
.borrow<&ExampleToken.Vault{ExampleToken.Balance}>()
24
?? panic("Could not borrow acct2 vault reference")
25
26
// Log the Vault balance of both accounts and ensure they are
27
// the correct numbers.
28
// Account 0x01 should have 40.
29
// Account 0x02 should have 20.
30
log("Account 1 Balance")
31
log(acct1ReceiverRef.balance)
32
log("Account 2 Balance")
33
log(acct2ReceiverRef.balance)
34
35
// verify that the balances are correct
36
if acct1ReceiverRef.balance != 40.0 || acct2ReceiverRef.balance != 20.0 {
37
panic("Wrong balances!")
38
}
39
40
// Find the public Receiver capability for their Collections
41
let acct1Capability = acct1.getCapability(ExampleNFT.CollectionPublicPath)
42
let acct2Capability = acct2.getCapability(ExampleNFT.CollectionPublicPath)
43
44
// borrow references from the capabilities
45
let nft1Ref = acct1Capability.borrow<&{ExampleNFT.NFTReceiver}>()
46
?? panic("Could not borrow acct1 nft collection reference")
47
48
let nft2Ref = acct2Capability.borrow<&{ExampleNFT.NFTReceiver}>()
49
?? panic("Could not borrow acct2 nft collection reference")
50
51
// Print both collections as arrays of IDs
52
log("Account 1 NFTs")
53
log(nft1Ref.getIDs())
54
55
log("Account 2 NFTs")
56
log(nft2Ref.getIDs())
57
58
// verify that the collections are correct
59
if nft1Ref.getIDs()[0] != 1 || nft2Ref.getIDs().length != 0 {
60
panic("Wrong Collections!")
61
}
62
}

You should see something similar to this output if your accounts are set up correctly. They are in the same state that they would have been in if you followed the Fungible Tokens and Non-Fungible Tokens tutorials in succession:

1
"Account 1 Vault Balance"
2
40
3
"Account 2 Vault Balance"
4
20
5
"Account 1 NFTs"
6
[1]
7
"Account 2 NFTs"
8
[]

Now that your accounts are in the correct state, we can build a marketplace that enables the sale of NFT's between accounts.

Setting up an NFT Marketplace


Every user who wants to sell an NFT will store an instance of a SaleCollection resource in their account storage.

Switch to account 0x03. Open ExampleMarketplace.cdc
With ExampleMarketplace.cdc open, click the Deploy button that appears at the top right of the editor. ExampleMarketplace.cdc should contain the following contract definition:

1
import ExampleToken from 0x01
2
import ExampleNFT from 0x02
3
4
// ExampleMarketplace.cdc
5
//
6
// The ExampleMarketplace contract is a very basic sample implementation of an NFT ExampleMarketplace on Flow.
7
//
8
// This contract allows users to put their NFTs up for sale. Other users
9
// can purchase these NFTs with fungible tokens.
10
//
11
// Learn more about marketplaces in this tutorial: https://docs.onflow.org/cadence/tutorial/08-marketplace-compose
12
//
13
// This contract is a learning tool and is not meant to be used in production.
14
// See the NFTStorefront contract for a generic marketplace smart contract that
15
// is used by many different projects on the Flow blockchain:
16
//
17
// https://github.com/onflow/nft-storefront
18
19
pub contract ExampleMarketplace {
20
21
// Event that is emitted when a new NFT is put up for sale
22
pub event ForSale(id: UInt64, price: UFix64, owner: Address?)
23
24
// Event that is emitted when the price of an NFT changes
25
pub event PriceChanged(id: UInt64, newPrice: UFix64, owner: Address?)
26
27
// Event that is emitted when a token is purchased
28
pub event TokenPurchased(id: UInt64, price: UFix64, seller: Address?, buyer: Address?)
29
30
// Event that is emitted when a seller withdraws their NFT from the sale
31
pub event SaleCanceled(id: UInt64, seller: Address?)
32
33
// Interface that users will publish for their Sale collection
34
// that only exposes the methods that are supposed to be public
35
//
36
pub resource interface SalePublic {
37
pub fun purchase(tokenID: UInt64, recipient: Capability<&AnyResource{ExampleNFT.NFTReceiver}>, buyTokens: @ExampleToken.Vault)
38
pub fun idPrice(tokenID: UInt64): UFix64?
39
pub fun getIDs(): [UInt64]
40
}
41
42
// SaleCollection
43
//
44
// NFT Collection object that allows a user to put their NFT up for sale
45
// where others can send fungible tokens to purchase it
46
//
47
pub resource SaleCollection: SalePublic {
48
49
/// A capability for the owner's collection
50
access(self) var ownerCollection: Capability<&ExampleNFT.Collection>
51
52
// Dictionary of the prices for each NFT by ID
53
access(self) var prices: {UInt64: UFix64}
54
55
// The fungible token vault of the owner of this sale.
56
// When someone buys a token, this resource can deposit
57
// tokens into their account.
58
access(account) let ownerVault: Capability<&AnyResource{ExampleToken.Receiver}>
59
60
init (ownerCollection: Capability<&ExampleNFT.Collection>,
61
ownerVault: Capability<&AnyResource{ExampleToken.Receiver}>) {
62
63
pre {
64
// Check that the owner's collection capability is correct
65
ownerCollection.check():
66
"Owner's NFT Collection Capability is invalid!"
67
68
// Check that the fungible token vault capability is correct
69
ownerVault.check():
70
"Owner's Receiver Capability is invalid!"
71
}
72
self.ownerCollection = ownerCollection
73
self.ownerVault = ownerVault
74
self.prices = {}
75
}
76
77
// cancelSale gives the owner the opportunity to cancel a sale in the collection
78
pub fun cancelSale(tokenID: UInt64) {
79
// remove the price
80
self.prices.remove(key: tokenID)
81
self.prices[tokenID] = nil
82
83
// Nothing needs to be done with the actual token because it is already in the owner's collection
84
}
85
86
// listForSale lists an NFT for sale in this collection
87
pub fun listForSale(tokenID: UInt64, price: UFix64) {
88
pre {
89
self.ownerCollection.borrow()!.idExists(id: tokenID):
90
"NFT to be listed does not exist in the owner's collection"
91
}
92
// store the price in the price array
93
self.prices[tokenID] = price
94
95
emit ForSale(id: tokenID, price: price, owner: self.owner?.address)
96
}
97
98
// changePrice changes the price of a token that is currently for sale
99
pub fun changePrice(tokenID: UInt64, newPrice: UFix64) {
100
self.prices[tokenID] = newPrice
101
102
emit PriceChanged(id: tokenID, newPrice: newPrice, owner: self.owner?.address)
103
}
104
105
// purchase lets a user send tokens to purchase an NFT that is for sale
106
pub fun purchase(tokenID: UInt64, recipient: Capability<&AnyResource{ExampleNFT.NFTReceiver}>, buyTokens: @ExampleToken.Vault) {
107
pre {
108
self.prices[tokenID] != nil:
109
"No token matching this ID for sale!"
110
buyTokens.balance >= (self.prices[tokenID] ?? 0.0):
111
"Not enough tokens to by the NFT!"
112
recipient.borrow != nil:
113
"Invalid NFT receiver capability!"
114
}
115
116
// get the value out of the optional
117
let price = self.prices[tokenID]!
118
119
self.prices[tokenID] = nil
120
121
let vaultRef = self.ownerVault.borrow()
122
?? panic("Could not borrow reference to owner token vault")
123
124
// deposit the purchasing tokens into the owners vault
125
vaultRef.deposit(from: <-buyTokens)
126
127
// borrow a reference to the object that the receiver capability links to
128
// We can force-cast the result here because it has already been checked in the pre-conditions
129
let receiverReference = receiver.borrow()!
130
131
// deposit the NFT into the buyers collection
132
receiverReference.deposit(token: <-self.ownerCollection.borrow()!.withdraw(withdrawID: tokenID))
133
134
emit TokenPurchased(id: tokenID, price: price, owner: self.owner?.address, buyer: receiverReference.owner?.address)
135
}
136
137
// idPrice returns the price of a specific token in the sale
138
pub fun idPrice(tokenID: UInt64): UFix64? {
139
return self.prices[tokenID]
140
}
141
142
// getIDs returns an array of token IDs that are for sale
143
pub fun getIDs(): [UInt64] {
144
return self.prices.keys
145
}
146
}
147
148
// createCollection returns a new collection resource to the caller
149
pub fun createSaleCollection(ownerCollection: Capability<&ExampleNFT.Collection>,
150
ownerVault: Capability<&AnyResource{ExampleToken.Receiver}>): @SaleCollection {
151
return <- create SaleCollection(ownerCollection: ownerCollection, ownerVault: ownerVault)
152
}
153
}

This marketplace contract has resources that function similarly to the NFT Collection that was explained in Non-Fungible Tokens, with a few differences and additions:

  • This marketplace contract has methods to add and remove NFTs, but instead of storing the NFT resource object in the sale collection, the user provides a capability to their main collection that allows the listed NFT to be withdrawn and transferred when it is purchased. When a user wants to put their NFT up for sale, they do so by providing the ID and the price to the listForSale function. Then, another user can call the purchase method, sending their ExampleToken.Vault that contains the currency they are using to make the purchase. The buyer also includes a capability to their NFT ExampleNFT.Collection so that the purchased token can be immediately deposited into their collection when the purchase is made.
  • This marketplace contract stores a capability: pub let ownerVault: Capability<&AnyResource{FungibleToken.Receiver}>. The owner of the sale saves a capability to their Fungible Token Receiver within the sale. This allows the sale resource to be able to immediately deposit the currency that was used to buy the NFT into the owners Vault when a purchase is made.
  • This marketplace contract includes events. Cadence supports defining events within contracts that can be emitted when important actions happen. External apps can monitor these events to know the state of the smart contract.
1
// Event that is emitted when a new NFT is put up for sale
2
pub event ForSale(id: UInt64, price: UFix64, owner: Address?)
3
4
// Event that is emitted when the price of an NFT changes
5
pub event PriceChanged(id: UInt64, newPrice: UFix64, owner: Address?)
6
7
// Event that is emitted when a token is purchased
8
pub event TokenPurchased(id: UInt64, price: UFix64, seller: Address?, buyer: Address?)
9
10
// Event that is emitted when a seller withdraws their NFT from the sale
11
pub event SaleCanceled(id: UInt64, seller: Address?)

This contract has a few new features and concepts that are important to cover:

Events

Events are special values that can be emitted during the execution of a program. They usually contain information to indicate that some important action has happened in a smart contract, such as an NFT transfer, a permission change, or many other different things. Off-chain applications can monitor events using a Flow SDK to know what is happening on-chain without having to query a smart contract directly.

Many applications want to maintain an off-chain record of what is happening on-chain so they can have faster performance when getting information about their users' accounts or generating analytics.

Events are declared by indicating the access level, event, and the name and parameters of the event, like a function declaration:

1
pub event ForSale(id: UInt64, price: UFix64, owner: Address?)

Events cannot modify state at all; they indicate when important actions happen in the smart contract.

Events are emitted with the emit keyword followed by the invocation of the event as if it were a function call.

1
emit ForSale(id: tokenID, price: price, owner: self.owner?.address)

External applications can monitor the blockchain to take action when certain events are emitted.

Resource-Owned Capabilities

We have covered capabilities in previous tutorials, but only the basics. Capabilities can be used for so much more!

As you hopefully understand, capabilites are links to private objects in account storage that specify subset of functionality to expose.

To create a capability, a user typically uses the AuthAccount.link method to create a link to a resource in their private storage, specifying a type to link the capability as:

1
// Create a public Receiver + Balance capability to the Vault
2
// acct is an `AuthAccount`
3
// The object being linked to has to be an `ExampleToken.Vault`,
4
// and the link only exposes the fields in the `ExampleToken.Receiver` and `ExampleToken.Balance` interfaces.
5
acct.link<&ExampleToken.Vault{ExampleToken.Receiver, ExampleToken.Balance}>
6
(/public/CadenceFungibleTokenTutorialReceiver, target: /storage/CadenceFungibleTokenTutorialVault)

Then, users can get that capability if it was created in a public path, borrow it, and access the functionality that the owner specified.

1
// Get account 0x01's PublicAccount object
2
let publicAccount = getAccount(0x01)
3
4
// Retrieve public Vault Receiver reference for the account
5
let acct1Capability = acct.getCapability<&AnyResource{ExampleToken.Receiver}>(/public/CadenceFungibleTokenTutorialReceiver)
6
7
// borrow the reference
8
let acct1ReceiverRef = acct1Capability.borrow()
9
?? panic("Could not borrow a receiver reference to the vault")
10
11
// deposit tokens
12
acct1ReceiverRef.deposit(from: <-tokens)

With the marketplace contract, we are utilizing a new feature of capabilities. Capabilities can be stored anywhere! Lots of functionality is contained within resources, and developers will sometimes want to be able to access some of the functionality of resources from within different resources or contracts.

We store two different capabilities in the marketplace sale collection:

1
/// A capability for the owner's collection
2
access(self) var ownerCollection: Capability<&ExampleNFT.Collection>
3
4
// The fungible token vault of the owner of this sale.
5
// When someone buys a token, this resource can deposit
6
// tokens into their account.
7
access(account) let ownerVault: Capability<&AnyResource{ExampleToken.Receiver}>

If a object like a contract or resource owns a capability, they can borrow a reference to that capability at any time to access that functionality without having to get it from the owner's account every time.

This is especially important if the owner wants to expose some functionality that is only intended for one person, meaning that the link for the capability is not stored in a public path. We do that in this example, because the sale collection stores a capability that can access all of the functionality of the ExampleNFT.Collection. It needs this because it withdraws the specified NFT in the purchase() method to send to the buyer.

It is important to remember that control of a capability does not equal ownership of the underlying resource. You can use the capability to access that resource's functionality, but you can't use it to fake ownership. You need the actual resource with the @ symbol specified to prove ownership.

Additionally, these capabilities can be stored anywhere, but if a user decides that they no longer want the capability to be used, they can revoke it with the AuthAccount.unlink() method so any capabilities that use that link are rendered invalid.

One last piece to consider about capabilities is the decision about when to use them instead of storing the resource directly. This tutorial used to have the SaleCollection directly store the NFTs that were for sale, like so:

1
pub resource SaleCollection: SalePublic {
2
3
/// Dictionary of NFT objects for sale
4
/// Maps ID to NFT resource object
5
/// Not recommended
6
access(self) var forSale: @{UInt64: ExampleNFT.NFT}
7
}

This is a logical way to do it, and illustrates another important concept in Cadence, that resources can own other resources! Check out the Kitty Hats tutorial for a little more exploration of this concept.

In this case however, it doesn't make sense. If a user decides to store their for-sale NFTs in a separate place from their main collection, then, those NFTs are not available to be shown to any app or smart contract that queries the main collection, so it is as if the owner doesn't actually own the NFT! In cases like this, we usually recommend using a capability to the main collection so that the main collection can remain unchanged and fully usable by other smart contracts and apps. This also means that if a for-sale NFT gets transferred by some means other than a purchase, than you need a way to get rid of the stale listing. That is out of the scope of this tutorial though.

Enough explaining! Lets execute some code!

Deploying and using the Marketplace

At this point, we should have an ExampleToken.Vault and an Example.NFT.Collection in both accounts' storage. Account 0x01 should have an NFT in their collection.

You can create a SaleCollection and list account 0x01's token for sale by following these steps:

Open Transaction 4, CreateSale.cdc
Select account 0x01 as the only signer and click the Send button to submit the transaction.

1
// CreateSale.cdc
2
3
import ExampleToken from 0x01
4
import ExampleNFT from 0x02
5
import ExampleMarketplace from 0x03
6
7
// This transaction creates a new Sale Collection object,
8
// lists an NFT for sale, puts it in account storage,
9
// and creates a public capability to the sale so that others can buy the token.
10
transaction {
11
12
prepare(acct: AuthAccount) {
13
14
// Borrow a reference to the stored Vault
15
let receiver = acct.getCapability<&{ExampleToken.Receiver}>(/public/CadenceFungibleTokenTutorialReceiver)
16
17
// borrow a reference to the nftTutorialCollection in storage
18
let collectionCapability = acct.link<&ExampleNFT.Collection>(/private/nftTutorialCollection, target: ExampleNFT.CollectionStoragePath)
19
?? panic("Unable to create private link to NFT Collection")
20
21
// Create a new Sale object,
22
// initializing it with the reference to the owner's vault
23
let sale <- ExampleMarketplace.createSaleCollection(ownerCollection: collectionCapability, ownerVault: receiver)
24
25
// List the token for sale by moving it into the sale object
26
sale.listForSale(tokenID: 1, price: 10.0)
27
28
// Store the sale object in the account storage
29
acct.save(<-sale, to: /storage/NFTSale)
30
31
// Create a public capability to the sale so that others can call its methods
32
acct.link<&ExampleMarketplace.SaleCollection{ExampleMarketplace.SalePublic}>(/public/NFTSale, target: /storage/NFTSale)
33
34
log("Sale Created for account 1. Selling NFT 1 for 10 tokens")
35
}
36
}

This transaction:

  1. Gets a capability for the owners Vault
  2. Creates the SaleCollection, which stores their Vault capability.
  3. Lists the token with ID=1 for sale and sets its price as 10.0.
  4. Stores the sale in their account storage and publishes a capability that allows others to purchase any NFTs for sale.

Let's run a script to ensure that the sale was created correctly.

Open Script 2: GetSaleIDs.cdc
Click the Execute button to print the ID and price of the NFT that account 0x01 has for sale.

1
// GetSaleIDs.cdc
2
3
import ExampleToken from 0x01
4
import ExampleNFT from 0x02
5
import ExampleMarketplace from 0x03
6
7
// This script prints the NFTs that account 0x01 has for sale.
8
pub fun main() {
9
// Get the public account object for account 0x01
10
let account1 = getAccount(0x01)
11
12
// Find the public Sale reference to their Collection
13
let acct1saleRef = account1.getCapability(/public/NFTSale)
14
.borrow<&AnyResource{ExampleMarketplace.SalePublic}>()
15
?? panic("Could not borrow acct2 nft sale reference")
16
17
// Los the NFTs that are for sale
18
log("Account 1 NFTs for sale")
19
log(acct1saleRef.getIDs())
20
log("Price")
21
log(acct1saleRef.idPrice(tokenID: 1))
22
}

This script should complete and print something like this:

1
"Account 1 NFTs for sale"
2
[1]
3
"Price"
4
10

Purchasing an NFT


The buyer can now purchase the seller's NFT by using the transaction in Transaction2.cdc.

Open Transaction 2: PurchaseSale.cdc file
Select account 0x02 as the only signer and click the Send button.

1
// PurchaseSale.cdc
2
3
import ExampleToken from 0x01
4
import ExampleNFT from 0x02
5
import ExampleMarketplace from 0x03
6
7
// This transaction uses the signers Vault tokens to purchase an NFT
8
// from the Sale collection of account 0x01.
9
transaction {
10
11
// Capability to the buyer's NFT collection where they
12
// will store the bought NFT
13
let collectionCapability: Capability<&AnyResource{ExampleNFT.NFTReceiver}>
14
15
// Vault that will hold the tokens that will be used to
16
// but the NFT
17
let temporaryVault: @ExampleToken.Vault
18
19
prepare(acct: AuthAccount) {
20
21
// get the references to the buyer's fungible token Vault and NFT Collection Receiver
22
self.collectionCapability = acct.getCapability<&AnyResource{ExampleNFT.NFTReceiver}>(from: ExampleNFT.CollectionPublicPath)
23
24
let vaultRef = acct.borrow<&ExampleToken.Vault>(from: /storage/CadenceFungibleTokenTutorialVault)
25
?? panic("Could not borrow owner's vault reference")
26
27
// withdraw tokens from the buyers Vault
28
self.temporaryVault <- vaultRef.withdraw(amount: 10.0)
29
}
30
31
execute {
32
// get the read-only account storage of the seller
33
let seller = getAccount(0x01)
34
35
// get the reference to the seller's sale
36
let saleRef = seller.getCapability(/public/NFTSale)!
37
.borrow<&AnyResource{ExampleMarketplace.SalePublic}>()
38
?? panic("Could not borrow seller's sale reference")
39
40
// purchase the NFT the the seller is selling, giving them the capability
41
// to your NFT collection and giving them the tokens to buy it
42
saleRef.purchase(tokenID: 1, recipient: self.collectionCapability, buyTokens: <-self.temporaryVault)
43
44
log("Token 1 has been bought by account 2!")
45
}
46
}

This transaction:

  1. Gets the public account object for account 0x01
  2. Gets the capability to the buyer's NFT receiver
  3. Borrow's a reference to the buyer's stored ExampleToken.Vault
  4. Withdraws the tokens that the buyer will use to purchase the NFT
  5. Gets the reference to the seller's public sale
  6. Calls the purchase function, passing in the tokens and the Collection reference. Then purchase deposits the bought NFT directly into the buyer's collection.

Verifying the NFT Was Purchased Correctly


You can run now run a script to verify that the NFT was purchased correctly because:

  • account 0x01 has 50 tokens and does not have any NFTs for sale or in their collection and account
  • account 0x02 has 10 tokens and an NFT with id=1

To run a script that verifies the NFT was purchased correctly, follow these steps:

Open Script 3: VerifyAfterPurchase.cdc.


Click Execute button VerifyAfterPurchase.cdc should contain the following code:

1
// VerifyAfterPurchase.cdc
2
3
import ExampleToken from 0x01
4
import ExampleNFT from 0x02
5
import ExampleMarketplace from 0x03
6
7
// This script checks that the Vault balances and NFT collections are correct
8
// for both accounts.
9
//
10
// Account 1: Vault balance = 50, No NFTs
11
// Account 2: Vault balance = 10, NFT ID=1
12
pub fun main() {
13
// Get the accounts' public account objects
14
let acct1 = getAccount(0x01)
15
let acct2 = getAccount(0x02)
16
17
// Get references to the account's receivers
18
// by getting their public capability
19
// and borrowing a reference from the capability
20
let acct1ReceiverRef = acct1.getCapability(/public/CadenceFungibleTokenTutorialReceiver)
21
.borrow<&ExampleToken.Vault{ExampleToken.Balance}>()
22
?? panic("Could not borrow acct1 vault reference")
23
24
let acct2ReceiverRef = acct2.getCapability(/public/CadenceFungibleTokenTutorialReceiver)
25
.borrow<&ExampleToken.Vault{ExampleToken.Balance}>()
26
?? panic("Could not borrow acct2 vault reference")
27
28
// Log the Vault balance of both accounts and ensure they are
29
// the correct numbers.
30
// Account 0x01 should have 50.
31
// Account 0x02 should have 10.
32
log("Account 1 Balance")
33
log(acct1ReceiverRef.balance)
34
log("Account 2 Balance")
35
log(acct2ReceiverRef.balance)
36
37
// verify that the balances are correct
38
if acct1ReceiverRef.balance != 50.0 || acct2ReceiverRef.balance != 10.0 {
39
panic("Wrong balances!")
40
}
41
42
// Find the public Receiver capability for their Collections
43
let acct1Capability = acct1.getCapability(ExampleNFT.CollectionPublicPath)
44
let acct2Capability = acct2.getCapability(ExampleNFT.CollectionPublicPath)
45
46
// borrow references from the capabilities
47
let nft1Ref = acct1Capability.borrow<&{ExampleNFT.NFTReceiver}>()
48
?? panic("Could not borrow acct1 nft collection reference")
49
50
let nft2Ref = acct2Capability.borrow<&{ExampleNFT.NFTReceiver}>()
51
?? panic("Could not borrow acct2 nft collection reference")
52
53
// Print both collections as arrays of IDs
54
log("Account 1 NFTs")
55
log(nft1Ref.getIDs())
56
57
log("Account 2 NFTs")
58
log(nft2Ref.getIDs())
59
60
// verify that the collections are correct
61
if nft2Ref.getIDs()[0] != 1 || nft1Ref.getIDs().length != 0 {
62
panic("Wrong Collections!")
63
}
64
65
// Get the public sale reference for Account 0x01
66
let acct1SaleRef = acct1.getCapability(/public/NFTSale)
67
.borrow<&AnyResource{ExampleMarketplace.SalePublic}>()
68
?? panic("Could not borrow acct1 nft sale reference")
69
70
// Print the NFTs that account 0x01 has for sale
71
log("Account 1 NFTs for sale")
72
log(acct1SaleRef.getIDs())
73
if acct1SaleRef.getIDs().length != 0 { panic("Sale should be empty!") }
74
}

If you did everything correctly, the transaction should succeed and it should print something similar to this:

1
"Account 1 Vault Balance"
2
50
3
"Account 2 Vault Balance"
4
10
5
"Account 1 NFTs"
6
[]
7
"Account 2 NFTs"
8
[1]
9
"Account 1 NFTs for Sale"
10
[]

Congratulations, you have successfully implemented a simple marketplace in Cadence and used it to allow one account to buy an NFT from another!

Scaling the Marketplace


A user can hold a sale in their account with these resources and transactions. Support for a central marketplace where users can discover sales is relatively easy to implement and can build on what we already have. If we wanted to build a central marketplace on-chain, we could use a contract that looks something like this:

1
// Marketplace would be the central contract where people can post their sale
2
// references so that anyone can access them
3
pub contract Marketplace {
4
// Data structure to store active sales
5
pub var tokensForSale: {Address: Capability<&SaleCollection>)}
6
7
// listSaleCollection lists a users sale reference in the array
8
// and returns the index of the sale so that users can know
9
// how to remove it from the marketplace
10
pub fun listSaleCollection(collection: Capability<&SaleCollection>) {
11
let saleRef = collection.borrow()
12
?? panic("Invalid sale collection capability")
13
14
self.tokensForSale[saleRef.owner!.address] = collection
15
}
16
17
// removeSaleCollection removes a user's sale from the array
18
// of sale references
19
pub fun removeSaleCollection(owner: Address) {
20
self.tokensForSale[owner] = nil
21
}
22
23
}

This contract isn't meant to be a working or production-ready contract, but it could be extended to make a complete central marketplace by having:

  • Sellers list a capability to their SaleCollection in this contract
  • Other functions that buyers could call to get info about all the different sales and to make purchases.

A central marketplace in an off-chain application is easier to implement because:

  • The app could host the marketplace and a user would simply log in to the app and give the app its account address.
  • The app could read the user's public storage and find their sale reference.
  • With the sale reference, the app could get all the information they need about how to display the sales on their website.
  • Any buyer could discover the sale in the app and login with their account, which gives the app access to their public references.
  • When the buyer wants to buy a specific NFT, the app would automatically generate the proper transaction to purchase the NFT from the seller.

Creating a Marketplace for Any Generic NFT


The previous examples show how a simple marketplace could be created for a specific class of NFTs. However, users will want to have a marketplace where they can buy and sell any NFT they want, regardless of its type. There are a few good examples of generic marketplaces on Flow right now.

  • The Flow team has created a completely decentralized example of a generic marketplace in the NFT storefront repo. This contract is already deployed to testnet and mainnet and can be used by anyone for any generic NFT sale!
  • VIV3 is a company that has a generic NFT marketplace.

Composable Resources on Flow


Now that you have an understanding of how composable smart contracts and the marketplace work on Flow, you're ready to play with composable resources! Check out the Kitty Hats tutorial!