Flow Developers

Flow is a fast, secure, and developer-friendly blockchain built to support the next generation of games, apps, and the digital assets that power them.

Start Here

Composable Smart Contracts: 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.


Open the starter code for this tutorial in the Flow Playground: https://play.onflow.org/b7965bf0-757d-4588-825e-3e7b15c5639a
The tutorial will be asking you to take various actions to interact with this code.

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 will want to be able to buy and sell them with their fungible tokens.

Now that there is a standard 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 it empowers developers to do more with less, which can lead to rapid innovation.

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 reference to 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 how the building blocks of this smart contract work.

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. 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 in their account. Then, users could either provide a reference to their sale to an application that can list it centrally, 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. It also discourages users from letting sales sit for a long time without getting updated or removed because the Flow blockchain will charge state rent for data stored in a user's account for extended periods of time.

Before we start, we need to confirm the state of your accounts.

If you haven't already, please perform the steps in Quick Set-up for Marketplace 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 CheckSetupScript.cdc script to ensure that your accounts are correctly set up:

// CheckSetupScript.cdc

import FungibleToken from 0x01
import NonFungibleToken from 0x02

// This script checks that the accounts are set up correctly for the marketplace tutorial.
//
// Account 0x01: Vault Balance = 40, NFT.id = 1
// Account 0x02: Vault Balance = 20, No NFTs
access(all) fun main() {
    // Get both public account objects
    let account1 = getAccount(0x01)
	let account2 = getAccount(0x02)

    // Get published Vault Receiver references from both accounts
    let acct1ftRef = account1.published[&AnyResource{FungibleToken.Receiver}] ?? panic("missing account 1 vault reference")
    let acct2ftRef = account2.published[&AnyResource{FungibleToken.Receiver}] ?? panic("missing account 2 vault reference")

    // Log the Vault balance of both accounts and ensure they are
    // the correct numbers.
    // Account 0x01 should have 40.
    // Account 0x02 should have 20.

    log("Account 1 Vault Balance")
    log(acct1ftRef.balance)

    log("Account 2 Vault Balance")
    log(acct2ftRef.balance)

    if acct1ftRef.balance != UInt64(40) || acct2ftRef.balance != UInt64(20) {
        panic("Wrong balances!")
    }

    // Get published NFT Collection Receiver references from both accounts
    let acct1nftRef = account1.published[&AnyResource{NonFungibleToken.NFTReceiver}] ?? panic("missing account 1 nft reference!")
	let acct2nftRef = account2.published[&AnyResource{NonFungibleToken.NFTReceiver}] ?? panic("missing account 2 nft reference!")

    // Log the NFT IDs that owned by both accounts.
    // Account 0x01 should have NFT 1
    // Account 0x02 should have none
    log("Account 1 NFTs")
    log(acct1nftRef.getIDs())
	log("Account 2 NFTs")
    log(acct2nftRef.getIDs())

    if acct1nftRef.getIDs()[0] != UInt64(1) || acct2nftRef.getIDs().length != 0 {
        panic("Wrong Balances!")
    }
}

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:

"Account 1 Vault Balance"
40
"Account 2 Vault Balance"
20
"Account 1 NFTs"
[1]
"Account 2 NFTs"
[]

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 a NFT will store an instance of a SaleCollection resource in their account storage.

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

import FungibleToken from 0x01
import NonFungibleToken from 0x02

// Marketplace.cdc
//
// The Marketplace contract is a sample implementation of an NFT Marketplace on Flow.
//
// This contract allows users to put their NFTs up for sale. Other users
// can purchase these NFTs with fungible tokens.
//
// Learn more about marketplaces in this tutorial: https://docs.onflow.org/docs/composable-smart-contracts-marketplace

