DeFi and Yield Farming Explained

DeFi and Yield Farming have been the most popular buzzwords among the crypto community in recent months. Some DeFi tokens can skyrocket to more than 10K USD in just a few days but drop back to near zero also in a matter of days! Besides that, people in the crypto community are talking about yield farming instead of mining nowadays, most of you might scratch your head and wonder what the heck is that? Skeptics might challenge that DeFi is merely hype, but the total value of digital assets locked in the DeFi platforms has reached an astounding $10 billion(as seen in the figure below), thus it has created huge DeFi economics(Should I call it DeFiconomics?).

Source: https://defipulse.com/

To help you understand DeFi and Yield Farming, I shall try my best to explain these two concepts in a nutshell.

What is DeFi?

The word DeFi stands for decentralized finance, which means operating financial applications on a decentralized platform such as blockchain. It is the new financial architecture that leverages decentralized networks and decentralized technologies such as smart contracts to transform old financial products into trustless and transparent protocols that run without intermediaries. DeFi has a popular nickname ‘Money Lego’ because of the process of DeFi development like building legos where different components of a system can easily connect and interoperate.

DEFI Features

DeFi has unique features compared to CenFi (Centralised finance) and claimed to be able to provide more convenient and seamless services, particularly for the underserved people. Here are some of the features:

  • P2P- Transactions are performed on peer to peer basis without the need for intermediaries
  • No need KYC- Anyone can open an account with a DeFi platform anytime and easily without going through the tedious and painful process of KYC
  • No one holds your digital assets- DeFi platforms are non-custodian in nature which means they do not hold your private keys, you have full control of your own digital assets.

DeFi Products

Popular DeFi products include decentralized exchanges, loan and savings markets, tokenized physical assets such as gold, derivatives, forecasting/betting markets, payment networks, insurance and more.

Loan and Savings Markets

DeFi loan and savings markets allow you to lend, borrow, or deposit money in a platform. Among the popular loan and savings platforms are Compound, Aave, MakerDAO, Dharma, dYdX, and more.

Compound

Compound is a protocol on the Ethereum blockchain that creates a money market, which is a group of assets with algorithmically earned interest rates, based on supply and demand for those assets. The asset provider (and borrower) interacts directly with the protocol, earning (and paying) floating interest rates, without having to negotiate conditions such as maturity, interest rates, or collateral with peers or business partners.

MakerDAO

MakerDAO is a smart contract that allows users to open Protected Debt Positions, or CDP (Collateralized Debt Positions). Users deposit ETH as collateral and can mint or borrow tokens called DAI. DAI is a stablecoin linked to the US dollar.

Borrowers pay an annual interest rate called the stability fee to mint a new DAI. After the debt is repaid, the DAI is burned along with the stability fee owed in the MKR Maker token. Stability charges prevent users from overspending the amount of DAI supply in excess.

Aave

Aave is a decentralized non-custodial money market protocol in which users can participate as depositors(lenders) or borrowers. Depositors provide liquidity to the market to earn passive income, while borrowers can borrow in an overcollateralized or undercollateralized manner.

Dharma

Dharma is an open-source lending and savings account built on Compound which is characterized by its ease of use and simplicity. Dharma features a Smart Wallet is a non-custodial that automatically lends out any DAI or USDC it receives on Compound and generates a variable interest rate. Dharma requires users to have a fully verified Coinbase Account in order to create a new account.

dYdX

dYdX is a non-custodial trading platform on Ethereum that caters to more experienced traders. The dYdX platform allows users to lend, borrow, or margin trade any supported asset like ETH, Dai, USDC, and more. Interest rates vary by asset and adjust with supply and demand. Interest continuously accrues and is paid to lenders, minus 5% which is set aside for dYdX’s insurance fund.

All borrowed funds must initially be collateralized with 125% of their value. Liquidation occurs if that ratio falls below 115% and comes with a 5% penalty. Traders can take leveraged long positions of up to 5x their collateral’s value and 4x for shorts. Loans and margin trades can remain open for a max of 28 days, after which they are automatically closed out with a 1% expiration fee.

Decentralized Exchange

Decentralized exchanges or DEX are like stock exchanges but run by smart contracts on the Ethereum blockchain. While both allow you to trade assets, decentralized exchanges only trade cryptocurrencies and do not require centralized authorities to operate. Some of the popular exchanges are Uniswap, SushiSwap, Bancor, Kyber, Balancer, and more.

Uniswap

Uniswap is a decentralized ERC-20 token exchange that supports Ethereum and ERC20 tokens. The advantage of Uniswap is that you can exchange ETH with other ERC-20 tokens in a decentralized way. No companies involved, no KYC, and no intermediaries.

The Uniswap platform is unique in that it does not use an order book to derive the price of an asset or to match buyers and sellers of tokens. Instead, Uniswap uses the Liquidity Pool which comprises a group of tokens managed by smart contracts. The liquidity pool ensures enough tokens for users to exchange with each other using Ethereum as a channel.

