© The Author(s) 2018
Sarah Swammy, Richard Thompson and Marvin LohCrypto Uncoveredhttps://doi.org/10.1007/978-3-030-00135-3_6

6. Crypto Currency: The Birth of an ICO

Sarah Swammy1  , Richard Thompson2   and Marvin Loh3  
(1)
State Street Global Market, LLC, New York, NY, USA
(2)
Digital Air Technologies, New York, NY, USA
(3)
Bank of New York Mellon, New York, NY, USA
 
 
Sarah Swammy (Corresponding author)
 
Richard Thompson
 
Marvin Loh

Keywords

Initial coin offerings (ICOs)TransactionalPlatformUtility tokensEthereum Virtual MachineInvestors

Crypto Currency

By continuing the journey through defining, launching, and bringing a crypto currency to a level of critical mass, a symbiotic relationship between the currency and the marketplace is naturally developed. Crypto currencies exist only within the networks that they are conceived in. Those networks which give life to a particular currency will survive or have viability relative to the utility value of the marketplace. At least this will be apparent initially. Confusing the entire relationship as crypto currency is easy. However, deconstructing all the components is vital to bring clarity as an initial coin offering (ICO) is launched, and the number of crypto currencies increases in number. In Chap. 4, the importance of managing the marketplace through a well-defined governance mechanism was explored in depth. Chapter 5 defined what crypto currency is and what its types are. Since an ICO is the preferred choice to bring a crypto currency online, this chapter goes through the details of launching an ICO using the working model of LUCKY DOG coin for reference.

Electricity brought the concept of crypto currency to life officially when Liberty Standard assigned a value to Bitcoin based upon the cost of the electricity used to create this form of electronic money at $1309,03 (BTC) to 1 USD. A technological process called minting controls the creation and protection, as cryptology hides the identities of all its users. The digital coin, the item of value, is implemented on a blockchain: a specialized immutable, decentralized, anonymous, and trustless database. An enormous amount of computing capacity is required to execute a blockchain. Crypto currencies brought to light the power of blockchain technology and became the gas that powered the existence of blockchain networks.

The pet industry is an 86-billion-dollar market sector. A nice market to target for the launch of a digital currency. This coin will exist within the lucky.io network and serve as the instrument of value used to manage transactions. The coin will be a transactional token built on the Ethereum platform. Further explanations are forthcoming in later sections. A digital currency in this high-growth arena would prove beneficial to track retail activity, provide dog breed preferability information, track immunization, licensing, and registration details of dogs through the blockchain.

How Crypto Currency Works

Removing the cloud and hype around crypto currencies, and reducing it to its fundamental element, you discover it is an electronic accounting system containing entries that cannot be changed unless explicit criteria are fulfilled. Every transaction is broadcast immediately through the entire network. However, confirmation is achieved only through solving the hash function, which requires a finite amount of time to achieve. This consensus form of confirmation is a crucial concept native to crypto currencies.

This consensus type of transaction validation is the heart and soul of crypto currencies. Transactions go through a workflow of pending to be confirmed. A transaction can be modified while in pending. However, once transactions are confirmed, it is cemented into the blockchain. It is no longer forgeable. Neither can it be reversed, nor is it part of an immutable record of historical transactions: of the so-called blockchain.

Within the decentralized transaction network, miners are the only participants within the network to confirm transactions. Using Bitcoin as the reference from which all other crypto currencies are derived, miners are incentivized to perform transactions by being awarded at the current time 12.5 Bitcoin per confirmed transaction. This is their role within a crypto currency network. They take transactions, stamp them as legit, and spread them in the network. After a miner confirms a transaction, every node has to add it to its database. It has to become part of the blockchain. The underlying data structure is an encrypted hash database called a Merkle Tree. In theory, anyone can be a miner. A decentralized network does not have any authority to delegate this task. Hence a crypto currency needs some mechanism to prevent one ruling party from abusing it. If there were no controls in place to prevent the spread of forged and fraudulent transactions from spreading, the system would break immediately.

Crypto currencies are entries about tokens in decentralized consensus databases. They are called CRYPTO currencies because strong cryptography secures the process. Cryptography is used to develop crypto currencies. They are secured by math. Because of the security, it is near to impossible that a Bitcoin address will be compromised.

Figure 6.1 depicts a very high-level overview of crypto currency.
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig1_HTML.png
Fig. 6.1

How crypto currency works

Types of Crypto Currency

Each crypto currency solves a particular problem and fits into one of the following three categories:
  1. 1.

    Transactional

     
  2. 2.

    Platform

     
  3. 3.

    Utility tokens

     

Some crypto currencies can be fit into more than one category. The categories along with some examples are discussed below.

Transactional

It is known as the original category for crypto currencies. These are mainly designed to be used as money and thus exchanged for goods and services. Some transactional crypto currencies are Bitcoin, Litecoin, and a host of others. This category of crypto currencies is intended to eliminate the need for government-issued currency. It is quite a possibility that some form of crypto currency may replace some or all fiat currencies one day. But the replacement cryptos may still come from central banks—Singapore’s government, for one, is testing out this idea with its Project Ubin.

Platform

Platform crypto currencies are designed to eliminate intermediaries. Markets are also created using these and even used for launching other crypto currencies. The base for a host of future applications is provided by platform crypto currencies.

One of the prime examples of a platform crypto currency is Ethereum. A decentralized platform like Ethereum is used for running smart contracts. A smart contract is a kind of application that runs precisely as programmed. Hence the possibility of fraud, censorship, or even downtime is significantly reduced. Many new crypto currencies are also built on Ethereum.

Utility Tokens

A particular task is performed by utility crypto currency. An example of a utility crypto currency is Ripple (XRP). It is designed to facilitate fiat money transfer in an economical and highly efficient manner. Multiple banks and institutions also use it. Some of the names include UBS, Santander, BMO, and American Express. Tech investor Nick Tomaino believes utility tokens can be broken down into four different categories:
  • Asset tokens

    Traditional asset tokens are the crypto representations of standard fiat assets.

  • Usage tokens

    Usage tokens provide digital service access. Bitcoin is considered a usage token because users are granted access to a virtual payments network.

  • Work tokens

    Work tokens offer users the right to contribute work to a decentralized organization. For example, Maker, a work token, serves as the backstop in a collateralized debt system.

  • Hybrid tokens

    Hybrid tokens are a mix of usage and work coins. They can be used for multiple purposes.

Ethereum

Similar to Bitcoin, Ethereum is a distributed public blockchain network. Some significant technical differences exist between the two, but the most important distinction to note is that Bitcoin and Ethereum differ substantially in purpose and capability. Bitcoin offers one particular application of blockchain technology, a peer-to-peer electronic cash system that enables online Bitcoin payments. While the Bitcoin blockchain is used to track ownership of digital currency (Bitcoins), the Ethereum blockchain focuses on running the programming code of any decentralized application. In the Ethereum blockchain, instead of mining for Bitcoin, miners work to earn Ethereum, a type of crypto token that fuels the network. Beyond a tradable crypto currency, Ethereum is also used by application developers to pay for transaction fees and services on the Ethereum network.

The Ethereum Virtual Machine, which is Ethereum’s core innovation, is a Turing complete software that runs on the Ethereum network. You can run any program, regardless of the programming language, given enough time and memory. The Ethereum Virtual Machine makes the process of creating blockchain applications much more accessible, and it is also more beneficial than ever before. Ethereum enables the development of potentially thousands of different applications all on one platform, and so you don’t have to build an entirely original blockchain for each new application. It gives allowance to the developers to build and deploy decentralized applications. A decentralized application or DAPP serves some particular purpose for its users. Bitcoin, for example, is a DAPP that provides its users with a peer-to-peer electronic cash system. Online Bitcoin payments are also possible through it. The code of decentralized applications runs on a blockchain network. This means that they are not controlled by any individual or central entity.