access(all) contract Marketplace {

    // Event that is emitted when a new NFT is put up for sale
    access(all) event ForSale(id: UInt64, price: UInt64)

    // Event that is emitted when the price of an NFT changes
    access(all) event PriceChanged(id: UInt64, newPrice: UInt64)
    
    // Event that is emitted when a token is purchased
    access(all) event TokenPurchased(id: UInt64, price: UInt64)

    // Event that is emitted when a seller withdraws their NFT from the sale
    access(all) event SaleWithdrawn(id: UInt64)

    // Interface that users will publish for their Sale collection
    // that only exposes the methods that are supposed to be public
    //
    access(all) resource interface SalePublic {
        access(all) fun purchase(tokenID: UInt64, recipient: &AnyResource{NonFungibleToken.NFTReceiver}, buyTokens: @FungibleToken.Vault)
        access(all) fun idPrice(tokenID: UInt64): UInt64?
        access(all) fun getIDs(): [UInt64]
    }

    // SaleCollection
    //
    // NFT Collection object that allows a user to put their NFT up for sale
    // where others can send fungible tokens to purchase it
    //
    access(all) resource SaleCollection: SalePublic {

        // Dictionary of the NFTs that the user is putting up for sale
        access(all) var forSale: @{UInt64: NonFungibleToken.NFT}

        // Dictionary of the prices for each NFT by ID
        access(all) var prices: {UInt64: UInt64}

        // The fungible token vault of the owner of this sale.
        // When someone buys a token, this resource can deposit
        // tokens into their account.
        access(account) let ownerVault: &AnyResource{FungibleToken.Receiver}

        init (vault: &AnyResource{FungibleToken.Receiver}) {
            self.forSale <- {}
            self.ownerVault = vault
            self.prices = {}
        }

        // withdraw gives the owner the opportunity to remove a sale from the collection
        access(all) fun withdraw(tokenID: UInt64): @NonFungibleToken.NFT {
            // remove the price
            self.prices.remove(key: tokenID)
            // remove and return the token
            let token <- self.forSale.remove(key: tokenID) ?? panic("missing NFT")
            return <-token
        }

        // listForSale lists an NFT for sale in this collection
        access(all) fun listForSale(token: @NonFungibleToken.NFT, price: UInt64) {
            let id = token.id

            // store the price in the price array
            self.prices[id] = price

            // put the NFT into the the forSale dictionary
            let oldToken <- self.forSale[id] <- token
            destroy oldToken

            emit ForSale(id: id, price: price)
        }

        // changePrice changes the price of a token that is currently for sale
        access(all) fun changePrice(tokenID: UInt64, newPrice: UInt64) {
            self.prices[tokenID] = newPrice

            emit PriceChanged(id: tokenID, newPrice: newPrice)
        }

        // purchase lets a user send tokens to purchase an NFT that is for sale
        access(all) fun purchase(tokenID: UInt64, recipient: &AnyResource{NonFungibleToken.NFTReceiver}, buyTokens: @FungibleToken.Vault) {
            pre {
                self.forSale[tokenID] != nil && self.prices[tokenID] != nil:
                    "No token matching this ID for sale!"
                buyTokens.balance >= (self.prices[tokenID] ?? UInt64(0)):
                    "Not enough tokens to by the NFT!"
            }

            // get the value out of the optional
            if let price = self.prices[tokenID] {
                self.prices[tokenID] = nil
                
                // deposit the purchasing tokens into the owners vault
                self.ownerVault.deposit(from: <-buyTokens)

                // deposit the NFT into the buyers collection
                recipient.deposit(token: <-self.withdraw(tokenID: tokenID))

                emit TokenPurchased(id: tokenID, price: price)
            }
        }

        // idPrice returns the price of a specific token in the sale
        access(all) fun idPrice(tokenID: UInt64): UInt64? {
            return self.prices[tokenID]
        }

        // getIDs returns an array of token IDs that are for sale
        access(all) fun getIDs(): [UInt64] {
            return self.forSale.keys
        }

        destroy() {
            destroy self.forSale
        }
    }

    // createCollection returns a new collection resource to the caller
    access(all) fun createSaleCollection(ownerVault: &AnyResource{FungibleToken.Receiver}): @SaleCollection {
        return <- create SaleCollection(vault: ownerVault)
    }
}
 

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 these functions also involve setting and removing a price. When a user wants to put their NFT up for sale, they do so by depositing it into the collection with the listForSale function. Then, another user can call the purchase method, sending their Vault that contains the currency they are using to make the purchase. The buyer also includes a reference to their NFT Collection so that the purchased token can be immediately deposited into their collection when the purchase is made.
  • This marketplace contract stores a reference: pub let ownerVault: &FungibleToken.Receiver.
    The owner of the sale saves a reference 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.
    access(all) event ForSale(id: UInt64, price: UInt64)
    access(all) event PriceChanged(id: UInt64, newPrice: UInt64)
    access(all) event TokenPurchased(id: UInt64, price: UInt64)
    access(all) event SaleWithdrawn(id: UInt64)

