Flow: How to Create an NFT Marketplace with Filebase + Flow
Learn how to create an NFT marketplace using Filebase and Flow.
NFT marketplaces like OpenSea are skyrocketing in value right now due to the rise in popularity of NFTs and the revenue generated by being a marketplace for users to buy and sell NFTs. Most marketplaces take a percentage of the NFTโs sale price, similar to other ecommerce marketplaces such as Etsy or Ebay.
But what if you create your own NFT marketplace for your NFT collection? You can cut out the middleman and avoid paying any fees associated with listing your NFTs on a third party marketplace.
What Youโll Learn
In this guide, weโll go over how to create your own NFT marketplace app using the Flow blockchain and Filebase for storage. You will learn:
How to create smart contracts with Cadence Language.
How to mint tokens and store the metadata in a Filebase bucket.
How to authenticate user wallets.
How to transfer tokens.
Once you've completed this guide, you'll have all the backend fundamentals of an NFT marketplace that you can use to develop a frontend user interface to create a full marketplace.
Terminology
Letโs go over a few terms before we get started. Flow uses the Cadence Language for creating smart contracts, tracking transactions, and running scripts.
A blockchain is a distributed, digital ledger that tracks and records transactions and the ownership of a resource.
A resource can be any object or item, such as currency or goods, both physical and digital. In this case, we will be using cryptocurrency. Resources are stored in user accounts and are accessible through access control properties that are defined in a smart contract.
An interface defines the behaviors or abilities of a resource.
An account owns resources or has access to the resources. Each account keeps a personal ledger of its spending or transferring of resources.
A contract is a ruleset used to govern actions. Actions that break a contract are punishable and have repercussions. In our guide, contracts are the initial program that gets deployed to a blockchain that initiates your applicationโs ability to access resources you create on the blockchain.
A script in this guide refers to a Cadence program used to read blockchain information and availability. A common script is a blockchain explorer that queries the current state of the blockchain.
Now that we have a basic understanding of these terms, letโs get started building out the NFT marketplace app.
1. First, we need an image to use as an NFT. Weโll start by uploading an image to Filebase for us to use.
To do this, navigate to console.filebase.com. If you donโt have an account already, sign up, then log in.
2. Select โBucketsโ from the left side bar menu, or navigate to console.filebase.com/buckets.
Select โCreate Bucketโ in the top right corner to create a new bucket for your NFTs.
3. Enter a bucket name and choose the IPFS storage network to create the bucket.
Bucket names must be unique across all Filebase users, be between 3 and 63 characters long, and can contain only lowercase characters, numbers, and dashes.
4. Next, select the bucket from your list of buckets, then select โUploadโ in the top right corner to upload an image file.
5. Select an image to be uploaded. Once uploaded, it will be listed in the bucket.
6. Click on your uploaded object to display the metadata for the object.
Take note of the IPFS CID. We will reference this later.
7. Next, open your command prompt. We need to create a new React app with the following command:
npx create-react-app nftmarketplace; cd nftmarketplace
Then we need to initialize a Flow project with the command:
flow init
This will result in a new React project with the file flow.json
stored inside. This file is important because it contains configuration information for our app such as where our contracts will be stored.
8. Add the following lines to the flow.json
file to configure the storage location for our contracts and the deployment app information.
flow.json
file to configure the storage location for our contracts and the deployment app information. Do not remove the other lines that are in the file:
9. Next we need to create directories for our contracts, scripts, and transactions.
Create these directories with the following command:
mkdir -p src/flow/{contract,transaction,script}
Then in each directory, create a Cadence file with the following names:
contract/nftMarketplace.cdc
transaction/mintToken.cdc
script/getTokenIds.cdc
10. Open the contract/nftMarketplace.cdc
file in your favorite code editor or IDE.
contract/nftMarketplace.cdc
file in your favorite code editor or IDE. Copy and paste the following code into the file:
With this code we have declared a dictionary for storing the variable owners. This variable will be used to keep track of all current token owners globally in our marketplace.
11. Now letโs add the NFTReceiver interface code to define the capabilities of an NFT receiver.
Add the following code to the nftMarketplace.cdc
file:
In this code, the withdraw(id: UInt64): @NFT
method takes in the id of an NFT and in return withdraws a token with the type @NFT
.
The deposit(token: @NFT)
method deposits the token to the current NFTReceiver
.
The getTokenMetadata(id: UInt64) : {String : String}
method takes the token ID and its associated metadata and returns the ID and metadata as a dictionary.
The updateTokenMetadata(id: UInt64, metadata: {String: String})
updates the targetโs NFT metadata.
12. Next weโll create the NFTCollection
resource where NFTs will be deposited to or withdrawn from.
NFTCollection
resource where NFTs will be deposited to or withdrawn from. Copy and paste the following code into your file:
This code creates a dictionary called ownedNFTs
that can be edited. This dictionary works by mapping the token ID to the NFT resource.
Then in the constructor method, the code creates an empty directory called ownedNFTs
that will contain any deposited NFTs, and includes a destructor method that will withdraw any sold NFTs.
13. Now letโs add the NFTMinter
resource. This resource will enable our app to mint the NFT tokens.
NFTMinter
resource. This resource will enable our app to mint the NFT tokens. Copy and paste the following code into your file:
14. Lastly, we need a constructor method to initialize our contract when it gets deployed.
Copy and paste the following code into your file:
This last bit of code uses the three domain namespaces that are used by Cadence. These are:
/public: This namespace is accessible by any account that can interact with the contract.
/private: This namespace is only accessible by accounts that are given access to the contract.
/storage: This namespace is only accessible to the owner of the account.
All together, your contract should look like this:
15. Now letโs deploy the contract. First weโll need to start the flow emulator in our command prompt:
flow emulator
This will return information, such as the FlowServiceAccount
and the port of your local HTTP server. Take note of these values.
16. Open another command prompt window and make sure you are in your project directory.
Use the following command to deploy your contract:
flow project deploy
You should receive the following output confirming your contract was successfully deployed:
17. Now itโs time to create the transaction responsible for minting tokens.
This is one of the most important pieces of any NFT app. Without this, the NFTs wonโt be created to be sold or traded.
Open the mintToken.cdc
file that we created earlier. Copy and paste the following code into the file:
There are a few things in this code you will need to replace:
In the first line, replace the address to import your contract from. This will be the Flow address that you recorded when you ran the Flow emulator.
In the execute section, there are some metadata fields. Edit these to reflect the desired metadata for your NFT. In our example, the NFT has a name and a type metadata field. Add or remove as many metadata fields as desired.
Replace the URI metadata CID with your Filebase object IPFS CID that you recorded at the beginning of this guide.
18. Now letโs send this transaction to the flow emulator that is running and mint a token.
This transaction requires metadata to mint the NFT, so weโll pass the metadata to the code with the following syntax:
flow transactions send src/flow/transaction/mintToken.cdc {}
This command should return a message that says that the transaction has been โsealedโ. This means that the transaction was successful.
Youโve just minted your first NFT! For our example, we created an NFT with the name โAppleโ and the type of โFruitโ with the image we uploaded to Filebase.
19. Next, we need to create the TransferToken
transaction. This transaction allows NFTs to be transferred between different users.
TransferToken
transaction. This transaction allows NFTs to be transferred between different users. This is vital to a marketplace, since what good is a marketplace where goods canโt be exchanged?
Since so far weโve only used our Flow emulator account, weโll need to create another account to test this transaction with. Start by getting a key pair for a new account with the command:
flow keys generate
To keep these keys safe and referenceable, create a new file called .keys.json
and paste the keys that were returned from the generate command.
20. Then letโs create an account using these keys. Run the following command, but replace PUBLIC_KEY
with the public key you just generated.
PUBLIC_KEY
with the public key you just generated.flow accounts create โkey PUBLIC_KEY โsigner emulator-account
Take note of the address that is returned, then open the flow.json
file and add an entry under โaccountsโ for your test account. Replace PRIVATE_KEY
with the test accountโs private key.
Like the mintToken.cdc
file, you will need to replace the address to import your contract from. This will be the Flow address that you recorded when you ran the Flow emulator.
21. Now letโs send this transaction with the following command:
flow transactions send src/flow/transaction/initCollection.cdc โsigner test-account
Now that our test account has been initialized, letโs create our transfer transaction to transfer an NFT from our emulator account to our test account.
22. Create another Cadence file in the transactions directory named transferToken.cdc
.
transferToken.cdc
. Copy and paste the following code into this file:
This code is a sequel to the initial minting process code. This code moves the token stored in a source accountโs NFTCollection
by receiving the destination accountโs token and calling the withdraw(id: UInt64)
and deposit(token: @NFT)
.
23. Letโs run this command to test our code.
This command needs the TokenID
of the NFTs to move and the destination address. TokenID
s are unsigned integers starting from 1:
flow transactions send src/flow/transaction/transferToken.cdc 1 0x01cf0e2f2f715450
You just withdrew and deposited your NFT into the test account!
24. Now that we can send transactions, we need scripts that can query the state of the blockchain.
To start, letโs query the NFT Token that we just transferred to our test account to confirm it was successfully received.
In your scripts directory, create the file named getTokenOwner.cdc
with the following content:
25. Another script to query the blockchain that we should have is the getTokenMetadata.cdc script.
This script will return the NFTโs metadata, which in this case should be Apple, Fruit, and the Filebase image URL.
Create a new file in the scripts directory called getTokenMetadata.cdc
with the following content:
26. Then execute the script with the following command. This command also requires the TokenID:
flow scripts execute src/flow/script/getTokenMetadata.cdc 1
Now we have all the back end fundamentals for creating a marketplace! From here, you can create a user interface for the front end of your marketplace using Reactjs that references these scripts, or you can continue to use the scripts by themselves to mint and transfer NFTs.
Last updated