Ethereum can decentralize any services that are centralized. Many intermediary services that exist across hundreds of different industries include apparent bank services like loans. This also includes intermediary services like title registries, voting systems, regulatory compliance, and much more. Decentralized Autonomous Organizations (DAOs) can also be made using Ethereum. A DAO is fully autonomous, with no single leader. They are run by programming code, on a collection of smart contracts. These smart contracts are written on the Ethereum blockchain. The code is designed to replace the rules and structure of a traditional organization, eliminating the need for people and centralized control. Everyone who purchases tokens owns a DAO, but instead of each token equating to equity shares and ownership, tokens act as contributions that give people voting rights.

Decentralized applications running on the Ethereum blockchain benefit from all of its properties.
  • Immutability—A third party cannot make any changes to data.

  • Corruption and tamper proof—Apps are based on a network formed around the principle of consensus, which in turn makes it impossible to censor.

  • Secure—With no central point of failure and secured using cryptography, applications are well protected against hacking attacks and fraudulent activities.

  • Zero downtime—Apps never go down and can never be switched off.

Though decentralized applications bring a lot of benefits, they aren’t faultless. Humans write smart contract code. So they are only as good as the people who write them. Unintended adverse actions can be taken because of code bugs or oversights. There is no way in which an attack or exploitation can be stopped if a mistake in the code gets exploited. It can be stopped either by obtaining a network consensus or by rewriting the underlying code. It goes against the essence of the blockchain which is meant to be immutable. Also, any action taken by a central party raises serious questions about the decentralized nature of an application.

Smart Contract

In the founding days of blockchain, Nick Szabo envisioned that smart contracts would be integral components of the technology. Blockchain is the core payment system and decentralized record-keeping technology of crypto currencies. However, it does not address the standardization of data content as more complex transactions enter the blockchain. Anyone can imagine as crypto currencies are utilized as payments for unstructured products, such as a bond with an embedded call option, that the description of the transaction must become more sophisticated as the type of transaction. These digital contracts, also referred to as self-executive contracts, would contain not only the physical economic terms between two parties but also settlement instructions, penalties, and rules that govern the enforcement of the transaction. The founders conceptualized a need for a computer program to control the transfer of the nominal units between two parties. That premise became the basis of smart contracts. Computer code is embedded within the details of the contract and distributed throughout the network that computes and manages the blockchain.

At a DC blockchain summit in 2016, the Ethereum smart contract was detailed by its founder, Vitalik Buterin, outlining the workflow of how an asset or currency is transferred into a program. At some point in time, the program runs and automatically validates a condition as to how the asset is awarded, testing if the asset should go to one party or a third party set within the rules of the contract or if it should be immediately refunded to the original party. As in the case of our working model Lucky coin, a contract may have conditions pending passing a physical examination by a determined veterinarian. Coins are transferred from Escrow to a designated breeder. If there is a physical failure by pure breed dog, tokens are returned to the original party. The blockchain records and replicates the document which gives it specific security and immutability. Figure 6.2 illustrates the importance of a smart contract.
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig2_HTML.png
Fig. 6.2

Benefits of a smart contract

Popular implementation of a smart contract is the ESCROW account. Let’s take the case of an employer and consultant situation. Consultant wants to be sure that the employer pays him by the end of the month and the employer is not sure about the consultant’s talent to deliver the service. Employer moves the money to the ESCROW account that ensures the consultant that the employer has enough funds to pay him when he delivers the work and the employer is not worried because if the consultant does not deliver the promised work, then the funds go back to the employer’s account (Fig. 6.3).
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig3_HTML.png
Fig. 6.3

Smart contract versus ESCROW

New crypto currency venture funds are raised by using this. An ICO is used by startups to bypass the rigorous and regulated capital-raising process required by venture capitalists or banks. A percentage of the crypto currency is sold to early backers of the project in exchange for legal tender or other crypto currencies, but usually for Bitcoin or Ethereum. This can also be stated as initial public coin offering (IPCO).

An ICO is used for crowdfunding a new crypto currency and an innovative idea perfect for implementing on the blockchain technology (mostly, as of now). If you are familiar with IPOs (initial public offerings) in the traditional stock market, you’ll understand that an ICO is a little similar, yet different, concept but for crypto currencies. When some genius developers and entrepreneurs come into contact with each other and generate a brilliant idea, tokens for a new crypto currency are offered by them so that they can gather enough funding to convert their idea into reality. The significant difference between ICOs and IPOs is that when you invest you get tokens of that new crypto currency which may get listed on the exchanges once the idea has been developed. It means they aren’t granting you any ownership in the company like IPOs do.

The event of an ICO usually runs for one week or more. Here everyone is allowed to purchase tokens by exchanging established crypto currencies like Bitcoin (BTC) or Ethereum (ETH) just like in the case of IPOs of the traditional stock market. A specific goal or limit can be present for project funding, which means that every token will have a predesignated price that will not change during the ICO period, which also means that the token supply is static. Usually, the number of tokens to be distributed are denoted by the company. For example, 40–50% of the tokens are allocated in the ICOs; 10–20% go to the development team and their efforts to make the project work; 20–30% stay reserved for future use purposes. Let’s look at some of the popular and successful ICOs in the past.
  1. 1.

    The Ethereum ICO in 2014 delivered the first ICO that introduced the smart contract officially and raised 18 million Bitcoins that were valued at $0.40 per Ethereum. It was one of the first of its kind to put this concept of an ICO on the map. In 2014, the Ethereum project was announced. Its ICO raised $18 million in Bitcoin at $0.40 per Ethereum. The project went live in the year 2015, and 2016 witnessed Ethereum’s value going up to $14 with a market capitalization of over $1 billion. Ever since receiving that amount of funding, Ethereum has quickly grown successfully to become the second-most valuable crypto currency ecosystem in the world today.

     
  2. 2.

    Golem Project. Raising $8.6 million in mere minutes is quite a fantastic thing. Golem project will be remembered for achieving that objective. Given that Golem is a decentralized global market for computing power, this significant amount of interest was not entirely unexpected. The ICO was launched at $0.01 and raised $8,596,000, selling 820,000,000 tokens within a few minutes. Presently, the token is valued at $0.512 stating the ROI of +5019.10%.

     
  3. 3.

    LISK, the world’s first modular blockchain-based platform allows developers to create their apps and run them on sidechains (this is a good thing). Programmers choose its apps as they are built with Javascript. Many of the key players from Ethereum were on board, and, consequently, the ICO went down a treat. After successfully raising $5.8 million in four weeks at the price of $0.076 per token, Lisk’s ROI currently sits at 19,080%.

     

How to Launch an ICO

ICOs are also thought of as a tool for any project by some startup owners. Money can be quickly raised and the lengthy and expensive process of registering an IPO with the regulatory agencies bypassed. It used to be the case during the formative days of the ICO market, but now it’s no longer true. ICO is not a tool that can be quickly raised. The ICO ethos is taking shape, and industries are adopting informal standards. The central question every startup considering an ICO should ask itself is whether they can integrate digital tokens into their business model in a meaningful way. If the only use for your coin is to trade on an exchange, it guarantees that the price will crash soon after the ICO takes place. As soon as any token released during a campaign hits the market, it will come under tremendous speculation. Strong demand for the token, is the one thing that can defend a demand that can be produced by the real utility. Authenticity and transparency are among the many core pillars of the crypto currency community. And that also includes the ICO market. Due to this, an ICO whose only objective is to enrich the project owners at the expense of the contributors will not receive any positive attention.

Following are the seven significant steps for launching an ICO.
  1. 1.

    Build the Product

     
  2. 2.

    Write the White Paper

     
  3. 3.

    Perform Legal Checks

     
  4. 4.

    Create the Token

     
  5. 5.

    Security Audit

     
  6. 6.

    Leadership

     
  7. 7.

    Manage the Community

     

Build the Product