Events are declared by indicating the access level, event, and the name and parameters of the event, like a function declaration. 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. External applications can monitor the blockchain to take action when certain events are emitted.

At this point, we should have a fungible token Vault and a 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 Transaction1.cdc
  • Select account 0x01 as the only signer and click the Send button to submit the transaction.
// Transaction1.cdc

import FungibleToken from 0x01
import NonFungibleToken from 0x02
import Marketplace from 0x03

transaction {

    prepare(acct: AuthAccount) {

        // get a reference to the signer's vault Receiver
        let ownerVault = acct.published[&AnyResource{FungibleToken.Receiver}] ?? panic("No receiver reference!")

        // create a new Sale object, 
        // initializing it with the reference to the owner's vault
        let sale: @Marketplace.SaleCollection <- Marketplace.createSaleCollection(ownerVault: ownerVault)

        // withdraw the NFT from their collection that they want to sell
        // and move it into the transaction's context
        let token <- acct.storage[NonFungibleToken.Collection]?.withdraw(withdrawID: 1) ?? panic("missing token!")

        // list it for sale by moving it into the sale object
        sale.listForSale(token: <-token, price: 10)

        // store the sale object in the account storage 
        let oldSale <- acct.storage[Marketplace.SaleCollection] <- sale
        destroy oldSale

        // create a public reference to the sale 
        // so that others can call its methods
        acct.published[&AnyResource{Marketplace.SalePublic}] = &acct.storage[Marketplace.SaleCollection] as &AnyResource{Marketplace.SalePublic}
      
        log("Sale Created for account 1. Selling NFT 1 for 10 tokens")
    }
}

This transaction:

  1. Retrieves the reference to the owners Vault
  2. Creates the SaleCollection, which stores their Vault reference.
  3. Withdraws the owner's token from their normal collection
  4. Lists that token for sale and sets its price
  5. Stores the sale in their account storage and publishes a reference that allows others to purchase any NFTs for sale.

Lets run a script to ensure that the sale was created correctly.

  • Open Script2.cdc
  • Click the Execute button to print the ID and price of the NFT that account 0x01 has for sale
// Script2.cdc

import FungibleToken from 0x01
import NonFungibleToken from 0x02
import Marketplace from 0x03

pub fun main() {
    let account1 = getAccount(0x01)

    let acct1saleRef = account1.published[&AnyResource{Marketplace.SalePublic}] ?? nil

    log("Account 1 NFTs for sale")
    log(acct1saleRef?.getIDs())
    log("Price")
    log(acct1saleRef?.idPrice(tokenID: 1))
}

This script should complete and print something like this:

"Account 1 NFTs for sale"
[1]
"Price"
10

Purchasing an NFT


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

  • Open the Transaction2.cdc file
  • Select account 0x02 as the only signer and click the Send button
// Transaction2.cdc

import FungibleToken from 0x01
import NonFungibleToken from 0x02
import Marketplace from 0x03

// This transaction uses the signers Vault tokens to purchase an NFT
// from the Sale collection of account 0x01.
transaction {

    // reference to the buyer's NFT collection where they
    // will store the bought NFT
    let collectionRef: &AnyResource{NonFungibleToken.NFTReceiver}

    // Vault that will hold the tokens that will be used to
    // but the NFT
    let temporaryVault: @FungibleToken.Vault

    prepare(acct: AuthAccount) {

        // get the references to the buyer's fungible token Vault and NFT Collection Receiver
        self.collectionRef = acct.published[&AnyResource{NonFungibleToken.NFTReceiver}] ?? panic("missing collection reference!")
        let vaultRef = &acct.storage[FungibleToken.Vault] as &FungibleToken.Vault
    
        // withdraw tokens from the buyers Vault
        self.temporaryVault <- vaultRef.withdraw(amount: 10)
    }

    execute {
        // get the read-only account storage of the seller
        let seller = getAccount(0x01)

        // get the reference to the seller's sale
        let saleRef = seller.published[&AnyResource{Marketplace.SalePublic}] ?? panic("missing sale reference!")

        // purchase the NFT the the seller is selling, giving them the reference
        // to your NFT collection and giving them the tokens to buy it
        saleRef.purchase(tokenID: 1, recipient: self.collectionRef, buyTokens: <-self.temporaryVault)

        log("Token 1 has been bought by account 2!")
    }
}
 