Bancor

Bancor is a protocol on Ethereum for non-custodial token exchange using pooled liquidity. Bancor does not use order books, Instead, it uses an algorithmic market-making mechanism through the use of Smart Tokens. This will ensure liquidity and accurate prices by maintaining a fixed ratio among connected tokens and adjusting their own supply.

The Bancor platform has expanded beyond Ethereum to offer an exchange with EOS and POA Network. It also features a native token known as BNT( Bancor Network Token), which serves as a Smart Token hub that connects all other tokens in the Bancor Network, enabling instant trades among any asset supported by Bancor.

Kyber

Kyber Network is an on-chain liquidity protocol that allows the token holders to contribute liquidity known as reserves. The Kyber Network offers multiple types of reserves that exist in smart contracts. Besides that, Kyber does not use order books; when a user initiates a trade, Kyber returns the best price across all reserves.

The Kyber Network can be integrated into dApps to enhance user experience. In addition, Vendors and wallets can also use the Kyber Network to allow users to transact using their token of choice in a single transaction. Moreover, Kyber has a native token called KNC which is used to align ecosystem incentives. Holders can stake KNC to participate in governance and earn rewards, reserve managers pay fees and receive rebates in KNC, and DApp integrators receive a portion of fees.

Balancer

Balancer is an automated market-maker built on Ethereum. It allows anyone to create or add liquidity to customizable pools and earn trading fees. Instead of the traditional AMM model, Balancer’s formula allows any number of tokens in any weights or trading fees.

In fact, Balancer is like an inverse of ETF: instead of paying fees to portfolio managers to rebalance your portfolio, you collect fees from traders, who continuously rebalance your portfolio by following arbitrage opportunities. Balancer protocol is designed to be composable and has three types of pools:

1) Private Pools where only the owner can contribute liquidity and has full permissions over the pool, being able to update any of its parameters.

2) Shared Pools where the pool’s tokens, weights, and fees are permanently set and the pool creator has no special privileges. Anyone may add liquidity to shared pools and ownership of the pool’s liquidity is tracked with a specific token called BPT – Balancer Pool Token.

3) Smart Pools which are a variation of a private pool where the controller is a smart contract, allowing for any arbitrary logic/restrictions on how pool parameters can be changed. Smart pools may also accept liquidity from anyone and issue BPTs to track ownership.

Yield Farming

Yield farming is an activity that uses crypto assets to generate as much return as possible on those assets. A yield farmer may continually chase which pool offers the best APY (Annual Percentage Yield). This may mean moving to risky pools from time to time, but yield farmers can deal with the risks.

In some sense, yield farming is similar to staking but is a lot more complex. In many cases, it works with users called liquidity providers (LP) that add funds to liquidity pools. For example, a yielding farmer puts 100,000 USDT into the Compound. In return, he or she will get a token for the stock, called cUSDT.

Let’s say he or she get 100,000 cUSDT back. He or she can then put the cUSDT into a liquidity pool that uses cUSDT in Balancer, an AMM (auto market maker) that allows users to set up a crypto index fund that is rebalancing. At normal times, this can earn a small amount of transaction fees. This is the basic idea of ​​yield farming. Users are looking for sophisticated cases in the system to produce as many results as possible in as many products as possible.

Liquidity Pool

What is a liquidity pool? It’s basically a smart contract that contains funds. In return for providing liquidity to the pool, LPs get a reward. That reward may come from fees generated by the underlying DeFi platform, or some other source.

Some popular Yield Farming platforms are SushiSwap, Yearn Finance, and YAM Finance.

SushiSwap

SushiSwap is an automated market making (AMM) decentralized exchange (DEX) currently on the Ethereum blockchain. Unlike other protocols, SushiSwap is a community-run project that is governed by the vote of the community. There are a few core products for SushiSwap’s ecosystem:

Each of these serve a different purpose within the ecosystem. Users Earn SUSHI tokens by staking SushiSwap V2 SLP Tokens.

Yearn Finance

yearn.finance is a decentralized ecosystem of aggregators that utilize lending platforms such as Aave, Compound, Dydx, and Fulcrum to optimize your token lending. When you deposit your tokens into yearn.finance, they are converted to yTokens. yTokens are periodically rebalanced to choose the most profitable lending services.

Among the aggregators, Curve.fi is the most prominent integrator of yTokens. Curve.fi creates an AMM between yDAI, yUSDC, yUSDT, yTUSD that not only earns the lending fees but also the trading fees on Curve.fi. On the other hand, YFI, yearn.finance’s governance token, is distributed only to users who provide liquidity with certain yTokens. With no pre-mine, pre-sale, or allocation to the team, YFI is claimed to be the most decentralized token in the DeFi space.

YAM Finance

YAM Protocol is a decentralized cryptocurrency that uses a rebasing mechanism to raise funds for a treasury managed by the community. The community can then use those funds via YAM governance to build the protocol.