Hustlers who are trying to raise capital as quickly as possible tend to ignore this crucial step. The most crucial part of an ICO is building an actual product. You should spend your time making a stable, robust, secure, and scalable product on the blockchain. Then only can you tell us how it’s going to change the world. Perhaps you can get away with launching an MVP or beta and then conduct your token sale. But I think it’s safe to say that a little equity investment has to be raised by most startups to start off their business. When we want to make money, we also require money. And this is no exception. You must have a product, and your token must be used by your product. Let’s take our use case from the last chapter of the LUCKY coin and build the product abstract.

The LUCKY coin is an Ethereum-based blockchain platform regulated by smart contracts. The platform supports the Dog community by building and creating solutions devoted to improving the quality of Dog care worldwide. The blockchain gives LUCKY coin the power to change the world for the better. LUCKY coin develops the Dog world as well as creates market intelligence through a crypto currency reward system that inspires participation throughout the community. The LUCKY coin is the first crypto currency that uses a decentralized review platform and transparently rewards owners and veterinarians who make contributions that benefit the community. The LUCKY coin Foundation team firmly believes in building a future health care world that will fall into the hands of the people. This will result in the disruption of the existing industries and the creation of new industries in the short and long term. LUCKY coin expects the platform to improve Dog health and hygiene habits drastically, thus improving the quality of life for individuals resulting in improved overall health and increased longevity.

Write the White Paper

A white paper can be described as a guidebook that clearly outlines the technical aspects of the product. It also includes the problems it intends to solve, how it is going to address them, a description of the team, and a story of the token generation and distribution strategy. To summarize, we can say that it is a pitch deck, a business plan, a marketing plan, and a technical manual all at once. So there might be a question in your mind as to why so many terrible white papers are being published. From personal experience, I can tell you that writing a white paper is NOT easy. These are seriously complex documents, and far too few teams are investing into proper writers and marketers. Hiring vetted external writers can force the founders to be more rigorous and thorough, while bad vendors will cover up gaps in thinking or product inefficiencies with jargon and fluff. If a white paper were to be written for LUCKY coin to set the stage for the world’s first pet coin, the white paper should thoroughly explain a new conceptual framework to be used within the Dog world for organizational purposes. It should start something like below:

Through the utilization of recent technological innovations, we have created a model with the ability to overcome the majority of the Dog industries’ major constraints and, furthermore, propose various measures that will significantly improve the efficiency of Dog practice, thus improving the owner’s level of Pet well-being. LUCKY coin strives to create a Dog world community by rewarding people who provide valuable contributions with crypto currency. By using this reward system, the foundation will see a rise in a currency which in turn will reach a broad market, including a vast number of people who have yet to participate in any crypto currency economy.

According to Harvard Business Review, “To protect the blockchain vision from political pressure and regulatory interference, blockchain networks rely on a decentralized infrastructure that can’t be controlled by any one person or group.”

The integration of Dog owners and the associated marketplace of service providers is an astounding concept. It requires the creation of a community in which transparency and shared responsibility can take place. The Metro Dog Foundation’s core missions are to improve the quality of Dog care worldwide, reduce pet care and treatment costs, and create a Dog community. The LUCKY Token will be created to help assist the Metro Dog Foundation with the missions mentioned above by giving power to the people. LUCKY coin focuses on developing some tools, each one targeting a different sector of the Dog world. These tools are used by individuals who will receive LUCKY Tokens as a reward. They can later use to pay for their Pet treatment or to purchase Pet products. The primary objective is not to compete with other crypto currencies, but rather to provide a solution and support for the Dog care services worldwide through a blockchain. The Metro Dog Foundation is interested in evaluating the actual substance and value that can be created with a coin (LUCKY) that represents the health of all individuals. The LUCKY coin will be both a FinTech and a logistic platform of the global Dog world. The Foundation’s exact contribution in ERC20 coins (LUCKY) used for Dog projects will be provided later on in the white paper.

Customer feedback is an essential part of all service industries aiming at long-term success. The Pet care World is no exception. No regulatory authority, no central institution, no powerful organization or individual can control the world better than the owner community. Trust among people is more valuable to the world players than constant, trustworthy feedback from the owners. A community is required for this to be achieved and this is where LUCKY coin steps in. LUCKY coin emphasizes the world’s challenges and reveals the solutions for increasing Pet practice’s efficiency. Implementing a blockchain-based industrial crypto currency can incentivize the world in solving the majority of the existing and future constraints. The four phases of implementation each with its milestones, goals, and focus are mentioned below.

We will stop here with the white paper sample. That’s how a white paper is prepared, highlighting the platform features and benefits followed by the project milestones. Mentioned below is a sample roadmap for the LUCKY coin launch. Roadmap is a must-have in any white paper (Fig. 6.4).
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig4_HTML.png
Fig. 6.4

LUCKY coin roadmap

That said, neither the white paper nor any other business collateral holds more weight than a working proof of concept. So, don’t stop with the white paper; develop a working prototype and demonstrate the concept that will drive more people to participate in your ICO.

Perform Legal Checks

The well-known phrase “leave it up to the professionals” is often said and sometimes heeded. However, when it comes to registering and creating ICOs and digital currencies this is advice to adhere to strictly. The Securities and Exchange Commission (SEC) does not officially recognize ICOs. Any interpretation that a communication is conveyed related to a security being offered, or any funder who may actually fund an ICO construes the message that an asset that yields a return other than what is being proposed is the funding of a token with no value and can be legally fatal to the issuer of the ICO. Entrepreneurs beware; let the legal professional, such as Cooley, Perkins Coie, and K&l Gates, all of whom have built strong reputations in navigating the legal minefield of ICO registration, perform this necessary function. No entrepreneur, looking to launch an ICO, wants any perception to be created through inadvertent communication that many have any funder thinking that they are buying an asset. Only a token that facilitates market transactions within the market network is being funded. No communications about a possible increase in prices or demonstrations of returns can ever be made. The legal professionals will draft the legal description and the token and construct the message to what the funders are receiving. Allowing the professionals to facilitate process and remaining transparent with all funders helps to avoid trouble from the regulators, such as the SEC of FinCEN. The governance framework established to manage participants to satisfy KYC and AML requirements and continuance of good compliance policy needs to be maintained during registration. SAFT (Simple Agreement for Future Tokens) has become an industry framework, designed and created by the legal stalwart Cooley; in particular, it has become an instrument and open-source legal framework for token sales. There are no global standards for ICOs and the registration and launching process varies from country to country. Put the effort in to comply with all relevant laws and regulations to remain clear of any legal ramifications. Following the best practices as a guideline is wise. Wiki your counsel and team:
  • Investigate to determine if the token you are offering during the ICO appears as security or not? What actions are necessary to alleviate the concerns that the token may be secure?

  • Target specific audiences during the token sale (geo-fencing).

  • It is a good practice to establish a foundation to champion the token.

Soliciting unregistered securities in the US can result in hefty fines and severe prison sentences. Nothing to be taken lightly or for granted. In the US, securities are heavily regulated and selling unregistered securities can result in significant fines and prison sentences. If a company develops a token and the company can distribute tokens at the time of the ICO, then the token is probably not secure, and there is not much problem. The company can crowdfund via an ICO just like Golem and accept money from anyone. However, if a company is raising funds to develop the token with a promise to distribute tokens to investors in the future, then it is conducting a token presale and not an ICO. The problem is that if a company is doing a token presale, it will possibly be seen as selling securities under the US Howey Test1 and will run into various SEC securities restrictions and potentially costly security registration and/or reporting requirements. To not be subject to US law, which may be applicable to foreign companies if they are seen as a Foreign Private Issuer by the SEC, some companies have incorporated outside the US and excluded US investors from their token presale. DFINITY, a Swiss organization, took this approach in their token presale stating “Due to regulatory uncertainty, you must not be a US person by citizenship or residency.”

Alternatively, a company can choose to be subject to, and comply with, US securities law to legally accept money from US investors in a token presale. CoinList (a platform for token-backed networks to raise funds through prelaunch token sales) and the SAFT aim to streamline US securities regulatory compliance and make it easy for companies to accept money from US investors in token presales legally. SAFT is modeled after the YC Simple Agreement for Future Equity (SAFE), which has become a standard angel and seed round investment agreement used by startups. SAFE promises investors future equity, while SAFT will seemingly promise investors future tokens.