This transaction:

  1. Gets the public account object for account 0x01
  2. Gets the references to the buyer's stored resources
  3. Withdraws the tokens that the buyer will use to purchase the NFT
  4. Gets the reference to the seller's public sale
  5. Calls the purchase function, passing in the tokens and the Collection reference. Then purchase deposits the bought NFT directly into the buyers 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 the Script3.cdc file
  • Click Execute button
    Script3.cdc should contain the following code:
// Script3.cdc

import FungibleToken from 0x01
import NonFungibleToken from 0x02
import Marketplace from 0x03

// This script checks that the Vault balances and NFT collections are correct
// for both accounts.
//
// Account 1: Vault balance = 50, No NFTs
// Account 2: Vault balance = 10, NFT ID=1
pub fun main() {
    // Get both public account objects
    let account1 = getAccount(0x01)
	  let account2 = getAccount(0x02)

    // Get published Vault Receiver references from both accounts
    let acct1ftRef = account1.published[&AnyResource{FungibleToken.Receiver}] ?? panic("missing account 1 vault reference")
    let acct2ftRef = account2.published[&AnyResource{FungibleToken.Receiver}] ?? panic("missing account 2 vault reference")

    // Log the Vault balance of both accounts and ensure they are
    // the correct numbers.
    // Account 0x01 should have 50.
    // Account 0x02 should have 10.

    log("Account 1 Vault Balance")
    log(acct1ftRef.balance)

    log("Account 2 Vault Balance")
    log(acct2ftRef.balance)

    if acct1ftRef.balance != UInt64(50) || acct2ftRef.balance != UInt64(10) {
        panic("Wrong balances!")
    }

    // Get published NFT Collection Receiver references from both accounts
    let acct1nftRef = account1.published[&AnyResource{NonFungibleToken.NFTReceiver}] ?? panic("missing account 1 nft reference!")
	  let acct2nftRef = account2.published[&AnyResource{NonFungibleToken.NFTReceiver}] ?? panic("missing account 2 nft reference!")

    // Log the NFT IDs that owned by both accounts.
    // Account 0x01 should have none
    // Account 0x02 should have NFT 1
    log("Account 1 NFTs")
    log(acct1nftRef.getIDs())
	  log("Account 2 NFTs")
    log(acct2nftRef.getIDs())

    if acct1nftRef.getIDs().length != 0 || acct2nftRef.getIDs()[0] != UInt64(1) {
        panic("Wrong NFTs in collection")
    }

    // Get the public sale reference for Account 0x01
    let acct1SaleRef = account1.published[&AnyResource{Marketplace.SalePublic}] ?? panic("missing account 1 Sale reference!")

    // Print the NFTs that account 0x01 has for sale
    log("Account 1 NFTs for sale")
    log(acct1SaleRef.getIDs())
    if acct1SaleRef.getIDs().length != 0 { panic("Sale should be empty!") }
}

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

"Account 1 Vault Balance"
50
"Account 2 Vault Balance"
10
"Account 1 NFTs"
[]
"Account 2 NFTs"
[1]
"Account 1 NFTs for Sale"
[]

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:

// Marketplace would be the central contract where people can post their sale
// references so that anyone can access them
access(all) contract Marketplace {
    // Data structure to store active sales
    access(all) var tokensForSale: [&SaleCollection]

    // listSaleCollection lists a users sale reference in the array
    // and returns the index of the sale so that users can know
    // how to remove it from the marketplace
    access(all) fun listSaleCollection(collection: &SaleCollection): Int {
        self.tokensForSale.append(collection)
        return (self.tokensForSale.length - 1)
    }

    // removeSaleCollection removes a user's sale from the array
    // of sale references
    access(all) fun removeSaleCollection(index: Int) {
        self.tokensForSale.remove(at: index)
    }

}

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 reference 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. Support for this feature is in development and will be shared soon.

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! Go to Composable Resources: Kitty Hats to learn more.

Updated 6 days ago



Composable Smart Contracts: Marketplace


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.