In addition, YAM is the governance token for the YAM protocol. Using token voting, YAM holders have direct influence over the YAM treasury and direction of the protocol. Governance discussions take place on the Yam Governance Forum.

Currently, you’re able to earn YAM rewards by providing liquidity to the yUSD/YAM Uniswap pool. The rewards given to the pool are 92,500 in week 1, decreasing by 10% every week after. Please realize that you must apply the YAM scaling factor to get the current reward amount at any given time.

Conclusion

In short, DeFi is the most exciting blockchain-based financial ecosystem right now, but it is also extremely risky and confusing. This article is just an introduction to DeFi and I hope you could understand the basic concepts. To help every understand the DeFi applications better and even use them to accumulate wealth in digital assets, I will attempt to write a series of article of DeFi that shall zoom into some famous DeFi platforms like Compound, UniSwap, SushiSwap, yearn finance, Balancer and more, stay tune!

References

Fighting COVID-19 with Blockchain

COVID-19 outbreak has become a global pandemic in recent months. The epicenter of the outbreak has moved from China to Europe and then the US. It has sickened hundreds of thousands of people and caused ten of thousands of deaths.

The coronavirus pandemic has highlighted many of the applications for blockchain technology. For example, Blockchain technology has been proposed as the most efficient means through which the United States’ stimulus package could be distributed.

On the other hand, the Chinese government has deployed blockchain in numerous applications to assist its efforts to fight COVID-19, using DLT to track the virus’ spread, medical records, and the distribution of medical supplies and charity donations.

To fight the outbreak, WHO has launched a DLT platform for sharing data pertaining to the COVID-19 Pandemic. In addition, some companies and non-profit organizations have also launched blockchain-based projects to counter the outbreak of COVID-19. Let’s examine a few of the aforementioned initiatives :

WHO

WHO has launched the blockchain-based platform know as MiPasa to fight COVID-19. The platform will enable “early detection of COVID-19 carriers and infection hotspots. It was built on top of the Hyperledger Fabric. Hyperledger Fabric is an open-source enterprise-grade permissioned distributed ledger technology (DLT) platform.

The MiPasa platform was co-developed by MiPasa, IBM, Oracle, Hacera and Microsoft. It aims to facilitate fully private information sharing between individuals, state authorities and health institutions.

MiPasa is a verifiable information highway that allows cross-references siloed location. Furthermore, health data is stored on the platform to obtain global insights while ensuring patient privacy. Besides that, MiPasa is will host an array of publicly accessible analytics tools too.

SNARK HEALTH

Snark Health is a platform that connects patients, doctors, insurers, and donors for health care services, private data sharing and payments via the blockchain technology.  

To combat COVID-19, SNARK is building a framework for data-driven discussions and shared learnings to help people have a greater impact at their respective local, state, national level in collaboration with their organizations and governmental agencies. It aims to enable more rapid dissemination of information to improve patient outcomes.

The goal of this project is to facilitate the exchange of knowledge, best practices, and lessons learned to support the people and organizations that are tasked with problem-solving at the local level across the globe. According to SNARK, there remain many unanswered questions in regards to the clinical, operational and financial aspects of the COVID-19 pandemic. Through the process of answering these critical questions, the new framework could lay the foundation for global triage support, improved access to health care services and clinical research.

BINANCE

Binance’s Blockchain-powered donation platform Binance Charity has initiated a $5 million coronavirus relief campaign At the time of writing this article, its “Crypto Against COVID” campaign has received 24 donations, amounting to a total of 160.6306 BTC. A wallet has been set up for public donations, which can be made in BNB, BTC, BUSD, and XRP. Besides that, Binance will make an upfront donation of $1 million in BUSD, which will be converted to fiat and used to purchase supplies to send to hospitals in affected countries.

In addition, Binance will also match donations up to $1 million. Furthermore, the company will donate $1 for every retweet of its #CryptoAgainstCovid posting and will donate an additional $1 million if the number of retweets reaches 1 million within seven days.

As of March 20 this year, Binance Charity has delivered a number of coronavirus aid products to over 300 hospitals and medical teams in multiple provinces and cities, including Hubei, Sichuan, Guangxi, and Shanghai. The items delivered include 366,000 pairs of gloves, 56,800 masks, 9 sterilizers, 173 barrels of disinfectant, 5,280 bottles of hand sanitizers, 20,000 testing kits, 7,850 protective suits, 20,000 pairs of goggles, 388 oxygen concentrators, and 1000 germicidal lamps.

Hashcash Consultants

Hashcash Consultants has launched the Corona Fund Index Cryptocurrency (CFIX), a coronavirus relief initiative involving cryptocurrency.

This global software firm promised that 90% of trading fees derived from CFIX will be diverted to its Corona Relief Fund. The fund will be donated to various non-profits and organizations that are actively combating the global COVID-19 pandemic crisis.

References