Create the Token

Creating the token is the most straightforward part of the ICO process. When a token is created at its core, it means you have created an asset that your business needs to survive. Tokens can represent any tradable good. This includes digital coins, loyalty points, gold certificates, IOUs, in-game items, and so on. Tokens are somewhat similar to shares of a company sold to investors in an IPO transaction.

You should decide on certain things before creating anything. This includes how much you want to raise, the number of blockchain or Ethereum tokens you will issue, the number of tokens you are planning to retain for the team. The number of tokens you are planning to sell within the pre-ICO (if you decide to sell some of the tokens before the main ICO). It should also be agreed in advance in what scenario you will issue additional tokens. There are several platforms, such as Ethereum and waves, that allow you to create your tokens without having to create a blockchain from scratch. Smart contract controls the sale of these tokens. It is a computer program which can directly control the transfer of digital assets between parties under certain conditions.

Creating the initial value for the token is a very complicated process. We should consider a lot of options. It is called the tokenization process. Tokenization includes defining a unit of value to represent a specific asset. Within the blockchain and crypto currency space, tokens act as a computing protocol in which developers can digitally assign a token to become a medium for value exchange within a network of users. The critical differentiator for any tokenization effort is designing a crypto-economic reason for the token to exist and have real utility, beyond its speculative trading value. Crypto-economics is about aligning incentives of using a token system to encourage beneficial behaviors among all participants.

Though tokenization has recently become a buzzword, it can’t be considered as a new concept. As recently as 1950, the US was home to thousands of functioning forms of tokenized currency. Individual banks would issue banknotes; industrial and agricultural trading companies would issue “scrip” to help streamline transactions; and government, retail, and property brokers would offer alternate forms of currency to replace illiquid government-issued currency. For instance, the US dollar, after moving off a gold-backed standard, became a long-standing example of a traditional asset token. A dollar tokenized on the blockchain should have a value of about a dollar. But given the instantaneous rate of exchange possible in a distributed network of servers, like blockchain, even minor fluctuations in price over time can create arbitrage opportunities between the value of a token and the asset it represents.

Due to the ICOs and token generation events (TGEs), tokenization has become a hot topic. In these events, a new crypto currency, digital coin, or token that investors can purchase as an investment in the company will be issued by a company. Hence, the company can raise millions of dollars in capital without using the conventional VC funding model. The rapid growth of crypto currency is attracting investors and founders. They want to be a part of the next big thing. Many government regulatory agencies around the world have also been attracted. More clarity is still required in how tokens should be designed and represented to potential buyers. If the industry for companies and investors focuses on the value of the token within its network, it will be more useful to them. Some tokens that are intrinsically designed to support the specific business purpose of the project has more potential to be on the right track for long-term growth.

Let’s do the token economics for LUCKY coin. LUCKY team will generate by Ethereum smart contract an ERC20 standard token LUCKY Coin (LUCKY). All wallets supporting Ethereum, including Jaxx, MyEtherWallet.​com, and Ethereum Wallet, support ERC20 compliant tokens. The ICO contract will be directly linked to the token contract so that instant issuance of tokens will be possible. Users will be able to see in real time how many tokens they will get in return to their contribution and will not need to wait for an extended period to get them (sending will be enabled immediately after the ICO ends) (Fig. 6.5).
  • Total number of generated LUCKY will be 200,000,000

  • 60% of tokens will be sold in the ICO to secure funds for further product development, operations, and international expansion

  • 16% of tokens will be held by the project founders and the rest of the team that helped to develop the project with their hard work and dedication

  • 4% of tokens will be given to early stage angel investors, true believers, who showed a lot of trust and provided rocket fuel for our idea

  • 5% of tokens is intended for the initial stocking of the bounty pool to award contributors, who help build and curate our database of entities

  • 8% of tokens will be awarded to our advisors and ambassadors that helped the project with their knowledge and expertise

  • 7% of tokens will be reserved for future partners who will join the project at a later stage All tokens belonging to founders, employees, and seed investors will be reversely vested for 24 months with monthly cliffs

../images/465002_1_En_6_Chapter/465002_1_En_6_Fig5_HTML.png
Fig. 6.5

Sample token economics

The tokens that remain unsold will be transferred into the marketing budget. Tokens will be locked into a smart contract and accessible after one year when the global marketing campaign will begin. The lockdown is to prove to the contributors that we believe in the value of the vibe and as reassurance that the tokens won’t be sold immediately and will be spent only for marketing and sales activities.

Security Audit

An audit measures whether your organization is following good data protection practice. An audit helps organizations to identify whether they have effective policies and procedures in place. The code is reviewed by experts to ascertain if the code is secure where they check the possibility of any existing vulnerabilities, future bugs, or any errors in coding that could expose users.

Due to the complexity of a new programming environment, it is possible for even expert developers to make mistakes when writing code. It becomes critical to verify correctness using unit testing and tooling validation.

Some of the leading smart contract security auditing companies are mentioned below. Each one of them is known for their strengths. As a business owner, you will need to research before hiring the advisory company to help you achieve your goals.
  1. 1.

    New Alchemy is known as a strategy and technology advisory company that specializes in tokenization.

     
  2. 2.

    Solidified.​io is a crowdsourcing company where any developer can submit their code for comprehensive quality review by a community of qualified and certified experts.

     
  3. 3.

    Coinfabrik is a firm that helps other firms to develop smart contracts. It is also involved in the development of hyper ledger, the private blockchain, supply chain blockchain, wallet protection, loan data sharing, and safe, reliable crypto exchanges in addition to helping with smart contract audits.

     
  4. 4.

    Zeppelin reviews code and develops a report on the quality of a company’s code, and the result is published online—same is the case with New Alchemy.

     
  5. 5.

    Token Market provides a complete token launching set of services including creating tokens, developing and auditing smarty contracts, and hosting crowd sale, among other services.

     

Leadership

The team is the essential part of any project. After taking a look at what the project aims to solve along with the crowd sale structure and token utility, it’s always important to make sure a programmer is present in the team or at least knows the technical requirements of a blockchain project.

Blocklancer’s CEO/Co-founder makes it very easy to understand whether or not the project has team members who can navigate the space.  He’s a computer scientist and also a university graduate on the topic. The project also has other technically versed members, but a Technical Founder is someone, in my experience, venture capitalists and angel investors want to have in a tech startup they’re deciding to invest in.

Blocklancer’s Founder made sure to put his face out there from the beginning. He also did an interview with CryptoCandor in which he explained essential facets of the Blocklancer ecosystem in detail. This is like the all-time best confirmation any ICO investor can see in a project because it ensures that their CEO/Lead Developer exists!

Manage the Community

It is probably the second-most important step in the ICO process. Token sales depend on the investors, and hence it is essential to note that to make your token sales to reach somewhere, enough investors should know about it. It is sad, but a fact, that initial hype drives the majority of token sales. This hype ideally should be supported by investors that support both you and your token, and will not sell at the first opportunity. The ICO marketing channels that I would suggest investing time and resources into are as follows:

Forums

The most famous is Bitcointalk, where practically all the ICO projects are run. You will receive many reviews — positive and negative—but they will help you to improve your project.

ICO Calendars

