Building a Simple Full-Stack Market-Place App With Blockchain
•
Leon Ross
Using blockchain technology to tokenise real world assets
Unless you’ve been living under a rock, you’ll have heard of blockchain. It’s the technology behind Bitcoin, De-centralised Finance, NFTs, and has a market cap in the trillions of dollars. Understandably, some folks view anything blockchain with scepticism, but that’s a normal reaction to any disruptive innovation. At Adapptor we’re working alongside Hatchd with clients to build apps on blockchain. Regardless of whether or not you’re planning a project involving blockchain, being conversant in its fundamentals is becoming a requirement for CTOs and developers. To that end, this post is the first in a series describing the creation of a simple marketplace app built on blockchain. The series will cover how to create, test, and deploy tokens, and how to build a simple marketplace app that makes use of our tokens. Along the way I’ll point out tips and tricks for developers.
Just quickly, you might be wondering why all the hoopla around blockchain. A deep dive into the benefits of blockchain fundamentals is beyond the scope of this series, and there are many, many, good resources.
But the TLDR is:
Cost reduction and efficiency — due to the removal of intermediaries
Security — from decentralisation and consensus-based updates
Traceability — through the immutable public record that is the chain
If your domain or app would benefit from one or more of these properties, it might pay you to investigate blockchain, and find out why it beats the internet as the fastest growing technology in history in terms of user adoption.
Sidebar: Continuing from Perry’s blog
I have to give a shout out to Perry Fardella over at our sister company, Hatchd. We’ll be expanding on his excellent blog series, Building a full-stack Decentralised Application on the Ethereum blockchain. He runs you through environment setup using VSCode, installing the required dependencies, and creating your first smart contract with unit tests. I encourage you to go and read parts One and Two before continuing here.
What Are We Building?
In this blog series we want to use blockchain technology to develop a demo application to allow us to tokenise real world assets and transfer ownership of assets, by trading them in a token marketplace.
In the first part of this series we’ll create a smart contract called TokenController that will allow us to create and destroy our own tokens. (I’ll explain what a token is below.)
In the second part of this series, we’ll create another smart contract called TokenMarket. This will allow users to trade their tokens at an agreed price. Sellers can list their tokens and when a matching buy order is received with the correct payment, the tokens are automatically forwarded to the buyer and the payment is disbursed to the seller.
Lastly, we will deploy our smart contracts to the blockchain and build a front-end to allow users to authenticate with their wallet, view their token balances, view the marketplace listings, and interact with the smart contracts to create and trade tokens.
Tokens For All
What is a token? A token is simply a representation of something in the blockchain. It could represent money, shares, loyalty or bonus points, virtual assets, or even a title of ownership of real world assets. A token contract is used to create tokens and is essentially a mapping of addresses to balances, including some functions to add and subtract from those balances.
Token Standards
In the world of Ethereum blockchain there are a few flavours of token expressed by various token standards, and each offers different features and abilities fit for different purposes.
You may have heard of the ERC20 standard. ERC20 is the original and most widely used token standard for fungible assets. ERC721 was later developed to address the need for non-fungible tokens and has given rise to the NFT trading phenomenon. ERC1155 followed combining the ability to mint fungible and non-fungible tokens in a single contract. It also supports batch operations for increased gas efficiency (where ‘gas’ refers to the cost of transacting on the blockchain). When transferring tokens, ERC1155 will automatically check that the receiving contract implements the ERC1155Receiver interface, avoiding the possibility of losing your tokens by sending them to a contract that doesn’t have the required functionality to deal with the tokens.
Create an ERC1155 TokenController Contract
Now let’s create a new contract to manage our tokens. OpenZeppelin is a fantastic resource for developers that provides a library of reusable and composable contracts that are well tested and use industry standards. As we don’t want to reinvent the wheel, we’ll use the OpenZeppelin contracts library to create a contract that implements the ERC1155 standard. We can use the contracts wizard to compose the contract we want. Select the options:
ERC1155
Name: TokenController
Mintable
SupplyTracking
Ownable
The wizard produces Solidity code, which is an object-oriented language for developing smart contracts on Ethereum, so this syntax will look familiar to developers. Now we can simply copy the code into our TokenController.sol file in VSCode. Create a new file contracts/TokenController.sol and paste in the code.
Then install the dependencies by running:
Let’s look at the code:
Here we define our TokenController contract which we can think of as defining a class that extends ERC1155, Ownable and ERC1155Supply, which have been imported from the @openzeppelin/contracts library.
ERC1155.sol exposes methods including:
mint(address, id, amount) to create tokens
setURI(newUri) to set the metadata location
balanceOf(address, id) check the address’s balance for token id
setApprovalForAll(address, approved) to give operator permissions
Ownable.sol exposes the “onlyOwner” modifier. Any function using onlyOwner will throw an error if called by any account other than the owner. Ownable also exposes functions transferOwnership(address newOwner) and renounceOwnership().
ERC1155Supply.sol exposes totalSupply(id) to track our token supplies across all addresses and will be updated whenever we create or destroy tokens.
Testing TokenController
Let’s write some tests for our TokenController. Create a new file test/TokenController.js
Each test will execute the beforeEach block to deploy the TokenController contract to our development environment.
Our first test will mint some tokens and check that the balance is updated correctly.
Test it should mint tokens.
Test that transferring tokens updates the token balance.
Test ERC1155Supply.sol is correctly tracking the total token supply.
Test that only the owner can mint (what the onlyOwner modifier means).
Not Everything is on Chain
While tokens are at the core of the marketplace implementation, it would be prohibitively expensive to store all information related to a token on chain. Instead, each token has a URI which points to its metadata, such as a name, image URI, details of an agreement, or title of ownership.
This metadata should be immutable. If I were to store the metadata on a traditional web server, the owner of the server could theoretically alter the data and change the meaning of the token, or the terms of a contract. To make our metadata immutable we can use a decentralised data storage provider, such as IPFS.io or Arweave.org. This will allow us to store the token metadata in a way that can not be changed.
We should also make sure to lock down the setUri() function to ensure no one can change the metadata location the token is pointing to after it has been minted.
Conclusion
In this post we have created our TokenController smart contract and written tests that show that the contract owner can mint new tokens on the Ethereum blockchain, transfer tokens, and track the overall token supply. This token technology can be applied to many use cases, such as minting your own NFTs and listing them on an NFT marketplace like Opensea.io, trading and tracking livestock or seafood from farm to plate, peer-to-peer electricity trading like our friends at Powerledger.io, or implementing your own loyalty rewards program.
Stay tuned for the next part of this series, where I’ll explain how to build a simple marketplace smart contract that connects buyers and sellers to trade their tokens. Until then, happy coding 💻😎