Blockchain-based Event Management and Ticketing Platform

The event management and ticketing industry is a huge market, particularly the event management software market. Markets Insider reported that the Event Management Software Market is projected to grow from USD 5.7 billion in 2019 to USD 11.4 billion by 2024, at a CAGR of 15% from 2019 to 2024.

However, despite the great potential of the event and ticketing industry, there are numerous problems and issues plaguing the current centralized event ticketing industry. The main issues include ticket counterfeiting, ticket scalpers, instant sell-outs and overpriced resale tickets on secondary markets (EventChain, 2017).

The good news is that the blockchain could fix the aforementioned issues.  A blockchain is a distributed digital ledger that can be used to record transactions and other data across a decentralized peer-to-peer network made up of a cluster of computing devices.

Using blockchain technology, every ticket sales can be publicly verified, and thus the authenticity of the ticket can be guaranteed. It is also able to prevent fraudulent sales and counterfeiting. It sets rules (using smart contracts) preventing secondary ticket websites from hoarding tickets and charging inflated prices for premium events. If the rules are broken, the fraudulent accounts are frozen and the tickets are made invalid.

In a nutshell, a blockchain-based event and ticketing system has the following benefits:

  • Elimination of ticket duplication and counterfeit tickets
  • Elimination of scalpers
  • Elimination of ticket touts and purchasing bots
  • Fully transparent ticketing aftermarket
  • Automatic refund at the time of cancelation

Use Cases

BitTicket

The Edinburgh-based Citizen Ticket is an event ticketing platform backed by blockchain technology that uses the cryptocurrency Ethereum Classic. In May 2017, they deployed the blockchain-based ticketing system BitTicket and delivered the first live event using blockchain technology.

BitTicket is a ticket delivery service that event organisers, venues, and artists can use to secure their tickets with blockchain technology. BitTicket provides users with one wallet QR code that holds all their BitTickets securely, no matter which ticketing provider they bought them from. They simply present it along with proof of ID to gain entry. Due to the security of BitTicket identity, ticket transfer to friends and family can be done easily and with assurance. BitTickets are immutable, transferable, and verifiable.

BitTicket guarantees the following:

  • Your purchased ticket is genuine
  • Inherent protection against industrial-scale ticket touts and ticket purchasing bots
  • Transfer your tickets securely and with ease between friends & family
  • Provides one wallet for all your tickets – no more individual tickets

GUTS

GUTS uses blockchain technology to create a transparent ticketing ecosystem where inflated secondary market prices and ticket fraud are eliminated. Their motto is simple, transparent and secure.

GUTS brings numerous benefits for different stakeholders:

  • Artist and Managers
    • A fair chance for all the fans to attend the show
    • Expand the fan base with exact data
    • Direct communication with your fans. Send them a message right before the show starts.
  • The Venue, Festival and Theatre Operators
    • No ticket fraud: fewer complaints and a stronger image
    • You know exactly who is present at any time (and who isn’t)
    • Automatic refund procedure at the time of cancelation or resale
    • Identification via mobile phones means shorter queues
  • Ticket Providers
    • Complete control of the tickets in both the primary and secondary market
    • Easy to integrate with existing ticketing solutions

LAVA

LAVA is a blockchain-based ticketing system that guarantees fair and secure smart tickets for music lovers. The system prevents ticket touting and fraud ruining festivals for music lovers.

The LAVA ecosystem has the following features:

  • 100% Safe
    • Using latest blockchain technology to eliminate ticket fraud
  • Smart Tickets
    • Smart tickets to stop the exploitation of festival tickets using a unique digital footprint
  • Lava Wallet – Eliminate printing completely by generating the ticket digitally and sending the digital ticket to the Lava wallet directly
  • No booking fee

PouchNATION

PouchNATION is an event management software system that uses the blockchain technology to good effect. PouchNATION is the first platform to implement blockchain and new digital currency across all verticals in event management. Its components comprise guest registration, cashless payment, access control, activity tracking, social engagement and detailed analytics reporting.

This innovative platform could overcome issues that the ticket industry is currently facing with managing events, attendance tracking apps, eliminating duplicate tickets, and validating registration at the door.

They have executed over 100 events including cashless events in Indonesia, Philippines, Vietnam, Malaysia, Thailand, and Myanmar.

EventChain

EventChain is a global Smart Ticketing blockchain project that will allow events worldwide to sell SmartTickets through a peer-to-peer network, solving the issues of the centralized event ticketing industry.

It implements the EventChain token network for event management to ensure faster transactions, indisputable ticket vouchers, transparency from event hosts and fully flexible and programmable SmartTickets. With the use of the EVC token, smart contract code, and the Ethereum blockchain, EventChain’s transaction network brings increased accountability, transparency, and security to event ticketing.

To fix the excessive ticket fees, EventChain is distributing EVC tokens, a digital ERC20 token created for buying, selling, and programming SmartTickets on the Ethereum distributed network. EventChain claims that their transaction fees are much lower and the transaction confirmation speed is near seconds.