Lists of “top ICOs” are often created by bloggers and journalists (https://​itsblockchain.​com/​top-5-upcoming-icos-to-invest-in/​) by the data from specific ICO calendar sites mentioned below:

Quora Discussions

A platform like Quora can play an important role here. Many discussions exist on Quora about different ICOs and specific crypto currencies. You can actively participate in these discussions and link back to your ICO landing page.

Slack and Telegram

Your channel on Slack and Telegram must be created in your communications strategy. Potential investors live on these channels and will be able to connect with the project’s founders, team members, and also with one another. Monitoring these channels at all times is crucial. All questions and false accusations raised by users must be answered promptly.

Media Coverage

Good PR can help a company in various ways. Quality PR in the right media outlets is required to help establish credibility and to position your company as an innovator and thought leader. It also has the potential to convince people of your business model. The mainstream media are becoming more and more cynical about ICOs. Thus having a great story outside of the ICO is critical. It is crucial to make sure to communicate with your audience both before and throughout the campaign. Also, be mindful that pre-ICO media is quite different than the post-ICO press, as the target demographic changes.

ICO Crowd Sale

A successful crowd sale is judged by the pre-allotment of tokens reserved by the ICO transferring from the assigned account of the ICO to the accounts of all investors participating in the ICO that accurately reflects the purchase amount and the funds from the investor transferring to the funding account of the ICO. Immediately after the ICO crowd sale event, a reconciliation process happens to ensure delivery of tokens and transfer of funds. If there are no errors or exceptions and initial investors are satisfied with receiving their assigned tokens, a successful ICO crowd sale has occurred.

Ethereum Development Model

Traditionally application development is being laid with a centralized server for managing and serving all the requests. A hosting provider is required to host your web application for which there are hosting providers like AWS, Heroku, or a VPS. All the clients interact with this one central application. Clients can be a browser or another API consuming your service. When a client requests the server, the server does its magic, talks to the database and/or cache, reads/writes/updates the database, and serves the client.

Most of the times this architecture works very well. However, there are specific applications where it would be beneficial if that database was publicly and securely accessible by everyone and you don’t have to rely on this web app owner for your data (Fig. 6.6).
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig6_HTML.png
Fig. 6.6

Traditional centralized application development

Let’s take eBay as an example. Consider yourself a power seller who has earned hundreds of good reviews. But for some reason, your account got suspended by eBay. That would be very bad and could severely impact your business. In this situation it would be nice if all your reviews and ratings could be moved to another platform (say eBay Competitor). Though eBay is a popular and trusted third party between buyers and sellers, each sale includes a commission for them. Imagine if there was a way to eliminate eBay from the transaction between buyer and seller. This way, you can save the amount you are spending on commission. Your data can also be accessed. Here decentralized applications (DAPPS) come into the picture. DAPPS (decentralized applications) can be built very easily using Ethereum. If you notice, every client (browser) tends to communicate with its instance of the application. No central server is present for all clients to connect to. This means a full copy of the blockchain running on their computer/phone and so on will be needed by every person who wants to interact with a DAPP. That means before an application can be used, the entire blockchain has to be downloaded, and then you can start using the application. Initially this might sound ridiculous, but it has the advantage of not relying on a single central server. Figure 6.7 highlights a reference model of an Ethereum DAPP at a high level.
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig7_HTML.png
Fig. 6.7

Ethereum development model

Solidity Programming Language

Solidity is a high-level language whose syntax is similar to that of JavaScript, and it is designed to compile the code for the Ethereum Virtual Machine. Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like objects in object-oriented programming, each contract contains state variables, functions, and standard data types. Contract-specific features include modifier (guard) clauses, event notifiers for listeners, and custom global variables. In the Ethereum ecosystem, Solidity is used to create contracts for voting, crowdfunding, blind auctions, multi-signature wallets, and more.

Before writing any Solidity, you need to mention to the compiler the version of Solidity it’s going to use. An example is discussed below:
pragma solidity ^0.4.19;

Object-oriented programming languages have classes and solidity has contracts. Contracts are similar to classes in object-oriented programming languages. The fundamental building block of an Ethereum app is known as Contract, which contains all the variables and functions. The procedure for creating a Contract is mentioned below.

contract Contract1 {
}

Here, the contract name is FirstContract. Every content between the curly braces is the body of the contract. Nothing is in the body of the contract (what it’s going to do or what code it will run). But word of contract marks it as a contract in the code, much in the same way the word object or function would in JavaScript.

Blockchain contains state variables which are stored in contract storage. Every contract has its storage. They’re stored in memory with javascript variables. With state variables, they’re stored on the blockchain. Pretty darn cool. We can create a string variable, name it firstVariable, and place it inside our first contract:
contract Contract1 {
  string Variable1;
}
Uint is an unsigned integer data type. The idea of signed and unsigned variables is present in solidity. Signed variables can have any value be it positive or negative. But an unsigned integer must have only a positive value. It can’t be negative.
contract Contract1 {
  uint Uint1;
}
Solidity also has functions. Functions are blocks of code to be executed. A function declaration in Solidity has to be written like this:
function Function1(string Param1, string Param2) {
}

A declared function tells the compiler about a function’s name and its parameters and so on. We have only scratched the surface of the Solidity programming language to construct our token in the next section. For detailed documentation on the Solidity programming, please refer to the below link.

http://​solidity.​readthedocs.​io/​en/​v0.​4.​21/​index.​html

Smart Contract

Smart contracts are the pieces of code that live on the blockchain and are designed to execute commands exactly how they were instructed to. They are also capable of reading other contracts, making decisions, sending Ethereum, and executing other contracts. Thus contracts will exist and run as long as the whole network exists and will only stop in scenarios such as if they run out of gas or if they were programmed to self-destruct.

What Can You Do with Contracts?

Almost anything can be done. Here, let’s do some simple things. You will get funds through crowdfunding that, if successful, it will supply a radically transparent and democratic organization. This organization will only obey its citizens and will neither swerve away from its constitution nor can it be censored or shut down. And all that can be achieved in less than 300 lines of code.

Now let’s apply the same concept to LUCKY DOG. We will develop a small application flow using the smart contract with Solidity. The concrete flow of implementation is as follows:
  • Setting up the development environment

  • Creating the Truffle project using the Truffle Box

  • Making the description of the Smart Contract

  • Compiling and Migrating the Smart Contract

  • Testing the Smart Contract

  • Creating the UI attached to the Smart Contract

  • Using the DAPP with browser

Creating a Truffle Project

Let’s set the environment that can use “node” and “npm.”

If the OS is Debien GNU, you can install the recommended version of node.js 8.x as follows.

$ apt-get update
$ curl -sL https://deb.nodesource.com/setup_8.x | bash -
$ apt-get install -y nodejs

To start with, the Truffle has to be installed.

$ npm install -g truffle

Thus we can say that Truffle is a development framework of Ethereum which is one of the most useful frameworks for smart contract development. Here compiling and deploying the source code can be done efficiently. You will have to create a directory called “pet-shop-example” and work in this directory. Normally, initialization is done with truffle init. Firstly, an empty project has to be created. For this tutorial, let’s develop it from a well-known project “Truffle Box.” You can find more details on truffle box here.

https://​truffle-box.​github.​io/​

$ mkdir pet-shop-example
$ cd pet-shop-example
$ truffle unbox pet-shop
Then, the following files and directory structure is prepared inside the pet-shop-example (Fig. 6.8).
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig8_HTML.png
Fig. 6.8

Truffle project

The directories and files that are used are mentioned below.
  • contracts directory: This contains the source files of solidity describing the Smart Contract

  • migrations directory: migration system used when deploying the Smart Contract

  • test directory: Test files that are written in Javascript and Solidity

  • truffle.js: Configuration file for Truffle

Creating the Smart Contract

Create a file called “Adoption.sol” in the created contracts directory and write the following.

pragma solidity ^0.4.4;
 contract Adoption {
  address[16] public adopters;
 function adopt(uint petId) public returns(uint) {
  require(petId >= 0 && petId <= 15);
  adopters[petId] = msg.sender;
  return petId;
 }
 function getAdopters() public returns (address[16]) {
 return adopters;
  }
 }

Let’s look at each part, in turn, specifying the version of the solidity compiler. Also, solidity adds a semicolon (;) at the end of the line like javascript.

pragma solidity ^0.4.4;

I declare a contract named Adoption. I will implement the contract in this.

contract Adoption {
・・・
 }

Here “adopters” which is a state variable is declared. Since solidity is a static language, declaring the data type of the variable is required. A unique data type “address” exists in Solidity in addition to general data types such as string and uint. The address of the account is stored in “Address.” Here address is an array, and 16 addresses will be present in the variable called “adopters.” As the address is described as public before the “adopters” variable, it can be viewed by anyone who has access to that contract.

address[16] public adopters;

After declaring the variable like this, I declare the method of the contract.

function adopt(uint petId) public returns (uint) {
 require(petId >= 0 && petId <= 15);
 adopters[petId] = msg.sender;
 return petId;
}

The variable “petId” which is an integer type is set to 0 to 15 based on the array length of adopters. (Array starts with the index of 0.) So I use require () for making petID 0 through 15.

msg.sender signifies the address of the person that called this function.

So “adopters [petId] = msg.sender;” adds the caller’s address to the adopters array.

And petId is returned to the caller as the response.

With the help of the adopt function mentioned above, it’s now possible to return one address, since petId is the key of adopters array.

However, since 16 API calls in every reload are required to be done, I will return the whole adopters array with the following getAdopters function.

function getAdopters() public returns (address[16]) {
  return adopters;
 }

The variable “adopters” has already been declared. Hence the data type needs to be specified, and the return value has to be returned. So this was the Smart Contract. To summarize the contents, I have created the below-mentioned Adoption contracts. Compiling and migrating this Smart Contract needs to be continued.

Compile the Smart Contract

This is the process where the source code that is written in the programming language is translated into a machine language. The computer can directly execute this machine language. In other words, it will convert the code written in the solidity language into bytecode. Thus the Ethereum Virtual Machine which is the virtual machine of Ethereum will be able to execute it. In the directory containing DAPP, launch Truffle Develop at the terminal, and so on.

$ truffle develop

Then enter “compile” at the started truffle develop console.

$ truffle(develop)> compile

If the compilation is successful, the following output will be displayed.

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

Though there will be a warning, which is public, it is fine to go through. (Let’s keep the truffle develop console open all the time.)

Migration

It means moving an existing system or the like to a new platform. In this case, the file that is being migrated will do the deployment of the created Adoption contract to the blockchain network of Ethereum. If we look at the migrations directory, there should already be a javascript migration file called “1_initial_migration.js.” Migrations.sol is deployed by this file in the contracts directory and managed so that a series of smart contracts can be migrated correctly.

Create a migration file named “2_deploy_contracts.js” in the migrations directory. In the migration file, write as follows.

const Adoption = artifacts.require("Adoption");
module.exports = (deployer) => {
  deployer.deploy(Adoption);
 };

Let’s run the migrate command on the running truffle develop console.

$ truffle(develop)> migrate

And it will be successful if the below-mentioned output is done.

Running migration: 1_initial_migration.js
Deploying Migrations...
 ... 0xa1f5bc4affc464999763799648db42acae31772140af652d27f921ee11cb330d
  Migrations: 0x8cdaf0cd259887258bc13a92c0a6da92698644c0
Saving successful migration to network...
 ... 0xd7bc86d31bee32fa3988f1c1eabce403a1b5d570340a3a9cdba53a472ee8c956
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying Adoption...
 ... 0xe46e604dce4322e0492be99b5d3744468e20f8a233e3da551dd42ad9272839b9
 Adoption: 0x345ca3e014aaf5dca488057592ee47305d9b3e10
Saving successful migration to network...
 ... 0xf36163615f41ef7ed8f4a8f192149a0bf633fe1a2398ce001bf44c43dc7bdda0
Saving artifacts...

With this, a Smart Contract can be created, compiled, and deployed in the test block chain of the local environment. Next, let’s test whether this works correctly.

Testing the Smart Contract

Testing the Smart Contract is one of the most important steps. This is because design mistakes and bugs in smart contracts are related to the user’s tokens (assets), which can cause severe damage to users. The smart contract conducts two different tests. This includes the manual test and the automatic test. Let’s check the operation both manually and automatically.

In the case of the manual test, the operation of the application is checked by using tools of a local development environment such as Ganache. These are easy to understand as they refer to transactions in the GUI. In Truffle, the automatic test of the Smart Contract can be described in both javascript and Solidity, but here we will use Solidity.

In the created test directory, create a file called “TestAdoption.sol” and write the following.

pragma solidity ^0.4.11;
 import "truffle/Assert.sol";
 import "truffle/DeployedAddresses.sol";
 import "../contracts/Adoption.sol";
contract TestAdoption {
  Adoption adoption = Adoption(DeployedAddresses.Adoption());
 function testUserCanAdoptPet() {
  uint returnedId = adoption.adopt(8);
  uint expected = 8;
  Assert.equal(returnedId, expected, "Adoption of pet ID 8
should be recorded.");
 }
 function testGetAdopterAddressByPetId() {
  address expected = this;
  address adopter = adoption.adopters(8);
  Assert.equal(adopter, expected, "Owner of pet ID 8 should be recorded.");
 }
 function testGetAdopterAddressByPetIdInArray() {
  address expected = this;
  address[16] memory adopters = adoption.getAdopters();
  Assert.equal(adopters[8], expected, "Owner of pet ID 8
should be recorded.");
 }
}

It’s a bit long, but let’s look at it after disassembling.

pragma solidity ^0.4.11;
 import "truffle/Assert.sol";
 import "truffle/DeployedAddresses.sol";
 import "../contracts/Adoption.sol";
contract TestAdoption {
 Adoption adoption = Adoption(DeployedAddresses.Adoption());
 /*
 *Add a function described later here
 */
 }

At first, let’s import the three contracts mentioned below.

Assert.sol: This includes the various checking works during testing.

DeployedAddresses.sol: Here the address of the contract deployed at the test time is obtained.

Adoption.sol: Test the Smart Contract.

Create a contract called “TestAdoption” and declare the variable adoption. “adoption” contains “DeployedAddresses.

In the TestAdoption contract below, let’s define the functions used for testing.

function testUserCanAdoptPet() {
 uint returnedId = adoption.adopt(8);
 uint expected = 8;
 Assert.equal(returnedId, expected, "Adoption of pet ID 8
should be recorded.");
 }

Let’s test the adopt () function defined in the Adoption Contract. If the adopt () function is functioning correctly, it will return the same petId (return value) as the number of the argument.

In this case, put petId of 8 into the adopt () function and make sure it matches the return value petId with Assert.equal ().

function testGetAdopterAddressByPetId() {
 address expected = this;
 address adopter = adoption.adopters(8);
 Assert.equal(adopter, expected, "Owner of pet ID 8 should be
recorded.");
 }

Let’s check whether the correct owner’s address is associated with petId. We will test whether the owner’s address with pet ID 8 is correct. By the way, the variable “this” represents the address in the current contract.

function testGetAdopterAddressByPetIdInArray() {
 address expected = this;
 address[16] memory adopters = adoption.getAdopters();
 Assert.equal(adopters[8], expected, "Owner of pet ID 8
should be recorded.");
 }

Finally, we have to check whether the array “adopters” that contain all the addresses that are returned correctly. The “memory” attribute is not saved in the “storage” of the contract. This means that it is a temporarily recorded value. Now that we can write the test let’s run this test file with Truffle Develop.

$ truffle(develop)> test

We have successfully tested when the following output is displayed.

Using network ‘develop.’
 Compiling ./contracts/Adoption.sol...
 Compiling ./test/TestAdoption.sol...
 Compiling truffle/Assert.sol...
 Compiling truffle/DeployedAddresses.sol...
TestAdoption
 ✓ testUserCanAdoptPet (133ms)
 ✓ testGetAdopterAddressByPetId (112ms)
 ✓ testGetAdopterAddressByPetIdInArray (196ms)
 3 passing (1s)

Develop the User Interface

So far, we have created the Smart Contract which is deployed in the test blockchain of the local environment and tested whether it usually works. Next, let’s make a user interface where we can see pet shops on the browser. Truffle Box makes the basic structure. So now you will have to add a characteristic function in Ethereum.

The src directory is the front-end part of the application, and you will edit the /src/js/app.js file in it.

App = {
 web3Provider: null,
 contracts: {},
 init: function() {
  // Load pets.
 $.getJSON(‘../pets.json’, function(data) {
  var. petsRow = $(‘#petsRow’);
  var. petTemplate = $(‘#petTemplate’);
 for (i = 0; i < data.length; i ++) {
  petTemplate.find(‘.panel-title’).text(data[i].name);
  petTemplate.find(‘img’).attr(‘src’, data[i].picture);
  petTemplate.find(‘.pet-breed’).text(data[i].breed);
  petTemplate.find(‘.pet-age’).text(data[i].age);
  petTemplate.find(‘.pet-location’).text(data[i].location);
  petTemplate.find(‘.btn-adopt’).attr(‘data-id’, data[i].id);
  petsRow.append(petTemplate.html());
 }
 });
 return App.initWeb3();
 },
 initWeb3: function() {
 /*
 *①Add code here
 */
  return App.initContract();
 },
 initContract: function() {
 /*
 * ②Add code here
 */
 return App.bindEvents();
 },
 bindEvents: function() {
 $(document).on(‘click’, ‘.btn-adopt’, App.handleAdopt);
 },
 markAdopted: function(adopters, account) {
 /*
 * ③Add code here
 */
 },
 handleAdopt: function(event) {
 event.preventDefault();
 var petId = parseInt($(event.target).data(‘id’));
 /*
 * ④Add code here
 */
 }
 };
 $(function() {
 $(window).load(function() {
 App.init();
  });
 });

Installation of Web 3

First, you will have to make sure if the instance of web3 is “active.” If it is “active,” it will be replaced with the web3 object of the created application. If it’s not “active,” create a web3 object in the local development environment.

if (typeof web3 !== 'undefined') {
 App.web3Provider = web3.currentProvider;
 } else {
 App.web3Provider = new Web3.providers.HttpProvider(‘http://localhost:9545’);
 }
 web3 = new Web3(App.web3Provider);

Instantiation of Contract

Since communicating with “Ethereum Network” via web 3 is possible, the “Smart Contract” that is created will be instantiated. For achieving that, we need to tell web 3 where the contract is and how it works.

$.getJSON('Adoption.json', function(data) {
 var AdoptionArtifact = data;
 App.contracts.Adoption = TruffleContract(AdoptionArtifact);
 App.contracts.Adoption.setProvider(App.web3Provider);
 return App.markAdopted();
});

“Truffle contract” is a useful library of Truffle. This is a library on web3, which makes it easy to connect with “contract.” For example, the truffle contract synchronizes the contract information during migration, so you do not need to change the deployed address manually. The Artifact file comprises the information on the deployed address and ABI (Application Binary Interface). Information is represented by ABI on the interface, that is, the variable, function, parameter, and so on, of the contract.

Insert Artifact into the TruffleContract() function and instantiate the contract.

Then set the App.web3Provider created by instantiating web3 to its contract.

UI Update

Let’s make sure that the state of the pet kept changed, and the UI is updated. First, getAdopters () is called on an instance of the deployed Adoption contract. The call () function does not change the state of the blockchain. It reads the data, so you do not need to pay gas. And check whether each petId is tied to an address. If an address exists, change the button to success so that you cannot press the button.

var adoptionInstance;
 App.contracts.Adoption.deployed().then(function(instance) {
 adoptionInstance = instance;
 return adoptionInstance.getAdopters.call();
 }).then(function(adopters) {
 for (i = 0; i < adopters.length; i++) {
  if (adopters[i] !== ‘0x0000000000000000000000000000000000000000’) {
  $(‘panel-pet’).eq(i).find(‘button’).text(‘Success’).attr(‘disabled’, true);
 }
 }
 }).catch(function(err) {
 console.log(err.message);
 });

Manipulating the Adopt Function

In this case, after confirming the error of the account using web 3, we will process the actual transaction. The adopt () function does transaction execution, and it takes an object containing the address of petId and the account as an argument.

Then, the transaction execution result will be reflected in the UI as the new data.

var adoptionInstance;
 web3.eth.getAccounts(function(error, accounts) {
  if (error) {
  console.log(error);
 }
 var account = accounts[0];
 App.contracts.Adoption.deployed().then(function(instance) {
  adoptionInstance = instance;
  return adoptionInstance.adopt(petId, {from: account});
 }).then(function(result) {
 return App.markAdopted();
 }).catch(function(err) {
  console.log(err.message);
 });
 });

Now if you are ready to use DAPP, let’s use the created DAPP in your browser!

Completion of the Application

We will use MetaMask which is the extension of Chrome. During that time, the account will use the account for Truffle Develop by using the following Wallet Seed. This Seed is displayed when Truffle Develop is executed. (It is common seed.)
candy maple cake sugar pudding cream honey rich smooth crumble sweet treat
(If you are using MetaMask now you can go from the menu Lock to the following screen.) (Fig. 6.9).
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig9_HTML.png
Fig. 6.9

Metamask wallet

The MetaMask has to be connected to the blockchain created by the Truffle Develop. To achieve that, you will have to change it from “Main Network” on the upper left to “Custom RPC.” And let’s change to http://​localhost:​9545 for “Truffle Develop.” The display changes from “Main Network” to “Private Network” (Fig. 6.10).
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig10_HTML.png
Fig. 6.10

(a) Connecting to the Ethereum network. (b) Metamask accounts

Accounts that are made from the seed mentioned above have weak 100ETH. It is drawn by the amount of gas consumed in the contract deployment. Firstly, you will have to set up the MetaMask as it has been stated above. Then the local web server can be started by executing the following code in terminal, (The lite - server library can be used, since bs - config.json and package.json have been created.)

$ npm run dev
Then, DAPP like the one shown below can be displayed on the browser (Fig. 6.11).
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig11_HTML.png
Fig. 6.11

Browser display

If the “adopt” button of your favorite pet is clicked, the transaction is sent by “MetaMask,” and then you can purchase pets by ETH payment! (Fig. 6.12).
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig12_HTML.png
Fig. 6.12

Adopt payment processing

Create an ERC 20 Token on Ethereum

A specific set of functions known as ERC20 are required by the developers to use in their tokens to make them ERC20 compliant. This is not an enforced rule. To make their tokens undergo interactions with various wallets, exchanges, and smart contracts without any issues, most developers involved in developing DAPP are encouraged to follow the standards. This gave everyone an idea of how future tokens are expected to behave. ERC20 tokens have gotten widespread approval, and most of the DAPPS sold on initial coin offerings (ICOs) have tokens based on the ERC20 standard.

We are familiar with ICOs by now. Investors invest millions of dollars in many projects that promise a revolutionary technology through smart contracts. It will change the world. Most of the time there is only that, a promise, along with a white paper and a website and the MVP is developed after the crowd sale. In this section, we’ll demonstrate how easy it is actually to make your own ERC20 token for the Ethereum blockchain.

Now, let’s revisit the LUCKY token that we discussed in Chap. 4 and try to build it on the Ethereum blockchain. To give a quick recap, the LUCKY coin is a utility token used in the business of Dog care. Figure 6.13 illustrates the Lucky coin marketplace.
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig13_HTML.png
Fig. 6.13

Lucky coin marketplace

LUCKY coin is a blockchain venture with the goal of revolutionizing the dog world through blockchain technology. The platform is set to offer its LUCKY ERC20 token for use in its global ecosystem of pet care. The crypto currency will facilitate dog care services and data management between pet owners, veterinarians, dog insurers, dog breeders, dog authenticators, dog walkers, dog groomers, and many other participants. As the first crypto for the dog world, LUCKY coin plans to introduce a reward program that will inspire participation across the world of dog owners. Each dog owner or veterinarian who makes a contribution that will benefit the LUCKY coin ecosystem will receive a reward through a transparent and decentralized reward scheme.

LUCKY Coin: Decentralized Pet Care Blockchain Solution Features

With the objective of improving the worldwide health care of dogs, LUCKY coin plans to initiate this through three features on its platform. The first feature is the dog assurance concept. In this, the dog owner has the option to ensure his or her pet with a blockchain-based insurance scheme that is aligned to suit their dog’s needs. Each insurance cover will be rated on the basis of the health condition of the pets and aligned to the dog’s veterinarian.

A health database will protect pet health records and data in a decentralized database. The pet owner or the veterinarian will have access to the information ecosystem through special permission. If the pet owners want to keep up with post-treatment or monitoring of their dog’s health condition, they can do so through an aftercare mobile app. The application will be made available to the Android operating system to achieve the platform’s goal of a global pet world.

ERC 20 Token Definition for LUCKY DOG

For creating an ERC20 token, you need the following:

../images/465002_1_En_6_Chapter/465002_1_En_6_Figa_HTML.png

The decimal places are where things can get tricky. Most tokens have 18 decimal places. It means that you can have up to 0.0000000000000000001 tokens. When creating the token, you’ll have to keep in mind the decimal places you’d like and how it should fit into the larger picture of your project. For illustration, let’s keep it simple such that either the people will have a token or they won’t have one. We are not keeping anything in between. So, let’s choose 0. But you could choose 1 if you wanted people to have half a token, or 18 if you wanted it to be “standard.”

Token Smart Contract Specification

Let’s define specific roles for the token maintenance purposes.

Creator—Person who develops and deploys the Smart Contract (Development Team).

Administrator—Person who maintains the business. In our case, Mark or his immediate subordinate will become the admin as this will be the highest level of control on the Smart Contract behavior.

Let’s now lay down some ground rules for our token contract to prepare a spec.
  1. 1.

    The coin must be called LUCKY DOG and must have the symbol as LUCKY.

     
  2. 2.

    The creator must be able to specify the initial supply, total supply, max supply, and decimal units during the creation.

     
  3. 3.

    Users must be able to transfer the coins to each other’s account.

     
  4. 4.

    Any debt or negative balance should not be allowed.

     
  5. 5.

    There should be one administrator who may not be the currency creator. That is, the currency creator must make someone as admin during the creation.

     
  6. 6.

    Anyone must be able to buy or sell the LUCKY using Ethereums.

     
  7. 7.

    Buy or sell price must be set by Admin at any time.

     
  8. 8.

    Admin must be able to transfer the administrator role to any other address.

     
  9. 9.

    Admin must be able to mint the new LUCKY to anyone’s address.

     
  10. 10.

    Admin must be able to freeze or unfreeze the coins of anyone’s account.

     
  11. 11.

    Admin must be able to set up a spender account with an allowance limit.

     

Now that we have a token definition and a Smart Contract specification let’s get started with some coding.

Minimum Viable Token

We will create a digital token. Coins, loyalty points, gold certificates, IOUs, in-game items, and so on, are the fungible tradable goods that can be represented by tokens in the Ethereums ecosystem. All tokens implement some essential features in a standard way. Your token and the Ethereums wallet will be instantly compatible with each other. I will also be compatible with any other client or contract that uses the same standards.

The standard token contract can be quite complicated. A very basic token boils down to this (Fig. 6.14):
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig14_HTML.png
Fig. 6.14

Minimum viable token

Breaking down the code into its bare necessities may give you a clear picture. There are three specific parts of this function:
  • The mapping.

  • Giving the creator all the tokens.

  • Transferring the token to a sender for Ethereum.

The Mapping

In this part, the mapping will be done. Here a database is created where everyone will be able to view your token balance. Tokens like ETH are logged into an open ledger. All the balances and transactions relating to that particular token will be visible to everyone.
../images/465002_1_En_6_Chapter/465002_1_En_6_Figb_HTML.png

Giving the Creator All the Tokens

In this part of the function, whoever has created the smart contract and tokens will get all the tokens:
../images/465002_1_En_6_Chapter/465002_1_En_6_Figc_HTML.png

Transfer the Token to a Sender for Ethereum

Finally, we reached the last part of the code. An equivalent amount of token can be made available to the sender for the Ethereum that they invest into the DAPP.
../images/465002_1_En_6_Chapter/465002_1_En_6_Figd_HTML.png

Transfer logic is very self-explanatory. It first checks the sender’s available balance of the tokens. Then it deducts the said amount from the sender’s balance and then credits that value to the recipient’s balance.

Complete Token Contract for the LUCKY DOG is available in Appendix A.

Create an ICO (Crowd Sale) Contract on Ethereum

The process of crowdfunding includes raising funds for a project or venture from the masses. This is a place where to generate a large investment people make investments in smaller amounts. This investment is used to meet the requirements. The investment plan is distributed across the masses. This is done to prevent any single person from spending more than he can spare. Also, there are instances where artists, authors, philosophers have crowdfunded their works.

Blockchain technology manages the value exchange under contract. This feature will come handy when it comes to managing rewards-based and equity-based crowdfunding campaigns. Automation of the whole process of assigning relevant rewards and equity against their contributions is possible by using blockchain-based smart contracts for crowdfunding. A set of predefined crowdfunding conditions is programmed on smart contracts. The system can be automated so that the smart contract is executed. The objective of this is issuing certain rewards or proof of ownership of a certain percentage of equity that is based on the amount contributed toward the campaign.

Crowd sales are a kind of crowdfunding campaigns in the crypto currency world. Here the premined crypto tokens for the platform under development are sold using the digital currency platform by exchanging Bitcoin, Ethereum, or some other established digital currency. The raised funds are then used for further developing the platform. The crypto tokens bought by the participants of the crowd sale are equivalent to both rewards and equity (depending upon the model followed by the platform). Blockchain technology and digital currencies have proven to be capable of being retrofitted to meet the needs of any industry, including the time-tested ones. Crowdfunding is one such segment, into which the technology is capable of blending in, entirely. Let’s build the crowd sale contract for the LUCKY coin using Solidity.

LUCKY Token contract definition

../images/465002_1_En_6_Chapter/465002_1_En_6_Fige_HTML.png

ICO Smart Contract Specification

  1. 1.
    CrowdSale smart contract for LUCKY must be able to initialize the following:
    • Ethereum price for LUCKY (ETH)

    • Minimum ETH required to buy LUCKY

    • Funding Minimum Target (ETH)

    • Funding Maximum Target (ETH)—Soft Cap

    • Funding Maximum Target (ETH)—Hard Cap

    • Crowd Sale/LuckyDog website

    • Beneficiary Account Address

    • Duration of Crowd sale

     
  2. 2.
    Crowd Sale smart contract should maintain a state that will indicate one of the following:
    • Fund-raising

    • Failed

    • Successful

    • Closed

     
  3. 3.

    Provide a function to pay ETH and buy LUCKY tokens

     
  4. 4.

    Should maintain a list of contributor address and the amount contributed in ETH

     
  5. 5.

    Provide properties to view the total amount of ETH raised so far and the current balance of the ETH

     
  6. 6.

    Check the status of the funding after each contribution

     
  7. 7.

    If the status reaches the required maximum limit, then perform the payout to the beneficiary account and trigger the end of the LifeCycle event

     
  8. 8.

    If the status is InComplete and Expired, then execute the refund logic to send back the contributed ETH and trigger the end of the LifeCycle event

     
  9. 9.

    Perform necessary validations and log all events

     
The way this particular crowd sale contract works is that you will have to set an exchange rate for your token. A proportional amount of tokens in exchange of their Ethereum will immediately be available to the donors. A funding goal and a deadline will also have to be set. Once that deadline is over, you can ping the contract, and if the goal were reached, it would send the Ethereum raised to you. Otherwise, it goes back to the donors. Donors keep their tokens even if the project doesn’t achieve its goal, as a proof that they helped. Below is the complete crowd sale contract that we are going to use for LUCKY DOG project (Fig. 6.15).
../images/465002_1_En_6_Chapter/465002_1_En_6_Fig15_HTML.png
Fig. 6.15

ICO smart contract flow diagram

ICO Smart Contract Code

../images/465002_1_En_6_Chapter/465002_1_En_6_Figf_HTML.png
../images/465002_1_En_6_Chapter/465002_1_En_6_Figg_HTML.png

ICO Smart Contract Flow Diagram