Event Management and Ticketing Platform-A Conceptual Model

After examining the above use cases, I propose a conceptual model that utilises a similar concept to develop a blockchain-based event management and ticketing platform. Below is a simple conceptual model of the Event Management and Ticketing Platform:

The platform allows an event organizer to create an event and broadcast it to the website as well as a mobile wallet. The event should comprise details such as event title, date, time, venue, and a ticketing ordering button. The participant can then order tickets by paying  Token X. Once the organizer receives Token X, the e-ticket shall be automatically delivered to the participant’s mobile wallet. To enter the event venue, the organizer just needs to scan the e-ticket of the participant.

To build the platform, we need to build a smart contract layer on top of blockchain network to automate the buying and selling of event tickets. We shall use Solidity to write the contracts. There shall be at least three smart contracts -the ERC20 token contract(to generate Token X),  the event contract, and the ERC721 ticket contract. The event contract will need to link to the ticket contract as it needs to use the data in the ticket contract. The keyword to access the data in another contract is import. For example, we can create an event contract event.sol that imports the ticket contract ticket.sol, using the syntax as follows:

Pragma Solidity ^0.5.0
import "./ticket.sol"; 

The event.sol file shall create an event contract that specifies event details such as total tickets, collected funds, start time, etc. The code could be as follows:

Contract Event { 
 struct EventDetails {  
 uint256 ticketAmount; 
 uint256 SoldticketAmount; 
 uint256 CollectedFunds; 
 uint256 StartTime; 
  } 

The event contract shall also include a create event function, as follows:

function CreateEvent{
 uint256 _ticketAmount; 
 uint256 _Startime 
}

There are many more functions to be included in the smart contracts but I will not dwell further as this is not a technical paper.

References


Event Management and Ticketing Platform

The event management and ticketing industry is a huge market, particularly the event management software market. Markets Insider reported that the Event Management Software Market is projected to grow from USD 5.7 billion in 2019 to USD 11.4 billion by 2024, at a CAGR of 15% from 2019 to 2024.

However, despite the great potential of the event and ticketing industry, there are numerous problems and issues plaguing the current centralized event ticketing industry. The main issues include ticket counterfeiting, ticket scalpers, instant sell-outs and overpriced resale tickets on secondary markets (EventChain, 2017).

The good news is that the blockchain could fix the aforementioned issues.  A blockchain is a distributed digital ledger that can be used to record transactions and other data across a decentralized peer-to-peer network made up of a cluster of computing devices.

Using blockchain technology, every ticket sales can be publicly verified, and thus the authenticity of the ticket can be guaranteed. It is also able to prevent fraudulent sales and counterfeiting. It sets rules (using smart contracts) preventing secondary ticket websites from hoarding tickets and charging inflated prices for premium events. If the rules are broken, the fraudulent accounts are frozen and the tickets are made invalid.

In a nutshell, blockchain-based event and ticketing system has the following benefits:

  • Elimination of ticket duplication and counterfeit tickets
  • Elimination of scalpers
  • Elimination of ticket touts and purchasing bots
  • Fully transparent ticketing aftermarket
  • Automatic refund at the time of cancelation

Use Cases

BitTicket

The Edinburgh-based Citizen Ticket is an event ticketing platform backed by blockchain technology that uses the cryptocurrency Ethereum Classic. In May 2017, they deployed the blockchain-based ticketing system BitTicket and delivered the first live event using blockchain technology.

BitTicket is a ticket delivery service that event organisers, venues, and artists can use to secure their tickets with blockchain technology. BitTicket provides users with one wallet QR code that holds all their BitTickets securely, no matter which ticketing provider they bought them from. They simply present it along with proof of ID to gain entry. Due to the security of BitTicket identity, ticket transfer to friends and family can be done easily and with assurance. BitTickets are immutable, transferable, and verifiable.

BitTicket guarantees the following:

  • Your purchased ticket is genuine
  • Inherent protection against industrial-scale ticket touts and ticket purchasing bots
  • Transfer your tickets securely and with ease between friends & family
  • Provides one wallet for all your tickets – no more individual tickets

GUTS

GUTS uses blockchain technology to create a transparent ticketing ecosystem where inflated secondary market prices and ticket fraud are eliminated. Their motto is simple, transparent and secure.

GUTS brings numerous benefits for different stakeholders:

  • Artist and Managers
    • A fair chance for all the fans to attend the show
    • Expand the fan base with exact data
    • Direct communication with your fans. Send them a message right before the show starts.
  • The venue, Festival and Theatre Operators
    • No ticket fraud: fewer complaints and a stronger image
    • You know exactly who is present, anytime (and who isn’t)
    • Automatic refund procedure at the time of cancelation or resale
    • Identification via mobile phones means a shorter queue
  • Ticket Providers
    • Complete control on the tickets at both the primary and secondary market
    • Easy to integrate with existing ticketing solutions

LAVA

LAVA is a blockchain-based ticketing system that guarantees fair and secure smart tickets for music lovers. The system could prevent ticket touting and fraud ruining festivals for music lovers.

The LAVA ecosystem has the following features:

  • 100% Safe
    • Using latest blockchain technology to eliminate ticket fraud
  • Smart Tickets
    • Smart tickets to stop the exploitation of festival tickets using a unique digital footprint
  • Lava Wallet-Eliminate printing completely by generating the ticket digitally and sending the digital ticket to the Lava wallet directly.
  • No booking fee

PouchNATION

PouchNATION is an event management software system that uses the blockchain technology to good effect. PouchNATION is the first platform to implement blockchain and new digital currency across all verticals in event management. Its components comprise guest registration, cashless payment, access control, activity tracking, social engagement and detailed analytics reporting.

This innovative platform could overcome issues that the ticket industry is currently facing with managing events, attendance tracking apps, eliminating duplicate tickets, and validating registration at the door.

They have executed over 100 events including cashless events in Indonesia events in Indonesia, Philippines, Vietnam, Malaysia, Thailand, and Myanmar.

EventChain

EventChain is a global Smart Ticketing blockchain project that will allow events worldwide to sell SmartTickets through a peer-to-peer network, solving the issues of the centralized event ticketing industry.

It implements the EventChain token network for event management presents to ensure faster transactions, indisputable ticket vouchers, transparency from event hosts and fully flexible and programmable SmartTickets. With the use of the EVC token, smart contract code, and the Ethereum blockchain, EventChain’s transaction network brings increased accountability, transparency, and security to event ticketing.

To fix the excessive ticket fees, EventChain is distributing EVC tokens, a digital ERC20 token created for buying, selling, and programming SmartTickets on the Ethereum distributed network. EventChain claims that their transaction fees are much lower and the transaction confirmation speed is near seconds.

A Conceptualised Event Management and Ticketing Platform

After examining the above use cases, I propose that we can use a similar concept to develop blockchain-based event management and ticketing system for a decentralized platform. Below is a simple conceptual model of Event Management and Ticketing platform:

The platform allows an event organizer to create an event and broadcast it to the website as well as the Token X wallet. The event should comprise details such as event title, date, time, venue, and a ticketing ordering button. The participant can then order tickets by paying Token X. Once the organizer receives Token X, the e-ticket shall be automatically delivered to the participant’s mobile wallet. To enter the event venue, the organizer just needs to scan the e-ticket of the participant.

To build the platform, we need to build a smart contract layer on top of the platform to automate the buying and selling of event tickets. We shall use Solidity to write the contracts. There shall be at least two smart contracts – the event contract, and the ticket contract. The event contract will need to link to the ticket contract as it needs to use the data in the ticket contract. The keyword to access the data in another contract is import. For example, we can create an event contract event.sol that imports the ticket contract ticket.sol, using the syntax as follows:

Pragma Solidity ^0.5.0
import "./ticket.sol";

The event.sol file shall create an event contract that specifies event details such as total tickets, collected funds, start time, etc. The code could be as follows:

Contract Event { 
struct EventDetails { 
uint256 ticketAmount;
uint256 SoldticketAmount;
uint256 CollectedFunds;
uint256 StartTime;
 }

The event contract shall also include a create event function, as follows:

function CreateEvent{
uint256 _ticketAmount;
uint256 _Startime
}

There are many more functions to be included in the smart contracts but I will not dwell further as this is not a technical paper.

References

Developing a DAPP – KittyChain Shop

What is DApp?

DApp is an abbreviation for decentralized application.

A DApp has its backend code running on a decentralized peer-to-peer network. Contrast this with an app where the backend code is running on centralized servers.

A DApp can have frontend code and user interfaces written in any language that can make calls to its backend. Furthermore, its frontend can be hosted on decentralized storage such as Swarm or IPFS.

The Project Description

In this project, we shall use Ganache (https://truffleframework.com/ganache) to develop the KittyChain Shop DApp.

Ganache is a personal blockchain for Ethereum development you can use to deploy contracts, develop your applications, and run tests. It is available as both a desktop application as well as a command-line tool (formerly known as the TestRPC). Ganache is available for Windows, Mac, and Linux.

Truffle is a world-class development environment, testing framework and asset pipeline for blockchains using the Ethereum Virtual Machine (EVM), aiming to make life as a developer easier.

The KittyChain DApp is an adoption tracking system for a pet shop

Steps to build the Dapp

  1. Setting up the development environment
  2. Creating a Truffle project using a Truffle Box
  3. Writing the smart contract
  4. Compiling and migrating the smart contract
  5. Testing the smart contract
  6. Creating a user interface to interact with the smart contract
  7. Interacting with the dApp in a browser

Step 1  Setting up the development environment

Install the following:

  1. Node.js
  2. Git
  3. Truffle 

Having installed the aforementioned packages, we shall proceed to install Ganache. You can download Ganache by navigating to http://truffleframework.com/ganache and clicking the “Download” button.

Step 2  Creating a Truffle project using a Truffle Box

Truffle initializes in the current directory, so first create a directory in your development folder of choice and then move inside it.

mkdir pet-shop-tutorial

cd pet-shop-tutorial

Now you have created a Truffle Box called pet-shop, which includes the basic project structure as well as code for the user interface.

Next, use the truffle unbox command to unpack this Truffle Box.

truffle unbox pet-shop

The Output

Directory structure

The default Truffle directory structure contains the following folders and files:

  • contracts/: Contains the Solidity source files for our smart contracts. There is an important contract in here called Migrations.sol, which we’ll discuss later.
  • migrations/: Truffle uses a migration system to handle smart contract deployments. Migration is an additional special smart contract that keeps track of changes.
  • test/: Contains both JavaScript and Solidity tests for our smart contracts.
  • truffle.js: Truffle configuration file.

Step 3  Writing the smart contract

We’ll shall write the smart contract that will act as the back-end logic and storage.

Create a new file named Adoption.sol in the contracts/ directory. To save time, please download the file from:

http://javascript-tutor.net/blockchain/download/contracts/Adoption.sol

Adoption.sol

pragma solidity ^0.4.24;
 contract Adoption { 
    //array of 16 addresses, 20 bytes 
    address[16] public adopters; 
 // Adopting a pet 
    function adopt(uint petId) public returns (uint) { 
    require(petId >= 0 && petId <= 15); 
 adopters[petId] = msg.sender; 
   return petId; 
    }
 // Retrieving the adopters 
    function getAdopters() public view returns (address[16]) { 
       return adopters; 
    } 
 } 

Step 4 Compiling and migrating the smart contract

Now that we have the smart contract, we shall proceed to compile and migrate it.

Truffle has a built-in developer console known as Truffle Develop, which generates a development blockchain that we can use to test and deploy the smart contract. It also has the ability to run Truffle commands directly from the console. 

We need to compile the smart contract written in Solidity to bytecode for the Ethereum Virtual Machine (EVM) to execute. Think of it as translating our human-readable Solidity into something the EVM understands. In a terminal, make sure you are in the root of the directory that contains the DApp and type:

truffle compile

The output


Compiling ./contracts/Migrations.sol...
Compiling ./contracts/Adoption.sol...
Writing artifacts to ./build/contracts

Now that we’ve successfully compiled our contracts, it’s time to migrate them to the blockchain! Migration is the deployment script meant to alter the state of the application’s contracts, moving it from one state to the next. For the first migration, you might just be deploying new code, but over time, other migrations might move data around or replace a contract with a new one.

By the way, there is one JavaScript file already in the migrations/ directory: 1_initial_migration.js. This file handles deploying the Migrations.sol contract to observe subsequent smart contract migrations, and ensures we don’t double-migrate unchanged contracts in the future. Now let’s create our own migration script.

Create a new file named 2_deploy_contracts.js in the migrations/directory.

To save time, download the file from the following link:

http://javascript-tutor.net/blockchain/download/contracts/2_deploy_contracts.js

Before we can migrate our contract to the blockchain, we need to have a blockchain running. For this tutorial, we’re going to use Ganache, a personal blockchain for Ethereum development you can use to deploy contracts, develop applications, and run tests. If you haven’t already, download Ganache and double click the icon to launch the application. This will generate a blockchain running locally on port 7545.

Launch Ganache and you get the following output:

Now back in your VS Code terminal, enter the following command:

truffle migrate

You can see the migrations being executed in order, followed by the blockchain address of each deployed contract.

In Ganache, note that the state of the blockchain has changed. The blockchain now shows that the current block, previously 0, is now 4. In addition, while the first account originally had 100 ether, it is now lower at 99.94, due to the transaction costs of migration. 

Step 5 Testing the smart contract

Truffle is very flexible when it comes to smart contract testing, in that tests can be written either in JavaScript or Solidity. In this tutorial, we’ll be writing our tests in Solidity.

Create a new file named TestAdoption.sol in the test/ directory. To save time, download a copy of the file from the following link:

http://javascript-tutor.net/blockchain/download/test/TestAdoption.sol

We start the contract off with 3 imports:

  • Assert.sol: Gives us various assertions to use in our tests. In testing, an assertion checks for things like equality, inequality or emptiness to return a pass/fail from our test. Here’s a full list of the assertions included with Truffle.
  • DeployedAddresses.sol: When running tests, Truffle will deploy a fresh instance of the contract being tested to the blockchain. This smart contract gets the address of the deployed contract.
  • Adoption.sol: The smart contract we want to test.

To run the test, enter the following command

Truffle test

The output is as follows:

Step 6 Creating a user interface to interact with the smart contract

Now that we’ve created the smart contract, deployed it to our local test blockchain and confirmed we can interact with it via the console, it’s time to create a UI so that the user can interact with the  pet shop!

Included with the pet-shop Truffle Box is the code for the app’s frontend. It is the JavaScript file app.js within the src/ directory. You can download the app.js file from the following link:

http://javascript-tutor.net/blockchain/download/src/js/app.js

We need to instantiate web3 to create the UI. The global App object is to manage our application, load in the pets data in init() and then call the function initWeb3(). The web3 JavaScript library interacts with the Ethereum blockchain. It can retrieve user accounts, send transactions, interact with smart contracts, and more.

First, we check if there’s a web3 instance already active. (Ethereum browsers like Mist or Chrome with the MetaMask extension will inject their own web3 instances.) If an injected web3 instance is present, we get its provider and use it to create our web3 object.

If no injected web3 instance is present, we create our web3 object based on our local provider. (Here we fallback on http://localhost:7545 that points to Ganache.)

Instantiating the contract

We need to instantiate our smart contract so web3 knows where to find it and how it works. Truffle has a library to help with this called truffle-contract. It keeps information about the contract in sync with migrations, so you don’t need to change the contract’s deployed address manually.

First, we retrieve the artifact file for our smart contract. Artifacts are information about our contract such as its deployed address and Application Binary Interface (ABI). The ABI is a JavaScript object defining how to interact with the contract including its variables, functions and parameters.

Once we have the artifacts in our callback, we pass them to TruffleContract(). This creates an instance of the contract we can interact with. With our contract instantiated, we set its web3 provider using the App.web3Provider value we stored earlier when setting up web3.

We then call the app’s markAdopted() function in case any pets are already adopted from a previous visit. We’ve encapsulated this in a separate function since we’ll need to update the UI any time we make a change to the smart contract data.

Getting The Adopted Pets and Updating The UI

We shall access the deployed Adoption contract, then call getAdopters() on that instance.

We first declare the variable adoptionInstance outside of the smart contract calls so we can access the instance after initially retrieving it.

Using call() allows us to read data from the blockchain without having to send a full transaction, meaning we won’t have to spend any ether.

After calling getAdopters(), we then loop through all of them, checking to see if an address is stored for each pet. Since the array contains address types, Ethereum initializes the array with 16 empty addresses. This is why we check for an empty address string rather than null or other false value.

Once a petId with a corresponding address is found, we disable its adopt button and change the button text to “Success“, so the user gets some feedback. Any errors are logged to the console.

Handling the adopt() Function

We use web3 to get the user’s accounts. In the callback after an error check, we select the first account.

From there, we get the deployed contract as we did above and store the instance in adoptionInstance. This time though, we’re going to send a transaction instead of a call. Transactions require a “from” address and have an associated cost. This cost, paid in ether, is called gas. The gas cost is the fee for performing computation and/or storing data in a smart contract. We send the transaction by executing the adopt() function with both the pet’s ID and an object containing the account address, which we stored earlier in account.

The result of sending a transaction is the transaction object. If there are no errors, we proceed to call our markAdopted() function to sync the UI with our newly stored data.

Step 7 Interacting with the DApp in a browser

The easiest way to interact with our DApp in a browser is through MetaMask, a browser extension for both Chrome and Firefox.

Install MetaMask in your browser.

Once installed, you’ll see the MetaMask fox icon next to your address bar. Click the icon and you’ll see this screen appear:

At the initial MetaMask screen, click Import Existing DEN.

In the box marked Wallet Seed, enter the mnemonic that is displayed in Ganache.

Enter a password below that and click OK.

Now we need to connect MetaMask to the blockchain created by Ganache. Click the menu that shows “Main Network” and select Custom RPC.

In the box titled “New RPC URL” enter http://127.0.0.1:7545 and click Save.

The network name at the top will switch to say “Private Network”.

Each account created by Ganache is given 100 ether. You’ll notice it’s slightly less on the first account because some gas was used when the contract itself was deployed and when the tests were run. (Make sure you are running Ganache as well.)

Installing and configuring lite-server

We can now start a local web server and use the DApp. We’re using the lite-server library to serve our static files. This shipped with the pet-shop Truffle Box, but let’s take a look at how it works.

Let’s examine  bs-config.json 

{
 "port": 3000, 
  "server": { 
 "baseDir": ["./src", "./build/contracts"], 
 "open": false 
  }, 
 "browser": ["chrome"] 
 } 

This tells lite-server which files to include in our base directory. We add the ./src directory for our website files and ./build/contracts directory for the contract artifacts.

I added “browser”: [“chrome”]

So that the UI opens in the Chrome browser.

We’ve also added a dev command to the scripts object in the package.json file in the project’s root directory. The scripts object allows us to alias console commands to a single npm command. 

To launch the app, enter the command in the VS Code Console.

npm run dev

Kittychain Shop

Pet Shop UI

Metamask appears after clicking adopt.

Transactions are shown on Metamask.

And also on Ganache.

References