<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Cryptocurrency - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Cryptocurrency - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:31:13 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/cryptocurrency/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Create Your Own Cryptocurrency Using Python ]]>
                </title>
                <description>
                    <![CDATA[ By Alfrick Opidi With the current rise of cryptocurrencies, blockchain is creating a buzz in the technology world. This technology has attracted so much attention mainly because of its ability to guarantee security, enforce decentralization, and qui... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/create-cryptocurrency-using-python/</link>
                <guid isPermaLink="false">66d45d9736c45a88f96b7cab</guid>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 08 Oct 2019 22:16:05 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/10/blockchain-3448502_1920-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Alfrick Opidi</p>
<blockquote>
<p>With the current rise of cryptocurrencies, blockchain is creating a buzz in the technology world. This technology has attracted so much attention mainly because of its ability to guarantee security, enforce decentralization, and quicken processes to several industries—especially to the financial industry.</p>
</blockquote>
<p>Essentially, a blockchain is a public database that irreversibly documents and authenticates the possession and transmission of digital assets. Digital currencies, like Bitcoin and Ethereum, are based on this concept. Blockchain is an exciting technology that you can use to transform the capabilities of your applications.</p>
<p>Of late, we’ve been seeing governments, organizations, and individuals using the blockchain technology to create their own cryptocurrencies—and avoid being left behind. Notably, when Facebook proposed its own cryptocurrency, called <a target="_blank" href="https://libra.org/en-US/white-paper/#introduction">Libra</a>, the announcement stirred many waters across the world.</p>
<p>What if you could also follow suit and create your own version of a cryptocurrency?</p>
<p>I thought about this and decided to develop an algorithm that creates a crypto.</p>
<p>I decided to call the cryptocurrency <strong>fccCoin</strong>.</p>
<p>In this tutorial, I’m going to illustrate the step-by-step process I used to build the digital currency (I used the object-oriented concepts of the <a target="_blank" href="https://www.freecodecamp.org/news/best-python-tutorial/">Python</a> programming language).</p>
<p>Here is the basic blueprint of the blockchain algorithm for creating the <strong>fccCoin</strong>:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Block</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>():</span>

    <span class="hljs-comment">#first block class</span>

        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculate_hash</span>():</span>

    <span class="hljs-comment">#calculates the cryptographic hash of every block</span>


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BlockChain</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
     <span class="hljs-comment"># constructor method</span>
    <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">construct_genesis</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-comment"># constructs the initial block</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">construct_block</span>(<span class="hljs-params">self, proof_no, prev_hash</span>):</span>
        <span class="hljs-comment"># constructs a new block and adds it to the chain</span>
        <span class="hljs-keyword">pass</span>

<span class="hljs-meta">    @staticmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_validity</span>():</span>
        <span class="hljs-comment"># checks whether the blockchain is valid</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">new_data</span>(<span class="hljs-params">self, sender, recipient, quantity</span>):</span>
        <span class="hljs-comment"># adds a new transaction to the data of the transactions</span>
        <span class="hljs-keyword">pass</span>

<span class="hljs-meta">    @staticmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">construct_proof_of_work</span>(<span class="hljs-params">prev_proof</span>):</span>
        <span class="hljs-comment"># protects the blockchain from attack</span>
        <span class="hljs-keyword">pass</span>

<span class="hljs-meta">    @property</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">last_block</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-comment"># returns the last block in the chain</span>
        <span class="hljs-keyword">return</span> self.chain[<span class="hljs-number">-1</span>]
</code></pre>
<p>Now, let me explain what is taking place…</p>
<h2 id="heading-1-building-the-first-block-class">1. Building the first Block class</h2>
<p>A blockchain comprises of several blocks that are joined to each other (that sounds familiar, right?).</p>
<p>The chaining of blocks takes place such that if one block is tampered with, the rest of the chain becomes invalid.</p>
<p>In applying the above concept, I created the following initial block class:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> hashlib
<span class="hljs-keyword">import</span> time

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Block</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, index, proof_no, prev_hash, data, timestamp=None</span>):</span>
        self.index = index
        self.proof_no = proof_no
        self.prev_hash = prev_hash
        self.data = data
        self.timestamp = timestamp <span class="hljs-keyword">or</span> time.time()

<span class="hljs-meta">    @property</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculate_hash</span>(<span class="hljs-params">self</span>):</span>
        block_of_string = <span class="hljs-string">"{}{}{}{}{}"</span>.format(self.index, self.proof_no,
                                              self.prev_hash, self.data,
                                              self.timestamp)

        <span class="hljs-keyword">return</span> hashlib.sha256(block_of_string.encode()).hexdigest()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__repr__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"{} - {} - {} - {} - {}"</span>.format(self.index, self.proof_no,
                                               self.prev_hash, self.data,
                                               self.timestamp)
</code></pre>
<p>As you can see from the code above, I defined the <strong><strong>init</strong>()</strong> function, which will be executed when the <strong>Block</strong> class is being initiated, just like in any other Python class.</p>
<p>I provided the following parameters to the initiation function:</p>
<ul>
<li><strong>self</strong>—this refers to the instance of the <strong>Block</strong> class, making it possible to access the methods and attributes associated with the class;</li>
<li><strong>index</strong>—this keeps track of the position of the block within the blockchain;</li>
<li><strong>proof_no</strong>—this is the number produced during the creation of a new block (called mining);</li>
<li><strong>prev_hash</strong>—this refers to the hash of the previous block within the chain;</li>
<li><strong>data</strong>—this gives a record of all transactions completed, such as the quantity bought;</li>
<li><strong>timestamp</strong>—this places a timestamp for the transactions.</li>
</ul>
<p>The second method in the class, <strong>calculate_hash</strong>, will generate the hash of the blocks using the above values. The SHA-256 module is imported into the project to assist in obtaining the hashes of the blocks.  </p>
<p>After the values have been inputted into the cryptographic hash algorithm, the function will return a 256-bit string representing the contents of the block.  </p>
<p>This is how security is achieved in blockchains—every block will have a hash and that hash will rely on the hash of the previous block. </p>
<p>As such, if someone tries to compromise any block in the chain, the other blocks will have invalid hashes, leading to disruption of the entire blockchain network.  </p>
<p>Ultimately, a block will look like this:</p>
<pre><code class="lang-python">{
    <span class="hljs-string">"index"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-string">"proof"</span>: <span class="hljs-number">21</span>,
    <span class="hljs-string">"prev_hash"</span>: <span class="hljs-string">"6e27587e8a27d6fe376d4fd9b4edc96c8890346579e5cbf558252b24a8257823"</span>,
    <span class="hljs-string">"transactions"</span>: [
        {<span class="hljs-string">'sender'</span>: <span class="hljs-string">'0'</span>, <span class="hljs-string">'recipient'</span>: <span class="hljs-string">'Quincy Larson'</span>, <span class="hljs-string">'quantity'</span>: <span class="hljs-number">1</span>}
    ],
    <span class="hljs-string">"timestamp"</span>: <span class="hljs-number">1521646442.4096143</span>
}
</code></pre>
<h2 id="heading-2-building-the-blockchain-class">2. Building the Blockchain class</h2>
<p>The main idea of a blockchain, just as the name implies, involves “chaining” several blocks to one another. </p>
<p>Therefore, I’m going to construct a <strong>Blockchain</strong> class that will be useful in managing the workings of the whole chain. This is where most of the action is going to take place.</p>
<p>The <strong>Blockchain</strong> class will have various helper methods for completing various tasks in the blockchain.</p>
<p>Let me explain the role of each of the methods in the class.</p>
<h3 id="heading-a-constructor-method">a. Constructor method</h3>
<p>This method ensures the blockchain is instantiated.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BlockChain</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.construct_genesis()
</code></pre>
<p>Here are the roles of its attributes:  </p>
<ul>
<li><strong>self.chain</strong>—this variable keeps all blocks;</li>
<li><strong>self.current_data</strong>—this variable keeps all the completed transactions in the block;</li>
<li><strong>self.construct_genesis()</strong>—this method will take care of constructing the initial block.</li>
</ul>
<h3 id="heading-b-constructing-the-genesis-block">b. Constructing the genesis block</h3>
<p>The blockchain requires a _<strong>construct_genesis</strong>_ method to build the initial block in the chain. In the blockchain convention, this block is special because it symbolizes the start of the blockchain.  </p>
<p>In this case, let’s construct it by simply passing some default values to the _<strong>construct_block</strong>_ method.</p>
<p>I gave both _<strong>proof_no</strong><em> and </em><strong>prev_hash</strong>_ a value of zero, although you can provide any value you want.  </p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">construct_genesis</span>(<span class="hljs-params">self</span>):</span>
    self.construct_block(proof_no=<span class="hljs-number">0</span>, prev_hash=<span class="hljs-number">0</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">construct_block</span>(<span class="hljs-params">self, proof_no, prev_hash</span>):</span>
    block = Block(
        index=len(self.chain),
        proof_no=proof_no,
        prev_hash=prev_hash,
        data=self.current_data)
    self.current_data = []

    self.chain.append(block)
    <span class="hljs-keyword">return</span> block
</code></pre>
<h3 id="heading-ia"> </h3>
<p>c. Constructing new blocks</p>
<p>The <strong>_construct<em>block</em></strong> method is used for creating new blocks in the blockchain.</p>
<p>Here is what is taking place with the various attributes of this method:  </p>
<ul>
<li><strong>index</strong>—this represents the length of the blockchain;</li>
<li><strong>proof_nor &amp; prev_hash</strong>—the caller method passes them;</li>
<li><strong>data</strong>—this contains a record of all the transactions that are not included in any block on the node;</li>
<li><strong>self.current_data</strong>—this is used to reset the transaction list on the node. If a block has been constructed and the transactions allocated to it, the list is reset to ensure that future transactions are added into this list. And, this process will take place continuously;</li>
<li><strong>self.chain.append()—</strong>this method joins newly constructed blocks to the chain;</li>
<li><strong>return</strong>—lastly, a constructed block object is returned.  </li>
</ul>
<h3 id="heading-d-checking-validity">d. Checking validity</h3>
<p>The _<strong>check_validity</strong>_ method is important in assessing the integrity of the blockchain and ensuring anomalies are absent.  </p>
<p>As mentioned earlier, hashes are essential for the security of the blockchain as even the slightest change in the object will lead to the generation of a completely new hash.  </p>
<p>Therefore, this <strong>_check<em>validity</em></strong> method uses <em><strong>if</strong></em> statements to check whether the hash of every block is correct.  </p>
<p>It also verifies if every block points to the right previous block, through comparing the value of their hashes. If everything is correct, it returns true; otherwise, it returns false.  </p>
<pre><code class="lang-python"><span class="hljs-meta">@staticmethod</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_validity</span>(<span class="hljs-params">block, prev_block</span>):</span>
    <span class="hljs-keyword">if</span> prev_block.index + <span class="hljs-number">1</span> != block.index:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

    <span class="hljs-keyword">elif</span> prev_block.calculate_hash != block.prev_hash:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

    <span class="hljs-keyword">elif</span> <span class="hljs-keyword">not</span> BlockChain.verifying_proof(block.proof_no, prev_block.proof_no):
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

    <span class="hljs-keyword">elif</span> block.timestamp &lt;= prev_block.timestamp:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
</code></pre>
<h3 id="heading-e-adding-data-of-transactions">e. Adding data of transactions</h3>
<p>The _<strong>new_data</strong><em> method is used for adding the data of transactions to a block. It’s a very simple method: it accepts three parameters (sender’s details, receiver’s details, and quantity) and append the transaction data to </em><strong>self.current_data</strong>_ list.  </p>
<p>Anytime a new block is created, this list is allocated to that block and reset once more as explained in the _<strong>construct_block</strong>_ method.  </p>
<p>Once the transaction data has been added to the list, the index of the next block to be created is returned.  </p>
<p>This index is calculated by adding 1 to the index of the current block (which is the last in the blockchain). The data will assist a user in submitting the transaction in future.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">new_data</span>(<span class="hljs-params">self, sender, recipient, quantity</span>):</span>
    self.current_data.append({
        <span class="hljs-string">'sender'</span>: sender,
        <span class="hljs-string">'recipient'</span>: recipient,
        <span class="hljs-string">'quantity'</span>: quantity
    })
    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
</code></pre>
<h3 id="heading-ia-1"> </h3>
<p>f. Adding proof of work</p>
<p><a target="_blank" href="https://en.bitcoin.it/wiki/Proof_of_work">Proof of work</a> is a concept that prevents the blockchain from abuse. Simply, its objective is to identify a number that solves a problem after a certain amount of computing work is done.</p>
<p>If the difficulty level of identifying the number is high, it discourages spamming and tampering with the blockchain.</p>
<p>In this case, we’ll use a simple algorithm that discourages people from mining blocks or creating blocks easily.</p>
<pre><code class="lang-python"><span class="hljs-meta">@staticmethod</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">proof_of_work</span>(<span class="hljs-params">last_proof</span>):</span>
    <span class="hljs-string">'''this simple algorithm identifies a number f' such that hash(ff') contain 4 leading zeroes
         f is the previous f'
         f' is the new proof
        '''</span>
    proof_no = <span class="hljs-number">0</span>
    <span class="hljs-keyword">while</span> BlockChain.verifying_proof(proof_no, last_proof) <span class="hljs-keyword">is</span> <span class="hljs-literal">False</span>:
        proof_no += <span class="hljs-number">1</span>

    <span class="hljs-keyword">return</span> proof_no


<span class="hljs-meta">@staticmethod</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">verifying_proof</span>(<span class="hljs-params">last_proof, proof</span>):</span>
    <span class="hljs-comment">#verifying the proof: does hash(last_proof, proof) contain 4 leading zeroes?</span>

    guess = <span class="hljs-string">f'<span class="hljs-subst">{last_proof}</span><span class="hljs-subst">{proof}</span>'</span>.encode()
    guess_hash = hashlib.sha256(guess).hexdigest()
    <span class="hljs-keyword">return</span> guess_hash[:<span class="hljs-number">4</span>] == <span class="hljs-string">"0000"</span>
</code></pre>
<h3 id="heading-g-getting-the-last-block">g. Getting the last block</h3>
<p>Lastly, the <strong>_latest<em>block</em></strong> method is a helper method that assists in obtaining the last block in the blockchain. Remember that the last block is actually the current block in the chain.</p>
<pre><code class="lang-python"><span class="hljs-meta">@property</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">latest_block</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.chain[<span class="hljs-number">-1</span>]
</code></pre>
<h2 id="heading-lets-sum-everything-together">Let’s sum everything together</h2>
<p>Here is the entire code for creating the <strong>fccCoin</strong> cryptocurrency.</p>
<p>You can also get the code on <a target="_blank" href="https://github.com/Alfrick/Create-Cryptocurrency-in-Python">this GitHub repository.</a></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> hashlib
<span class="hljs-keyword">import</span> time


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Block</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, index, proof_no, prev_hash, data, timestamp=None</span>):</span>
        self.index = index
        self.proof_no = proof_no
        self.prev_hash = prev_hash
        self.data = data
        self.timestamp = timestamp <span class="hljs-keyword">or</span> time.time()

<span class="hljs-meta">    @property</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculate_hash</span>(<span class="hljs-params">self</span>):</span>
        block_of_string = <span class="hljs-string">"{}{}{}{}{}"</span>.format(self.index, self.proof_no,
                                              self.prev_hash, self.data,
                                              self.timestamp)

        <span class="hljs-keyword">return</span> hashlib.sha256(block_of_string.encode()).hexdigest()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__repr__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"{} - {} - {} - {} - {}"</span>.format(self.index, self.proof_no,
                                               self.prev_hash, self.data,
                                               self.timestamp)


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BlockChain</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.construct_genesis()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">construct_genesis</span>(<span class="hljs-params">self</span>):</span>
        self.construct_block(proof_no=<span class="hljs-number">0</span>, prev_hash=<span class="hljs-number">0</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">construct_block</span>(<span class="hljs-params">self, proof_no, prev_hash</span>):</span>
        block = Block(
            index=len(self.chain),
            proof_no=proof_no,
            prev_hash=prev_hash,
            data=self.current_data)
        self.current_data = []

        self.chain.append(block)
        <span class="hljs-keyword">return</span> block

<span class="hljs-meta">    @staticmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_validity</span>(<span class="hljs-params">block, prev_block</span>):</span>
        <span class="hljs-keyword">if</span> prev_block.index + <span class="hljs-number">1</span> != block.index:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

        <span class="hljs-keyword">elif</span> prev_block.calculate_hash != block.prev_hash:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

        <span class="hljs-keyword">elif</span> <span class="hljs-keyword">not</span> BlockChain.verifying_proof(block.proof_no,
                                            prev_block.proof_no):
            <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

        <span class="hljs-keyword">elif</span> block.timestamp &lt;= prev_block.timestamp:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">new_data</span>(<span class="hljs-params">self, sender, recipient, quantity</span>):</span>
        self.current_data.append({
            <span class="hljs-string">'sender'</span>: sender,
            <span class="hljs-string">'recipient'</span>: recipient,
            <span class="hljs-string">'quantity'</span>: quantity
        })
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>

<span class="hljs-meta">    @staticmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">proof_of_work</span>(<span class="hljs-params">last_proof</span>):</span>
        <span class="hljs-string">'''this simple algorithm identifies a number f' such that hash(ff') contain 4 leading zeroes
         f is the previous f'
         f' is the new proof
        '''</span>
        proof_no = <span class="hljs-number">0</span>
        <span class="hljs-keyword">while</span> BlockChain.verifying_proof(proof_no, last_proof) <span class="hljs-keyword">is</span> <span class="hljs-literal">False</span>:
            proof_no += <span class="hljs-number">1</span>

        <span class="hljs-keyword">return</span> proof_no

<span class="hljs-meta">    @staticmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">verifying_proof</span>(<span class="hljs-params">last_proof, proof</span>):</span>
        <span class="hljs-comment">#verifying the proof: does hash(last_proof, proof) contain 4 leading zeroes?</span>

        guess = <span class="hljs-string">f'<span class="hljs-subst">{last_proof}</span><span class="hljs-subst">{proof}</span>'</span>.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        <span class="hljs-keyword">return</span> guess_hash[:<span class="hljs-number">4</span>] == <span class="hljs-string">"0000"</span>

<span class="hljs-meta">    @property</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">latest_block</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.chain[<span class="hljs-number">-1</span>]

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">block_mining</span>(<span class="hljs-params">self, details_miner</span>):</span>

        self.new_data(
            sender=<span class="hljs-string">"0"</span>,  <span class="hljs-comment">#it implies that this node has created a new block</span>
            receiver=details_miner,
            quantity=
            <span class="hljs-number">1</span>,  <span class="hljs-comment">#creating a new block (or identifying the proof number) is awarded with 1</span>
        )

        last_block = self.latest_block

        last_proof_no = last_block.proof_no
        proof_no = self.proof_of_work(last_proof_no)

        last_hash = last_block.calculate_hash
        block = self.construct_block(proof_no, last_hash)

        <span class="hljs-keyword">return</span> vars(block)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_node</span>(<span class="hljs-params">self, address</span>):</span>
        self.nodes.add(address)
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>

<span class="hljs-meta">    @staticmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">obtain_block_object</span>(<span class="hljs-params">block_data</span>):</span>
        <span class="hljs-comment">#obtains block object from the block data</span>

        <span class="hljs-keyword">return</span> Block(
            block_data[<span class="hljs-string">'index'</span>],
            block_data[<span class="hljs-string">'proof_no'</span>],
            block_data[<span class="hljs-string">'prev_hash'</span>],
            block_data[<span class="hljs-string">'data'</span>],
            timestamp=block_data[<span class="hljs-string">'timestamp'</span>])
</code></pre>
<p>Now, let’s test our code to see if it works.</p>
<pre><code class="lang-python">blockchain = BlockChain()

print(<span class="hljs-string">"***Mining fccCoin about to start***"</span>)
print(blockchain.chain)

last_block = blockchain.latest_block
last_proof_no = last_block.proof_no
proof_no = blockchain.proof_of_work(last_proof_no)

blockchain.new_data(
    sender=<span class="hljs-string">"0"</span>,  <span class="hljs-comment">#it implies that this node has created a new block</span>
    recipient=<span class="hljs-string">"Quincy Larson"</span>,  <span class="hljs-comment">#let's send Quincy some coins!</span>
    quantity=
    <span class="hljs-number">1</span>,  <span class="hljs-comment">#creating a new block (or identifying the proof number) is awarded with 1</span>
)

last_hash = last_block.calculate_hash
block = blockchain.construct_block(proof_no, last_hash)

print(<span class="hljs-string">"***Mining fccCoin has been successful***"</span>)
print(blockchain.chain)
</code></pre>
<p>It worked!</p>
<p>Here is the output of the mining process:</p>
<pre><code class="lang-python">***Mining fccCoin about to start***
[<span class="hljs-number">0</span> - <span class="hljs-number">0</span> - <span class="hljs-number">0</span> - [] - <span class="hljs-number">1566930640.2707076</span>]
***Mining fccCoin has been successful***
[<span class="hljs-number">0</span> - <span class="hljs-number">0</span> - <span class="hljs-number">0</span> - [] - <span class="hljs-number">1566930640.2707076</span>, <span class="hljs-number">1</span> - <span class="hljs-number">88914</span> - a8d45cb77cddeac750a9439d629f394da442672e56edfe05827b5e41f4ba0138 - [{<span class="hljs-string">'sender'</span>: <span class="hljs-string">'0'</span>, <span class="hljs-string">'recipient'</span>: <span class="hljs-string">'Quincy Larson'</span>, <span class="hljs-string">'quantity'</span>: <span class="hljs-number">1</span>}] - <span class="hljs-number">1566930640.5363243</span>]
</code></pre>
<h2 id="heading-ia-2"> </h2>
<p>Conclusion</p>
<p>There you have it!</p>
<p>That’s how you could create your own blockchain using Python.</p>
<p>Let me say that this tutorial just demonstrates the basic concepts for getting your feet wet in the innovative blockchain technology.</p>
<p>If <strong>this coin</strong> were deployed as-is, it could not meet the present market demands for a stable, secure, and easy-to-use cryptocurrency.</p>
<p>Therefore, it can still be improved by adding additional features to enhance its capabilities for mining and sending <a target="_blank" href="https://www.forextradingbig.com/">financial transactions</a>.</p>
<p>Nonetheless, it’s a good starting point if you decide to make your name known in the amazing world of cryptos.</p>
<p>If you have any comments or questions, please post them below.</p>
<p>Happy (crypto) coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Universal Ethereum Delegated Transactions: No More Transaction Fees ]]>
                </title>
                <description>
                    <![CDATA[ TL;DR Check this back end and front end solutions for delegated transactions. It is universal for any token which supports the delegation of its functions. Read more below. This mostly technical article provides a universal framework and a working s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/universal-ethereum-delegated-transactions-no-more-ethereum-fees/</link>
                <guid isPermaLink="false">66b99b7c3cd81de09c96b2bc</guid>
                
                    <category>
                        <![CDATA[ Blockchain ]]>
                    </category>
                
                    <category>
                        <![CDATA[ crypto ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ethereum ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ethereum blockchain ]]>
                    </category>
                
                    <category>
                        <![CDATA[ token economy ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tokenization ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nikita Savchenko ]]>
                </dc:creator>
                <pubDate>Mon, 30 Sep 2019 15:53:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/09/you-need-some-ether-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <blockquote>
<p>TL;DR Check this <a target="_blank" href="https://github.com/ZitRos/ethereum-delegated-tx-service">back end</a> and <a target="_blank" href="https://zitros.github.io/ethereum-delegated-tx-widget/">front end</a> solutions for delegated transactions. It is universal for any token which supports the delegation of its functions. Read more below.</p>
</blockquote>
<p>This mostly technical article provides a <strong>universal framework</strong> and a <strong>working solution</strong> for Ethereum tokens and applications that eliminates the need to pay fees in Ether, a problem that is practically killing the user experience of many blockchain applications.</p>
<blockquote>
<p><em>Imagine spending dollars and then being asked to also hand over some</em> <a target="_blank" href="https://en.wikipedia.org/wiki/Ukrainian_hryvnia"><em>Hryvnias</em></a> <em>as a transaction fee. That's how Ethereum tokens work so far.</em></p>
</blockquote>
<p>In other words, for example, to transfer any Ethereum token (like <a target="_blank" href="https://coinmarketcap.com/currencies/tether/">Tether</a>, <a target="_blank" href="https://coinmarketcap.com/currencies/dai/">DAI</a>, <a target="_blank" href="https://coinmarketcap.com/currencies/basic-attention-token/">BAT</a>, <a target="_blank" href="https://token.dreamteam.gg/">DREAM</a>, etc.), the user has to also spend some <a target="_blank" href="http://ethereum.org/use/#_2-what-is-eth-and-how-do-i-get-it">Ether</a> (internal Ethereum platform currency). This introduces a big inconvenience that prevents the mass adoption of DApps: users have to purchase multiple currencies instead of just one to interact with the blockchain network.</p>
<h1 id="heading-the-problem">The Problem</h1>
<p>Tokens, as we imagine them today are just fuel for applications and services on top of blockchain networks. Organizations create their own tokens (using ICOs, IEOs, etc) and run services/applications that utilize them, introducing their own micro-economy (widely known as a <a target="_blank" href="https://medium.com/@pentremont/token-economy-101-or-why-blockchain-powered-decentralized-networks-are-important-310de1cc8bac">token economy</a>). But almost every token turns out to be quite a complex currency itself. By design of how blockchain networks work, in order to do something with your tokens, you also need another currency — often Ether (for Ethereum) to be able to transfer tokens.</p>
<p>To illustrate the problem, let's look into how users come to use different blockchain-powered services and applications like:</p>
<ul>
<li><a target="_blank" href="https://trickle.gg/">Trickle</a> - where you create secure, hourly-based contracts with an untrusted party in any token</li>
<li><a target="_blank" href="https://loomx.io/">Loom</a> - where you use Loom tokens to create sidechains in Loom Network</li>
<li><a target="_blank" href="https://www.cryptokitties.co/">Cryptokitties.co</a> - where you breed, trade and transfer kitties (ERC721 tokens)</li>
<li><a target="_blank" href="https://www.stateofthedapps.com/">Others</a> (there are a lot!)</li>
</ul>
<p>All these applications use tokens, as well as they require you to purchase Ether. The complexity of using crypto tokens as we know them today is one of the biggest reasons why 99% of crypto startups fail (or avoid adopting real crypto, for example, by replacing it with virtual coins).</p>
<p>As you may already know, the harder it is to use the application, the fewer users it will get right from the beginning. This is something known as <a target="_blank" href="https://www.appcues.com/blog/user-onboarding-funnel-amplitude">The User Onboarding Funnel</a>, which is still a big pain for blockchain-powered applications and services:</p>
<p><img src="https://lh3.googleusercontent.com/XJyaZoGARI3TF4DOjODJerEUNwn3qFm2D8WSZBrxwYE81oSHaw5h3MOweymV5VV9Jby-2OBUE7o1FGkVqZxWvONW0GLuoezAKqt8HmB-N-vPwHL_ouohPO2whDyS1jiXHLIQv9am" alt="Image" width="1275" height="359" loading="lazy">
<em>The typical user onboarding funnel of a decentralized, blockchain-based application</em></p>
<p>To understand why I put 0.001% of users prior to the service use, let's see what exactly purchasing some Ether means:</p>
<ul>
<li>Creating a crypto wallet</li>
<li>Registering on Exchange (and learning all the exchange rules, including country policies!)</li>
<li>Passing KYC (though it's getting easier, still, many countries have limited access to exchanges)</li>
<li>Purchasing a minimum allowed amount of Ether (usually, it's <a target="_blank" href="https://changelly.com/widget-settings">whopping $50</a> while you need just nearly $0.05 to perform one or two transactions)</li>
<li>Withdrawing Ether to your wallet</li>
<li>Not to mention reading lengthy guides on how to perform all these steps properly</li>
</ul>
<p>Instead of just:</p>
<ul>
<li>Creating a crypto wallet</li>
</ul>
<p>Of course, it highly depends on how the application or service is made. But, so far, there was no better simplification of the onboarding flow as just cutting crypto tokens from there, or making them fake, "virtual" currency with deposit and withdrawal function. Unfortunately, the latter approach is now the common one across all startups and companies adopting crypto, for many good reasons. Another reason could be a monetization strategy, but this is another big story worth a dedicated article (Interested? Comment out!).</p>
<p>Getting back to the transaction fees problem, we can state the following, which is hard to argue with.</p>
<blockquote>
<p><em>It is natural for the user to purchase <strong>only</strong> the cryptocurrency they really need (for instance, tokens:</em> <a target="_blank" href="https://coinmarketcap.com/currencies/tether/"><em>Tether</em></a><em>,</em> <a target="_blank" href="https://coinmarketcap.com/currencies/dai/"><em>DAI</em></a><em>,</em> <a target="_blank" href="https://coinmarketcap.com/currencies/basic-attention-token/"><em>BAT</em></a><em>,</em> <a target="_blank" href="https://token.dreamteam.gg/"><em>DREAM</em></a><em>, etc.), and they would normally expect to pay any transaction fees <strong>in this cryptocurrency</strong>.</em></p>
</blockquote>
<p>So why not just allow them to do so? Because it's quite complex indeed. Let's see why, and how this has just got easier with our open-sourced solution (at least for Ethereum).</p>
<h1 id="heading-existing-approaches">Existing Approaches</h1>
<p>From the very beginning of blockchain existence, there were a couple of solutions that could simplify the user onboarding flow to the flow depicted below, avoiding the step of purchasing an intermediate currency like Ether. Still, creating a blockchain wallet is not an easy step, but some users who do understand the value of the application/service go through this step quite well.</p>
<p><img src="https://lh3.googleusercontent.com/B_D585TaVcYR9qXA-0q3MfvAv1DjGzAulIup0XT1X8Va3eeekX32jAtayKbFCmKoISotoBk_WOyq9jGAdqJzfAnz5q61foOPjgxeVbcfq8bXlA9X25iqzKczy6qmjPvZJgBYsRrL" alt="Image" width="1275" height="359" loading="lazy">
<em>The user onboarding funnel with delegated transactions</em></p>
<p>The solution which allows to avoid using intermediate currencies (Ether for Ethereum) is called "delegated transactions", or "meta transactions". </p>
<blockquote>
<p><em>In short, delegated transaction, or "meta transaction" in blockchain is the type of transaction which performs an intended action on one account's behalf, while it is conducted (published) by another account (delegate), who actually pays fees for the transaction.</em></p>
</blockquote>
<p>There are <a target="_blank" href="https://medium.com/@austin_48503/ethereum-meta-transactions-90ccf0859e84">multiple</a> <a target="_blank" href="https://fravoll.github.io/solidity-patterns/proxy_delegate.html">approaches</a> <a target="_blank" href="https://medium.com/@e2toe4/ethereum-meta-transactions-36f10448619">around</a> <a target="_blank" href="https://github.com/ethereum/EIPs/issues/1035">the</a> <a target="_blank" href="https://github.com/ethereum/EIPs/issues/1228">internet</a> of the generalized concept of delegated transactions I am presenting in this article. But it seems that none of them are still widely adopted, as these approaches are quite complex by its nature, very specific as for the implementation, as well as some of them are <strong>quite complex to standardize</strong>. To be more constructive, existing approaches can be divided into 3-4 groups: those which use proxy smart contracts, those which embed delegation into a smart contract itself and, theoretically, there is an opportunity for the blockchain-native implementation (say, Ethereum 2.0).</p>
<h2 id="heading-1-delegated-transactions-approaches-which-use-proxy-contracts">1. Delegated transactions approaches which use proxy-contracts</h2>
<p>Proxy contracts, or, in this context, identity contracts are tiny contracts deployed to replace the user account which wants to avoid paying fees. This smart contract is programmed to act as a wallet, as well as a "caller" (sender) of other smart contract's functions. The key is that it is a delegate account that triggers all the actions, while the true "owner" of this smart contract is another user. The user just generates correct signatures in order to control their funds stored on a smart contract address (= in their wallet).</p>
<p><img src="https://lh3.googleusercontent.com/BqoXbK-n6UmpKY-nu8_GuibFbfA3a2Lrghc_fHSoJOzMqv_MYL2BNzIUzyZPgT1aSM00WC0fJoyErLQKc0Dtu3D92NRdYB3Cm4bJ8vZAnbfHVaSe4pCxrEsI8rvEiNCbQriStqfx" alt="Image" width="1025" height="471" loading="lazy">
<em>A visualization of how identity contracts look like</em></p>
<p><strong>Pros of this approach:</strong></p>
<ul>
<li>It works with any tokens and contracts which are already deployed to the network</li>
</ul>
<p><strong>Cons of this approach:</strong></p>
<ul>
<li>Users don't see tokens in their wallet, because they are physically on an identity smart contract</li>
<li>As a result, a need to develop custom UIs and custom tools/wallets</li>
<li>Identity smart contract deployment and assignment initial fees, as opposed to no fees at all</li>
<li>Requires a comprehensive standard to be widely adopted</li>
</ul>
<h2 id="heading-2-semi-delegated-transactions-via-operator-pattern-erc777httpseipsethereumorgeipseip-777">2. Semi-delegated transactions via "Operator" pattern (<a target="_blank" href="https://eips.ethereum.org/EIPS/eip-777">ERC777</a>)</h2>
<p>There is a token standard that describes this approach — <a target="_blank" href="https://eips.ethereum.org/EIPS/eip-777">ERC777</a>. In short, any token holder can authorize any other account to freely manage their tokens. I won't call it delegated transactions but nevertheless, I need to mention that, as here we somewhat delegate control over your tokens to other accounts.</p>
<p><img src="https://lh6.googleusercontent.com/Sf3WEbL4fRfefAZLZIBzxD8nAhLnFt75uIZUSO0SjifRwqbiIwSOUnWf4QkN6v6kmWXBazs05bGnG6w1AOTNZIEXwuVUf6GIPdBNtD60mAwiU5r7Oe4MMlNEGLy5htCrk51zsfwi" alt="Image" width="1025" height="471" loading="lazy">
<em>A visualization of ERC777 standard's "operator" pattern</em></p>
<p><strong>Pros of this approach:</strong></p>
<ul>
<li>Standardized</li>
</ul>
<p><strong>Cons of this approach:</strong></p>
<ul>
<li>Highly centralized around the "operator" accounts</li>
<li>Weak security due to operators have 100% control over your tokens</li>
<li>Initial fees for approval transaction</li>
<li>Requires additional UIs/tools development</li>
</ul>
<h2 id="heading-3-delegated-transactions-embedded-directly-into-a-token-smart-contract">3. Delegated transactions embedded directly into a (token) smart contract</h2>
<p>Just the same as it is possible to implement custom fees in a proxy smart contract, paying fees in tokens can be implemented directly in a token smart contract. For example, using the approach I described in <a target="_blank" href="https://hackernoon.com/you-dont-need-ether-to-transfer-tokens-f3ae373606e1">my previous article</a>, it is possible to implement a function in a smart contract, which will transfer tokens accepting the user's signature, instead of requiring the user to call this function directly. We have implemented this approach in our <a target="_blank" href="https://token.dreamteam.gg/">DREAM Token</a>, which is used on our <a target="_blank" href="https://dreamteam.gg/">dreamteam.gg</a> platform.</p>
<p><img src="https://lh3.googleusercontent.com/NTd44yatekkdfGEOfSDdsXi1S8cmtRdkQLXmUKSIm-nFzMMQdOM1Rox1nML6Y2Z8gYh9t_sMIsPvr7L7AHxTPlYXp0ENnVWQBLf5g85Cue-CiR2zb1Xw4Ym4G407MQOhCUUnSrrQ" alt="Image" width="1025" height="471" loading="lazy">
<em>A visualization of how embedding delegation into the token contract looks like</em></p>
<p>As you may notice, in contrast to the previous approach there is no identity contract anymore, and there is an optional way to call other smart contracts directly from the token contract.</p>
<p><strong>Pros of this approach:</strong></p>
<ul>
<li>Users see their tokens as usual on their wallet's balance</li>
<li>No initial fees for account initialization</li>
<li>May not even require a standard (continue reading)</li>
</ul>
<p><strong>Cons of this approach:</strong></p>
<ul>
<li>If you have a (token) smart contract that is already deployed to the network, you cannot apply this approach to it directly. While you can always deploy a new token and, for example, a "migration" utility, which will allow other users to swap tokens (burn the old token and mint a new one)</li>
<li>Because a standard for this approach is yet not well-defined, implementation can drastically vary</li>
<li>A need to develop custom UI/tools for delegated transactions (continue reading — solved!)</li>
</ul>
<h2 id="heading-4-delegated-transactions-on-the-blockchain-platform-level">4. Delegated transactions on the (blockchain) platform level</h2>
<p>This is far the best one of all the described approaches above but also the one <strong>which is not implemented anywhere yet</strong> (by anywhere I mean the most popular blockchain platforms). There is a hope that its support comes with Ethereum 2.0 release, or at least I've heard from Vitalik that they are in progress with something cool there.</p>
<p>Theoretically, we can imagine this approach as being able to make an "offline" signature of two transactions at a time: one which does something useful for the signing account which wants to avoid paying fees (for example, transferring tokens) and another one which does something useful for the delegate (for example, paying fee in tokens to the account which executes these two transactions).</p>
<p><img src="https://lh5.googleusercontent.com/R1S5_YVazRlh2mfzuMLaKAnix8GmXJy4swBQyxzWFzhIZhE5nDTZ4gfOLp9G51dx-ydW7sLQCsWkic6k_nVj_1CD8JkHjGjRYSMwt17wGSLAG58Vs2ve02KS3L5m5L2oTCMWfxlG" alt="Image" width="1142" height="505" loading="lazy">
<em>A visualization of how platform-native delegated transactions could look like</em></p>
<p>But the problem is, regarding Ethereum 2.0, this feature has a chance to land only in 2022 or even later. I also suppose that this feature will still require a dedicated back end (similar to the one which is introduced within this article), as it is hard to imagine how miners will accept fees in tokens. Simply put, if some of them refuse to accept fees in tokens than it makes little sense to do it on a "mining" level at all, not to mention how much would it take to track all token prices and volumes across exchanges, in a decentralized manner.</p>
<p><strong>Pros of this approach:</strong></p>
<ul>
<li>No need to change smart contracts that were already deployed</li>
<li>No initial fees for account initialization</li>
<li>May not even require a custom UI/tools if standardized</li>
</ul>
<p><strong>Cons of this approach:</strong></p>
<ul>
<li>Most likely, will still require a centralized back end (the "delegate")</li>
<li>Not yet implemented on a platform level (as of 2019)</li>
</ul>
<h1 id="heading-the-solution">The Solution</h1>
<p>From the four approaches above, except for the platform-level approach which is yet to be implemented and standardized in 2022+, the most appealing one is <strong>the third approach</strong>, where we embed delegated functions directly to the token smart contract. Thus, we save the standard token paradigm allowing wallets to normally work with the smart contract and have no need to wait until delegated transactions will land natively in one of the top blockchain platforms. We will stick to this approach and make it <strong>universal</strong> just below.</p>
<p>Delegated transactions support programmed right in the token smart contract is awesome. But how to deal with its cons? In fact, the only problem which is tough to deal with (as you cannot modify existing smart contracts), <strong>you will need to deploy a new token smart contract if you have already deployed it without delegated functions</strong> (for instance, standard ERC20 or ERC721 tokens). The next step, in this case, would be adding a way to migrate tokens from one smart contract to another. For example, you can decide to implement one more function in the new smart contract that will allow token holders to migrate their assets from the old smart contract.</p>
<p>Token migration function implementation can vary, starting from implementing <em>receiveApproval</em> in the new token, if the previous token supports <em>approveAndCall</em>, or ending with utilizing <em>approve</em> + <em>transferFrom</em> framework if you have just a bare minimal ERC20 (the user _approve_s tokens to the new token contract address and then calls a function in the new contract which burns old tokens and mints new ones — but this requires a standard fee for the user for the approval transaction). Actually, there is more: you can decide not to burn old tokens but to "lock" them on a new token smart contract, minting new tokens — this opens an opportunity to implement <strong>two-sided token migration</strong>, which is awesome — <strong>you won't need to list the "new" token on the exchange</strong>, while the users will still be able to send the old token to exchanges without fees in Ether! If you are interested, please fill the issue <a target="_blank" href="https://github.com/ZitRos/ethereum-delegated-tx-service/issues">here</a> if you want to know more details on how to do it, because this approach is worth a whole new article.</p>
<p>In my <a target="_blank" href="https://hackernoon.com/you-dont-need-ether-to-transfer-tokens-f3ae373606e1">previous article</a>, I provided an example of the token smart contract which supports delegation of such functions like <em>transfer</em>, <em>transferFrom</em>, <em>approve</em> and <em>approveAndCall</em>. Exactly these "delegated" functions allow users to pay fees in tokens, instead of Ether.</p>
<p><img src="https://lh6.googleusercontent.com/K95psDr4YlNLWPFIByI6HmE5DOz-uIGmD9xfNODmhfj6oRfkIlGJwkZLPYBEVof4MwitQe5Li6SbUNptplVKL2MfERLbVHLJru5jJkTpCVDnDaQbpMd24wtbWOTp81hX7CHtiRtR" alt="Image" width="1568" height="609" loading="lazy">
<em>How delegation works in Ethereum, in short. Read more in <a target="_blank" href="https://hackernoon.com/you-dont-need-ether-to-transfer-tokens-f3ae373606e1">this article</a>.</em></p>
<p>But that wasn't enough to start the mass adoption. In this article, I am providing a complete <a target="_blank" href="https://github.com/ZitRos/ethereum-delegated-tx-service">universal back end solution</a> (Transaction Publisher in the picture above), as well as a <a target="_blank" href="https://github.com/ZitRos/ethereum-delegated-tx-widget">configurable widget</a> (<a target="_blank" href="https://zitros.github.io/ethereum-delegated-tx-widget/">check it here</a>), which allows you to replace Ether fees for token fees today.</p>
<p>Some key points before we dive in:</p>
<ul>
<li>This delegated transactions back end is made to be universal, or <strong>standard-free</strong>, meaning that you can have <strong>any implementation</strong> of delegated functions and <strong>use any signature standard(s)</strong> in your token. From the back end standpoint, you just need to write a manifest file for your token, describing its usage.</li>
<li>Currently, converting collected fees in tokens back to Ether is a manual action on exchanges. But it could be a potential improvement for automation in the future (if needed).</li>
</ul>
<h1 id="heading-the-concept-behind-the-universal-solution">The Concept Behind the Universal Solution</h1>
<p>What does it mean that the token supports delegated transactions? Let's look at it using the ERC20 standard token as an example.</p>
<h2 id="heading-smart-contract">Smart Contract</h2>
<p>As for the token smart contract, the approach is quite straightforward. In addition to every method like <strong>transfer(to, value)</strong> which we want to be "delegatable", we add a companion function which, instead of inspecting <strong>msg.sender</strong>, accepts the signature of a user and does the same what the original function meant to do by validating this signature inside the smart contract. Thus, for example, for <strong>transfer(to, value)</strong> function we can add <strong>transferViaSignature(to, value, ...aditionalParams)</strong> function. As you know from <a target="_blank" href="https://en.wikipedia.org/wiki/Public-key_cryptography">public-key cryptography</a>, no one can create a valid signature except private key owner, so that's why this approach is as secure as Ethereum itself.</p>
<p>And the coolest part is that the delegated function implementation, as well as its signature doesn't matter much, from the delegate back end standpoint. You can even decide to implement one "call by signature" function for all other functions that the smart contract supports. Delegate back end just need to know <strong>how</strong> to call this function, which is solved by providing an off-chain contract manifest for the delegate back end. For example, the argument <em>additionalParams</em> in <strong>transferViaSignature</strong> can vary and can include anything from this list, if not more: fee, fee recipient address, expiration timestamp, a signature standard used, a signature itself, nonce number or any other unique delegated transaction ID and so on. Regarding the smart contract design, in order to understand why exactly these arguments, read my <a target="_blank" href="https://hackernoon.com/you-dont-need-ether-to-transfer-tokens-f3ae373606e1">previous article</a>.</p>
<p>We also want to allow "delegates" to earn something in order to cover their Ether spending, as well as to be profitable. Thus, we have to add a fee, but a much more natural fee than Ether: a fee in the token itself. So that, for example, if you need to transfer 100 tokens, you pay 3 more tokens to the delegate depending on its price and network conditions to perform a transfer, and this should be preserved in a smart contract logic.</p>
<h2 id="heading-back-end">Back End</h2>
<p>All right, now we have a token that allows transferring someone else's tokens by using their signature. Now, the crucial part is to automate the process of requesting and publishing such transactions. And here where our open-sourced <a target="_blank" href="https://github.com/dreamteam-gg/ethereum-delegated-tx-service">back end</a> (and a <a target="_blank" href="https://github.com/dreamteam-gg/ethereum-delegated-tx-widget">front end</a>) kicks in.</p>
<p>Below is the sequence diagram describing how front end (client) communicates with the back end from the delegated transaction request to its publishing to the network:</p>
<ol>
<li>(hidden on the diagram) The client requests information from the delegated back end to understand which contracts does it support, as well as which functions can it delegate.</li>
<li>The client requests a particular smart contract's function to be delegated. Most importantly, the back end returns the fees it charges and a data to be signed by the client.</li>
<li>The client signs the data in their wallet. Signing is a free operation, unlike publishing transaction to the network.</li>
<li>The client sends their signature back, thus confirming their intent to perform this particular delegated transaction. The back end validates this transaction against the current network.</li>
<li>Finally, the back end publishes a transaction to the network.</li>
<li>(hidden on the diagram) The client constantly polls the back end for the delegated request status until it receives a mined status. Note: it is important to poll the back end instead of using a transaction hash to understand when the transaction is mined. It is a very common case when the gas price suddenly increases, and, in order for the transaction to be mined quickly, the back end may republish it with a higher gas price. Though it is currently not implemented, it is very likely to be implemented soon.</li>
</ol>
<p><img src="https://lh5.googleusercontent.com/X2SADmcB2aMcJoUgN291XXPdk73sVNi4ebruRwN6TCcDgVWi7ILZs02Mlz0WSR4ufOnzXqxrHIdTSJyijeSKsTw1Z89vB0zjwD8dvQ3Jop6Z4xPKET1TWBnNDBad5QDlD8y0jptG" alt="Image" width="1600" height="1190" loading="lazy">
<em>Sequence diagram representing the simplified flow of how delegated transaction is delivered to the network</em></p>
<p>This approach is universal, and only requires the manifest file for the back end to understand how to calculate fees and which signature standard to use on the client side. Here is another visualization of the components of the system and their interaction sequence:</p>
<p><img src="https://lh4.googleusercontent.com/EmfRndRu7BJyU9UTYVGt_rKlQIE83v21s7UywoeTeZQ3Y832Z85KgYRQgmB4o9bqUS7OExMGy2ace6kc3v7QEL-t0bcsvsg9xu9zqLdKDUrzHWXrhHnwoOQWUkd8GBAOWwLww5e8" alt="Image" width="1459" height="934" loading="lazy">
<em>Component diagram</em></p>
<p>We've provided a comprehensive <a target="_blank" href="https://github.com/dreamteam-gg/ethereum-delegated-tx-service#delegated-transactions-concept">documentation</a> for this solution. You can check how the back end <a target="_blank" href="https://github.com/dreamteam-gg/ethereum-delegated-tx-service#api">API is structured</a>, as well as find the token <a target="_blank" href="https://github.com/dreamteam-gg/ethereum-delegated-tx-service/blob/master/config/contracts/mainnet/0x82f4ded9cec9b5750fbff5c2185aee35afc16587/manifest.js">manifest file</a> which describes how to work with a <a target="_blank" href="https://etherscan.io/address/0x82f4ded9cec9b5750fbff5c2185aee35afc16587#code">particular token contract</a>. We encourage you to contribute your own tokens there!</p>
<p>And you don't need much setup: it's already there with the universal front end!</p>
<h2 id="heading-front-end">Front End</h2>
<p><a target="_blank" href="https://github.com/dreamteam-gg/ethereum-delegated-tx-widget">Open-sourced front end part</a> of the delegated transactions is the user interface which is <strong>set up for every token</strong>: just run your delegated transactions back end and you are ready to go!</p>
<p><img src="https://lh4.googleusercontent.com/8TagMGFbuyXbiIEe8_x7cmBycjrAxcpE8zyURXmDIF1cQET-K64NchEmK0lWfNpwR5mzcJIQ5YLp--hLSCksLlMflOAPBbDCf2frPrF4xm6cEZ92GNXH-QDA3MBKpokX4O2tZoUq" alt="Image" width="689" height="908" loading="lazy">
<em>What <a target="_blank" href="https://send-token.dreamteam.gg">it</a> looks like</em></p>
<p>It is made to be an embeddable widget, which will guide the user through the procedure of sending tokens. You can plug any back end, token or call any token function with it by utilizing <a target="_blank" href="https://github.com/dreamteam-gg/ethereum-delegated-tx-widget#embedding">additional URL parameters</a> you can specify.</p>
<p>Using this widget, and by implementing something similar to widely used, but not standardized <em><strong>approveAndCall</strong></em> function in your token smart contract, you will be able to call other smart contracts with arbitrary data by paying fees in tokens!</p>
<p>Here is a quick guide for you if you want to play with this UI yourself:</p>
<ol>
<li>Access the widget via <a target="_blank" href="https://zitros.github.io/ethereum-delegated-tx-widget/?contractAddress=0xcc7e25e30b065ea61814bec6ecdb17edb0f891aa">this link</a>.</li>
<li>It will ask you to switch to the Kovan test network.</li>
<li>Get some test Ether using <a target="_blank" href="https://www.google.com/search?q=ethereum+kovan+faucet">any available Kovan faucet</a>.</li>
<li>Use test Ether to mint some <a target="_blank" href="https://kovan.etherscan.io/address/0xcc7e25e30b065ea61814bec6ecdb17edb0f891aa#writeContract">test tokens</a>: call <a target="_blank" href="https://kovan.etherscan.io/dapp/0xcc7e25e30b065ea61814bec6ecdb17edb0f891aa#writeContract">mintTokens</a> function in a token smart contract which will give you 10 test tokens.</li>
<li>Now, get back to <a target="_blank" href="https://zitros.github.io/ethereum-delegated-tx-widget/?contractAddress=0xcc7e25e30b065ea61814bec6ecdb17edb0f891aa">the widget</a> and try to transfer these tokens!</li>
</ol>
<p>If you open up the browser's developer tools, you may notice that there are a couple of back ends connected by default — they provide the front end with all required information to make a delegated request according to given widget URL parameters. All backends are requested during the widget load and, if any of them can provide a delegation for a particular contract's function, then the widget requests additional information: fees, supported signatures, etc. If there are multiple back ends which can delegate the same contract function, all of them are requested and the back end which provides the best fee will be used for the transaction.</p>
<p>Transaction mining time is seemingly fixed, but it can vary because of the network conditions. The back end uses an actual network fee when calculating the token fee, however, it may change before the user decides to execute the transaction. Thus, the "underpriced" transaction is submitted to the network and can be pending for a while. While the back end is currently not programmed to deal with this case, it might be implemented in future — transactions will be republished with higher gas fees in case of the network fee increases. But, we will also need to count this into the token fee.</p>
<h2 id="heading-signature-standards">Signature Standards</h2>
<p>The last question which you may be wondering is — which signature standard to use for your token. There are several available: _eth<em>sign</em> (deprecated), _eth<em>personalSign</em> (note that old <a target="_blank" href="https://trezor.io/">Trezor</a> and <a target="_blank" href="https://www.ledger.com/">Ledger</a> produce a different signatures because of ambiguity in a standard, so you may want to include both), _eth<em>signTypedData</em> (deprecated), <a target="_blank" href="https://medium.com/metamask/eip712-is-coming-what-to-expect-and-how-to-use-it-bb92fd1a7a26">_eth_signTypedData<em>v3</em></a> and so on. I would recommend supporting at least two: ageless _eth<em>personalSign</em> and new <a target="_blank" href="https://medium.com/metamask/eip712-is-coming-what-to-expect-and-how-to-use-it-bb92fd1a7a26">_eth_signTypedData<em>v3</em></a> (as of 2019).</p>
<p><img src="https://lh3.googleusercontent.com/TZhSpdfJF_035M1uCARZVYixZC4W8hsiG1jbs2zTyYZQC5fpwJUR3W7x14WaLofyklmEaR9O4Cgt7EkKb7MCb1RHK6geJfxKb-oGVVxlOXBOu6dh5c6nRtNwblF5B0sZ07Gf6mV7" alt="Image" width="1408" height="1279" loading="lazy">
<em>Signature standards comparison — what the user sees</em></p>
<p>The front end is programmed to always prefer the user-readable standard like <a target="_blank" href="https://medium.com/metamask/eip712-is-coming-what-to-expect-and-how-to-use-it-bb92fd1a7a26">eth_signTypedData_v3</a> to any others eth_personalSign. So if your token supports many signature standards, and you added all of them to the <a target="_blank" href="https://github.com/dreamteam-gg/ethereum-delegated-tx-service/blob/master/config/contracts/mainnet/0x82f4ded9cec9b5750fbff5c2185aee35afc16587/manifest.js">manifest file</a> of your token, it will display <a target="_blank" href="https://medium.com/metamask/eip712-is-coming-what-to-expect-and-how-to-use-it-bb92fd1a7a26">eth_signTypedData_v3</a> prompt first.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Delegated transactions are great: they solve one of the biggest problems of blockchain application adoption, which eases the mass adoption of crypto overall. I will put a couple of thesis in a Q&amp;A format here for you to answer the last questions that you may still have after reading this article:</p>
<ul>
<li>Our open-source solution is free to use and production-ready, feel free to apply it to your applications or tokens!</li>
<li>The described approach does not compromise security nor centralization. Think this way: the centralized back end is only a helper for someone who wants to transfer tokens without fee in Ether. If the back end is hacked, or it is just unavailable, there's no problem to interact with the network just as it was before, by paying fees in Ether. As well as the back end cannot harm or trick the user to steal their tokens when a proper signature standard is used (it's up to your token implementation).</li>
<li>There is a way to support delegated transactions for existing, already-deployed tokens. However, it requires the additional Ether-consuming step to migrate existing tokens to a new token contract. And, by programming a new token contract properly, as well as designing your application to work with both tokens you can even avoid a need to list a new token on exchanges.</li>
<li>By using the <a target="_blank" href="https://github.com/zitros/ethereum-delegated-tx-service/blob/master/config/contracts/mainnet/0x82f4ded9cec9b5750fbff5c2185aee35afc16587/manifest.js">existing tokens as an example</a>, which is available in delegated transactions <a target="_blank" href="https://github.com/zitros/ethereum-delegated-tx-service">back end</a> and <a target="_blank" href="https://github.com/zitros/ethereum-delegated-tx-widget">front end</a> repositories, you can produce your own manifest for your own token.</li>
<li><a target="_blank" href="https://github.com/zitros/ethereum-delegated-tx-service#setup">Read the instructions</a> on how to set up your own back end for a token, and then add it to the URL of your widget (or commit to the open-source repository).</li>
<li>Have a token which already supports delegated transactions? Plug it into <a target="_blank" href="https://zitros.github.io/ethereum-delegated-tx-widget">our UI</a> with these three quite simple steps: (1) create a manifest for your token and put your token abi file while setting up the delegate back end, (2) run this back end, exposing a public API URL and (3) use URL parameters in a widget to reference your back end or commit it directly to our open-source repository. Read more about it in GitHub's readme file.</li>
</ul>
<p>I hope that was a really helpful piece of information for all the searchers of incredible. Feel free to contact <a target="_blank" href="https://nikita.tk/">me</a> or fill the issue <a target="_blank" href="https://github.com/ZitRos/ethereum-delegated-tx-service/issues">here</a> if I missed something. Have fun, let the token economy be simple!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ This absurd rap battle summarizes the arguments for and against cryptocurrency ]]>
                </title>
                <description>
                    <![CDATA[ A rap battle group has resurrected Alexander Hamilton so he could square off against Satoshi Nakamoto. In a silly (and PG-rated) rap battle, Hamilton and Satoshi argue the merits behind centralized and decentralized currencies. Alexander Hamilton is ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/this-absurd-rap-battle-summarizes-the-arguments-for-and-against-cryptocurrency/</link>
                <guid isPermaLink="false">66b8d60e80f2fbfc1b20bc01</guid>
                
                    <category>
                        <![CDATA[ Bitcoin ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Quincy Larson ]]>
                </dc:creator>
                <pubDate>Thu, 05 Sep 2019 20:47:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/09/maxresdefault--4--1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A rap battle group has resurrected Alexander Hamilton so he could square off against Satoshi Nakamoto.</p>
<p>In a silly (and PG-rated) rap battle, Hamilton and Satoshi argue the merits behind centralized and decentralized currencies.</p>
<p>Alexander Hamilton is one of America's Founding Fathers and served as our first Secretary of Treasury under George Washington. He was a lawyer, banker, and advocate of centralized control of fiscal and monetary policy.</p>
<p>And yes - he's the same Hamilton from the Broadway play.</p>
<p>Hamilton is played by EpicLloyd (of Epic Rap Battles of History fame.)</p>
<p>Satoshi Nakamoto is the creator of the Blockchain and of the Bitcoin cryptocurrency. Nobody knows what he looks like - or whether he's even a real person. (And yes - this is addressed in the rap battle).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/09/printing_front_jpg-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Satoshi Nakamoto's <a target="_blank" href="https://www.freecodecamp.org/news/shop">Programmer Playing Card</a>.</em></p>
<p>Nakamoto is portrayed by an unmasked TimothyDeLaGhetto.</p>
<p>In the 6-minute video, the rappers trade ideological blows with one another.</p>
<p>Hamilton brings up issues with Bitcoin's high transaction costs, scalability issues, and energy consumption.</p>
<p>Nakamoto raps about how untraceable cash can facilitate crime, and how the existence of giant banks can necessitate taxpayer bailouts.</p>
<p>Here's the full video:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/JaMJi1_1tkA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>And here are the full lyrics in case you don't want to be seen at your desk watching Alexander Hamilton rap with a musket in hand. (But really - you should watch it.)</p>
<p>[Alexander Hamilton]<br>Before we begin, everyone do me a favor,<br>And read a little thing I wrote called the Federalist Papers.<br>I explain how a nation’s unlikely to survive<br>Without a strong central government to keep it alive,<br>When I launched the central bank, Jefferson called me ill,<br>Now you have my face to thank on every ten dollar-bill.<br>When America was cash-strapped, I pushed past that,<br>Now some sicko makes crypto and our nation backtracks?</p>
<p>[Satoshi Nakamoto]<br>Decentralized currency. Yes, I invented it.<br>I’m sure many governments wish they had prevented it<br>Their national cash is how they keep control,<br>But freedom to the people was my ultimate goal.<br>Am I a pseudonym? A group of men? It doesn’t even matter.<br>I invented Bitcoin cause fiat is a disaster.<br>A man from Japan or a damn hologram?<br>I’m the reason open season on crypto began.</p>
<p>[Alexander Hamilton]<br>Does anybody know what this crypto-thing means?<br>To me, sounds like the new Get Broke Quick scheme,<br>A bunch of fools from across the land<br>Investing in something they don’t even understand,<br>Buying Litecoin, Dash, Bitcoin Cash,<br>It’s all gonna crash, and be gone in a flash.<br>All this unsupported money’s an irrational prank,<br>And I’ll be laughing all the way to my National Bank.</p>
<p>[Satoshi Nakamoto]<br>Hahahahahah, yeah dude, super funny,<br>As if banks these days still helped people make money.<br>The rich get richer and we follow like we’re all sheep,<br>The banks serve Wall Street, crypto serves all streets,<br>The interest in crypto’s on rapid ascent<br>What’s your current interest? Half a percent?<br>I’m sorry, the bank’s gone past its peak<br>But I want info encrypted, not hacked and leaked.</p>
<p>[Alexander Hamilton]<br>If this crypto system will be our salvation,<br>It needs to be centralized, needs regulation.<br>If our central database gets… how you say, “hacked?”<br>Insurance will just make a case to get your money back.<br>‘Cause in fact, it’s tracked, and the money leaves a trail.<br>Central currency is strong, cryptocurrency is frail.<br>Untraceable money — wow, so clever.<br>One typo in your address? Now it’s gone forever.</p>
<p>[Satoshi Nakamoto]<br>Crypto is frail? That’s the essence of your lesson?<br>Your money leaves a trail? Yeah, a trail to a recession.<br>A buncha rich white guys made this system.<br>Why would they ever change this, when It’s made them rich men!<br>Movie moguls fought hard against the VCR.<br>Horse and buggy manufacturers all hated the car.<br>So why would I take my advice from the banks?<br>I don’t need a bailout to survive. Thanks.</p>
<p>[Satoshi Nakamoto's backup singer]<br>The system is so broken.<br>We need that crypto token.</p>
<p>[Alexander Hamilton's backup singer]<br>The system isn’t broken.<br>Can we trust crypto tokens?</p>
<p>[Alexander Hamilton]<br>It’s gotta be centralized!</p>
<p>[Satoshi Nakamoto]<br>Decentralized!</p>
<p>[Alexander Hamilton]<br>Centralized!</p>
<p>[Satoshi Nakamoto]<br>Decentralized!</p>
<p>[Alexander Hamilton]<br>We need control!</p>
<p>[Satoshi Nakamoto]<br>Free enterprise!</p>
<p>[Debate moderator]<br>Bring me the facts.<br>Please testify.</p>
<p>[Satoshi Nakamoto]<br>Fiat's the way a government controls the populace.</p>
<p>[Alexander Hamilton]<br>Government protects its people. All of this is obvious.<br>They keep the peace, and so they keep control.<br>You want us ruled by crypto-miners no one even knows.</p>
<p>[Satoshi Nakamoto]<br>Oh, it’s that "Strong Central Government" bit again.<br>They protect people, but only their citizens.<br>Crypto has no borders, it's a true global currency.<br>And censorship resistance for those who need it urgently.</p>
<p>[Alexander Hamilton]<br>Banks earn trust by assuming liability.<br>You know a key, we know the customer explicitly.<br>Will the real Satoshi please stand up?<br>Nope, you’ll still be hiding when crypto busts.</p>
<p>[Satoshi Nakamoto]<br>You don’t need to trust the people, you just need to trust the code.<br>Every record’s in the network, you’re just one node.<br>And when you find a flaw, there’s a software update.<br>Now try updating cash. Go ahead, I’ll wait.</p>
<p>[Alexander Hamilton]<br>Wait? Cash works! You immediately pay.<br>Crypto's a far worse medium of exchange.<br>Can’t bitcoin the dentist, can’t bitcoin my breakfast.<br>Can’t even use bitcoin at bitcoin conventions.</p>
<p>[Satoshi Nakamoto]<br>No currency starts with universal adoption.<br>It takes time for places to make it an option.<br>Plus billions of people don’t have bank accounts.<br>No savings, no interest, no checks to bounce.</p>
<p>[Alexander Hamilton]<br>You’re saving the world? But what’s the price you’re paying?<br>The only change you’re creating is climate change.<br>Power grids spiking all across the land.<br>Overheated, no one needs it, hope it all is banned.</p>
<p>[Satoshi Nakamoto]<br>From the king of paper currency, the hypocrisy!<br>For bills and forms in triplicates, you’re killing all the trees.<br>Don’t like my power usage? Stop targeting my rights.<br>I own my purchased power and the market sets the price.</p>
<p>[Alexander Hamilton]<br>It’s gonna get real dark if this is crypto’s night.<br>They use your currency for crimes, that’s your kryptonite.</p>
<p>[Satoshi Nakamoto]<br>Most crime is done with Benjamins, not the blockchain.<br>There’s a reason most dollars carry traces of cocaine.</p>
<p>[Alexander Hamilton]<br>Where’s your proof of work? That’s pure speculation.<br>Those darknet black markets need more regulation.</p>
<p>[Satoshi Nakamoto]<br>The world’s fulla currencies. And this one makes it worse?<br>1 hundred eighty now, Bitcoin’s a hundred-eighty-first.</p>
<p>[Alexander Hamilton]<br>It’s not the currency itself, it’s the method, man.<br>You can’t build things that last without a central plan.</p>
<p>[Satoshi Nakamoto]<br>Crypto is a balance to the centralized model.<br>Cause things fall apart. The center cannot hodl.</p>
<p>[Alexander Hamilton]<br>If you end up having problems, I’ll feel bad for you, son.</p>
<p>[Satoshi Nakamoto]<br>I’ve got 99 problems but a bit ain’t one.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Brave Browser: How much money can your website or YouTube channel make as a publisher? ]]>
                </title>
                <description>
                    <![CDATA[ Over the past 18 months, our nonprofit has made nearly $2,000 from people who are using the Brave Browser to visit freeCodeCamp.org. In this article, I'm going to tell you about the Brave Browser and show how it works. I'll also help you decide wheth... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-brave-browser-how-much-money-can-your-website-make-as-a-publisher/</link>
                <guid isPermaLink="false">66b8d5bb35b58875dce6fdc9</guid>
                
                    <category>
                        <![CDATA[ Brave ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Browsers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ nonprofit ]]>
                    </category>
                
                    <category>
                        <![CDATA[ open source ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Quincy Larson ]]>
                </dc:creator>
                <pubDate>Tue, 27 Aug 2019 12:02:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/08/scrooge.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Over the past 18 months, our nonprofit has made nearly $2,000 from people who are using the Brave Browser to visit freeCodeCamp.org.</p>
<p>In this article, I'm going to tell you about the Brave Browser and show how it works.</p>
<p>I'll also help you decide whether it's worth registering your website or YouTube channel as a Brave publisher.</p>
<p>And if you want to register so you can get paid, I'll show you how to do that, too.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/brave-payments.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Every transfer freeCodeCamp.org has gotten from Brave since we signed up as a publisher (1 BAT = US $0.20)</em></p>
<p>But first, I want to temper your expectations. Unless you have a huge audience, Brave is unlikely to be a significant proportion of your income.</p>
<p>For some perspective:</p>
<ol>
<li>freeCodeCamp.org is one of the top 2,000 most-visited websites</li>
<li>And our audience is mostly developers, who are much more likely to use the Brave Browser than a less-technical audience</li>
</ol>
<p>In other words, your mileage may vary.</p>
<h1 id="heading-a-quick-note-on-my-objectivity">A quick note on my objectivity</h1>
<p>Before anyone accuses me of using my influence to drive up the value of Brave's Basic Attention Token (BAT) cryptocurrency: we sold all of freeCodeCamp's BAT before publishing this.</p>
<p>We transferred it into freeCodeCamp's bank account, where it will help us cover this month's server costs.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/TOTAL_BUS_CHK_-_chase_com.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>By the way, if you want to support freeCodeCamp, I recommend you <a target="_blank" href="https://donate.freecodecamp.org">donate to us directly</a>. This is where a vast majority of our nonprofit's budget comes from. The resources we get from Brave certainly help, but they don't even begin to cover the costs of running a nonprofit like ours.</p>
<h1 id="heading-what-exactly-is-the-brave-browser">What exactly is the Brave Browser?</h1>
<p>Brave is an open source browser with a built-in ad blocker.</p>
<p>Brave was created by Brendan Eich - that same developer who created the JavaScript programming language back in 1995.</p>
<p>The big idea behind Brave is that instead of supporting websites by viewing their banner ads, you can pay them directly through your browser.</p>
<p>Here's how it works:</p>
<ol>
<li>You use money to buy Brave's Basic Attention Token (BAT) cryptocurrency, and that BAT goes into your Brave wallet.</li>
<li>Brave will keep track of how much time you spend on each website or YouTube channel.</li>
<li>Then Brave will divide up your BAT and pay websites and YouTube channels each month based on how much time you spent using them.</li>
</ol>
<p>This means instead of making a bunch of small individual donations to the dozens of websites and YouTube channels you use each month, you can just load money into Brave. Brave will then passively distribute that money for you.</p>
<p>Brave also has a manual "tipping" feature.</p>
<h1 id="heading-how-do-you-make-money-from-brave">How do you make money from Brave?</h1>
<p>First, you have to register your website or YouTube channel as a publisher. You can <a target="_blank" href="https://publishers.basicattentiontoken.org">register as a Brave publisher here</a>.</p>
<p>Then each month, if people are using Brave to browse your website or watch your videos, Brave will send you their Basic Attention Token (BAT) cryptocurrency through a service called Uphold.</p>
<p>In order to actually withdraw that BAT from Uphold (and convert it into another currency), you have to first create an Uphold account.</p>
<p>Note that this involves filling out forms and sharing a lot of sensitive information, such as your bank information, social security number, your ID, and your photo.</p>
<h2 id="heading-how-can-you-can-try-out-the-brave-browser-itself">How can you can try out the Brave Browser itself?</h2>
<p>Brave is free and open source. You don't have to pay money to use it. </p>
<p>But if you do put money into your Brave wallet, Brave will share 95% of that with the websites you visit. (Brave keeps 5% of it as a transaction fee).</p>
<p>If you <a target="_blank" href="https://brave.com/fre385">install Brave using this link</a>, Brave says they'll donate $5 to freeCodeCamp. Brave says - rather vaguely - that you have to "use the browser (minimally) over a 30 day period" in order for freeCodeCamp.org to get the $5. So I guess try to use it at least a little each day.</p>
<p>There are some other interesting aspects of Brave, too. For example, you can voluntarily view Brave's own ads - which are more anonymized than traditional ad network ads. Brave will then pay you a small amount of Basic Attention Token in exchange for your attention.</p>
<p>Brave's approach of replacing more intrusive ads on websites with more privacy-minded ads of their own is still a controversial one. But it could eventually pressure some of the worst actors in the "ad tech" space to become less intrusive themselves.</p>
<h2 id="heading-does-brave-have-a-bright-future">Does Brave have a bright future?</h2>
<p>Over the past 2 years, aside from a few spikes, the value of Brave's BAT cryptocurrency has been around US $0.20 per token:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/Basic_Attention_Token__BAT__price__marketcap__chart__and_fundamentals_info___CoinGecko.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I don't know anyone working at Brave, and I don't have any information about their company that isn't already public.</p>
<p>According to Crunchbase, Brave hasn't raised any money since June of 2017, when they had <a target="_blank" href="https://techcrunch.com/2017/06/01/brave-ico-35-million-30-seconds-brendan-eich/">one of the only successful ICOs in history</a>, selling $35 million worth of BAT in less than 30 seconds.</p>
<p>It's possible they may not need to raise additional funding if they are making enough money through BAT and their operations.</p>
<p>If anything, Brave seems well-poised to grow. Google plans to <a target="_blank" href="https://www.wired.com/story/google-chrome-ad-blockers-extensions-api/">essentially kill ad-blocker Chrome extensions</a>. This may cause more people to switch over to a browsers with built-in ad blockers, like Brave.</p>
<h2 id="heading-how-are-your-brave-earnings-so-far">How are your Brave earnings so far?</h2>
<p>If you've been a Brave publisher for a while, I encourage you to share your numbers. How much have you all made from Brave so far?</p>
<p>I hope this guide has been a helpful resource for you. Happy coding.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Technical primer to Blockchain & Ethereum ]]>
                </title>
                <description>
                    <![CDATA[ By Srinivasan C I attended a talk on Ethereum sometime back and was fascinated by the possibilities it provided and started exploring the ecosystem. It is a pretty nascent ecosystem that is catching up fast among the developer community. In this post... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/technical-primer-to-blockchain-ethereum/</link>
                <guid isPermaLink="false">66d4614fbd438296f45cd3be</guid>
                
                    <category>
                        <![CDATA[ Blockchain ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ethereum ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ethereum blockchain ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 23 Jul 2019 06:30:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9ca14a740569d1a4ca4dc5.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Srinivasan C</p>
<p>I attended a talk on Ethereum sometime back and was fascinated by the possibilities it provided and started exploring the ecosystem. It is a pretty nascent ecosystem that is catching up fast among the developer community. In this post I will explain the technology behind Ethereum so that we can get started with developing with Ethereum. This assumes you have technology background and basic understanding of blockchain so that we can discuss the Ethereum implementation.</p>
<h2 id="heading-first-things-first">First things first</h2>
<p>Blockchain provides a <strong>de-centralized</strong>, <strong>peer to peer</strong> network where digital assets can be transferred from one peer to another. The major problem we face in a de-centralized network is who will verify the validity of all the <strong>transactions</strong> taking place? The short answer is <strong>everyone.</strong></p>
<p>Imagine a document with some information . Each person in the network keeps a copy of the same document. If there is an update in the document, it is propagated across the network and everyone updates their own copy of the document. Lets say a new person comes with different content in the document, then all the others can verify their copy and detect that the new person is lying and kick him out of the network. This is basically how a blockchain works.</p>
<p>First we need to understand few basic terms to get started.</p>
<h3 id="heading-hash">Hash</h3>
<p>We can use a cryptographic hash function(SHA256) to convert any string to its equivalent hash. The hash has two unique properties:</p>
<ol>
<li>The hash produced has <strong>one to one mapping</strong> with the input string. The same input always produces the same unique hash and no other input can have the same hash.</li>
<li>Even a <strong>small change</strong> in the input string will lead to a <strong>large change</strong> in the output hash and thus the input can be easily validated.</li>
</ol>
<h3 id="heading-transaction">Transaction</h3>
<p>The process by which assets are moved from one party to another in the network is known as Transaction. All transactions are recorded and permanently stored.Lets say A wants to transfer 5 Ether to B. Then this is a transaction in the network.</p>
<h3 id="heading-block">Block</h3>
<p>Many transactions are combined together to form a block. Each block consists a unique <strong>hash</strong> which identifies it in the network. A block is chained to previous block using the hash of the previous block.</p>
<h3 id="heading-genesis-block">Genesis Block</h3>
<p>The initial block or state of the blockchain that is agreed upon by all the nodes in the network.</p>
<h3 id="heading-blockchain">Blockchain</h3>
<p>As the transactions are added many blocks are created and then they are chained together using their hashes into blockchain network.</p>
<h3 id="heading-proof-of-work">Proof of work</h3>
<p>A <strong>proof of work</strong> is a piece of data which is difficult (costly, time-consuming) to produce but easy for others to verify and which satisfies certain requirements. When there is a transaction in the network, any node that tries to process the transaction should solve a cryptographic puzzle for it to be accepted to the block. This is known as proof of work. The work that is to be performed can be done only by trial and error and this has to be performed for any valid transaction in the network before it can become part of the blockchain.</p>
<h3 id="heading-mining">Mining</h3>
<p>The process of processing a transaction and adding it to the block by carrying out the proof of work is known as mining. The miners(nodes) get the rewards of the transaction once the transaction is accepted as part of the blockchain.</p>
<h3 id="heading-merkle-tree">Merkle Tree</h3>
<p>A <strong>Merkle tree</strong> is a tree in which every non-leaf node is labelled with the hash of the labels of its child nodes. We can verify that the data blocks received from other nodes are received undamaged and unaltered, and even to check that the other nodes do not lie and send fake blocks.</p>
<h3 id="heading-working">Working</h3>
<p>We can now move on to basic working of a blockchain.</p>
<ol>
<li>Each node starts with genesis block and builds its way up to the “current state” of the blockchain. When it receives a new block each node verifies its hash and thus validates if its a valid block or not and keeps building the chain.</li>
<li>Once there is a transaction in the network, the miner mines it by generating the required proof of work. Then the miner adds it to his copy of the network and <strong>propagates</strong> the change to the nearby nodes.</li>
<li>All the nodes which receives it will validate the proof of work and then add it to their respective copies. If it is not valid, then the block is not added to the chain.</li>
<li>When there is a conflict in the network , then the “longest chain rule” is applied to resolve it. Lets say two miners claim the same block and both have valid proof of work. Then the longest chain rule is applied which is whichever miner has the longest chain of blocks will be taken as the winner and that is added to the blockchain.</li>
</ol>
<h2 id="heading-ethereum">Ethereum</h2>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*AReX8uZOZKpGcvuUjogh0g.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now that you have got a grasp of blockchain lets move ahead with Ethereum. Ethereum is a <strong>decentralized platform that</strong> allows us to write applications that run exactly as programmed without any possibility of downtime, censorship, fraud or third party interference. It consists of Ethereum Virtual Machine(EVM) which provides the container in which all the smart contracts can be executed.</p>
<h3 id="heading-smart-contracts">Smart contracts</h3>
<p>Ethereum allows us to write applications on the blockchain and this applications are known as smart contracts. These smart contracts reside on the blockchain and they are <strong>immutable</strong> in nature, ie. the code cannot be deleted or modified in the blockchain once it is deployed. This can be written using Solidity or other languages, but the most preferred is solidity. It is a turing complete language.</p>
<h3 id="heading-ether">Ether</h3>
<p>Ether is the cryptocurrency used in the Ethereum blockchain.</p>
<h3 id="heading-accounts">Accounts</h3>
<p>In Ethereum, the state is made up of objects called “accounts”, with each account having a 20-byte address and state transitions being direct transfers of value and information between accounts. There are two types of accounts in Ethereum:</p>
<ul>
<li><strong>Externally owned accounts :</strong> These accounts are owned by users, controlled by private keys. An externally owned account has no code, and one can send messages from an externally owned account by creating and signing a transaction.</li>
<li><strong>Contract accounts:</strong> These accounts are owned by contract code. In a contract account, every time the contract account receives a message its code activates, allowing it to read and write to internal storage and send other messages or create contracts in turn.</li>
</ul>
<h3 id="heading-gas">Gas</h3>
<p>As smart contracts are turing complete any infinity loop or other code can be written and the blockchain can be crashed. To prevent from such attacks Ethereum uses a concept called gas. Gas is nothing but some transaction cost which is paid to execute the transaction using Ether(basic currency in Ethereum chain). Each instruction requires some gas to be executed and the gas is sent along with any call that needs to modify the blockchain.</p>
<h3 id="heading-dapps">DAPPS</h3>
<p>These are distributed apps that can be built using the smart contracts and providing an interface for the users(accounts). Different kinds of applications can be developed which will interact with smart contracts residing in the blockchain.</p>
<h3 id="heading-basic-workflow-using-ethereum">Basic Workflow using Ethereum</h3>
<p>We can discuss a basic workflow in Ethereum network for better understanding of how all these concepts work together in unison.</p>
<ol>
<li>We can write smart contracts and deploy it to Ethereum network. Once deployed these contracts cannot be changed.</li>
<li>Any account or another smart contract in the network can execute these smart contracts functions through transactions.</li>
<li>The smart contracts can be called and executed by sending transactions to the contract. These transactions cost <strong>gas</strong> and a certain gas should also be sent along with the transaction.</li>
<li>Sometimes we just need to know the state of some contract without modifying the blockchain. These are known as <strong>calls and they do not cost any gas.</strong></li>
<li>We can build various Dapps by executing the smart contracts using transactions and calls , thus allowing the user to directly interact the smart contract in different ways.</li>
</ol>
<p>I believe this post provides basic understanding of the blockchain and Ethereum. In my next post I will provide a detailed guide to getting started with building Dapps using Ethereum.</p>
<p><em>If you liked this story, feel free to reach out to me at <a target="_blank" href="https://kaizencoder.com/contact">https://kaizencoder.com/</a></em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to handle RESTful web Services using Retrofit, OkHttp, Gson, Glide and Coroutines ]]>
                </title>
                <description>
                    <![CDATA[ By Andrius Baruckis Kriptofolio app series — Part 5 These days almost every Android app connects to internet to get/send data. You should definitely learn how to handle RESTful Web Services, as their correct implementation is the core knowledge while... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/kriptofolio-app-series-part-5/</link>
                <guid isPermaLink="false">66d45dde36c45a88f96b7cc7</guid>
                
                    <category>
                        <![CDATA[ Android ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ web services ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 11 May 2019 08:26:24 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*F9gJTRqiq_YPvga0sPu_qw.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Andrius Baruckis</p>
<h4 id="heading-kriptofolio-app-series-part-5">Kriptofolio app series — Part 5</h4>
<p>These days almost every Android app connects to internet to get/send data. You should definitely learn how to handle RESTful Web Services, as their correct implementation is the core knowledge while creating modern apps.</p>
<p>This part is going to be complicated. We are going to combine multiple libraries at once to get a working result. I am not going to talk about the native Android way to handle internet requests, because in the real world nobody uses it. Every good app does not try to reinvent the wheel but instead uses the most popular third party libraries to solve common problems. It would be too complicated to recreate the functionality that these well-made libraries have to offer.</p>
<h3 id="heading-series-content">Series content</h3>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series">Introduction: A roadmap to build a modern Android app in 2018–2019</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series-part-1">Part 1: An introduction to the SOLID principles</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series-part-2">Part 2: How to start building your Android app: creating Mockups, UI, and XML layouts</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series-part-3">Part 3: All about that Architecture: exploring different architecture patterns and how to use them in your app</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series-part-4">Part 4: How to implement Dependency Injection in your app with Dagger 2</a></li>
<li>Part 5: Handle RESTful Web Services using Retrofit, OkHttp, Gson, Glide and Coroutines (you’re here)</li>
</ul>
<h3 id="heading-what-is-retrofit-okhttp-and-gson">What is Retrofit, OkHttp and Gson?</h3>
<p>Retrofit is a REST Client for Java and Android. This library, in my opinion, is the most important one to learn, as it will do the main job. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice.</p>
<p>In Retrofit you configure which converter is used for the data serialization. Typically to serialize and deserialize objects to and from JSON you use an open-source Java library — Gson. Also if you need, you can add custom converters to Retrofit to process XML or other protocols.</p>
<p>For making HTTP requests Retrofit uses the OkHttp library. OkHttp is a pure HTTP/SPDY client responsible for any low-level network operations, caching, requests and responses manipulation. In contrast, Retrofit is a high-level REST abstraction build on top of OkHttp. Retrofit is strongly coupled with OkHttp and makes intensive use of it.</p>
<p>Now that you know that everything is closely related, we are going to use all these 3 libraries at once. Our first goal is to get all the cryptocurrencies list using Retrofit from the Internet. We will use a special OkHttp interceptor class for CoinMarketCap API authentication when making a call to the server. We will get back a JSON data result and then convert it using the Gson library.</p>
<h3 id="heading-quick-setup-for-retrofit-2-just-to-try-it-first">Quick setup for Retrofit 2 just to try it first</h3>
<p>When learning something new, I like to try it out in practice as soon as I can. We will apply a similar approach with Retrofit 2 for you to understand it better more quickly. Don’t worry right now about code quality or any programming principles or optimizations — we’ll just write some code to make Retrofit 2 work in our project and discuss what it does.</p>
<p>Follow these steps to set up Retrofit 2 on My Crypto Coins app project:</p>
<h4 id="heading-first-give-internet-permission-for-the-app"><strong>First, give INTERNET permission for the app</strong></h4>
<p>We are going to execute HTTP requests on a server accessible via the Internet. Give this permission by adding these lines to your Manifest file:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">manifest</span> <span class="hljs-attr">xmlns:android</span>=<span class="hljs-string">"http://schemas.android.com/apk/res/android"</span>
    <span class="hljs-attr">package</span>=<span class="hljs-string">"com.baruckis.mycryptocoins"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">uses-permission</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.permission.INTERNET"</span> /&gt;</span>
    ...
<span class="hljs-tag">&lt;/<span class="hljs-name">manifest</span>&gt;</span>
</code></pre>
<h4 id="heading-then-you-should-add-library-dependencies"><strong>Then you should add library dependencies</strong></h4>
<p>Find the latest <a target="_blank" href="https://square.github.io/retrofit/">Retrofit version</a>. Also you should know that Retrofit doesn’t ship with an integrated JSON converter. Since we will get responses in JSON format, we need to include the converter manually in the dependencies too. We are going to use latest Google’s JSON converter <a target="_blank" href="https://github.com/google/gson">Gson version</a>. Let’s add these lines to your gradle file:</p>
<pre><code class="lang-gradle">// 3rd party
// HTTP client - Retrofit with OkHttp
implementation "com.squareup.retrofit2:retrofit:$versions.retrofit"
// JSON converter Gson for JSON to Java object mapping
implementation "com.squareup.retrofit2:converter-gson:$versions.retrofit"
</code></pre>
<p>As you noticed from my comment, the OkHttp dependency is already shipped with the Retrofit 2 dependency. Versions is just a separate gradle file for convenience:</p>
<pre><code class="lang-gradle">def versions = [:]

versions.retrofit = "2.4.0"

ext.versions = versions
</code></pre>
<h4 id="heading-next-set-up-the-retrofit-interface"><strong>Next set up the Retrofit interface</strong></h4>
<p>It’s an interface that declares our requests and their types. Here we define the API on the client side.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * REST API access points.
 */</span>
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ApiService</span> </span>{

    <span class="hljs-comment">// The @GET annotation tells retrofit that this request is a get type request.</span>
    <span class="hljs-comment">// The string value tells retrofit that the path of this request is</span>
    <span class="hljs-comment">// baseUrl + v1/cryptocurrency/listings/latest + query parameter.</span>
    <span class="hljs-meta">@GET(<span class="hljs-meta-string">"v1/cryptocurrency/listings/latest"</span>)</span>
    <span class="hljs-comment">// Annotation @Query is used to define query parameter for request. Finally the request url will</span>
    <span class="hljs-comment">// look like that https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?convert=EUR.</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getAllCryptocurrencies</span><span class="hljs-params">(<span class="hljs-meta">@Query(<span class="hljs-meta-string">"convert"</span>)</span> currency: <span class="hljs-type">String</span>)</span></span>: Call&lt;CryptocurrenciesLatest&gt;
    <span class="hljs-comment">// The return type for this function is Call with its type CryptocurrenciesLatest.</span>
}
</code></pre>
<h4 id="heading-and-set-up-the-data-class"><strong>And set up the data class</strong></h4>
<p>Data classes are POJOs (Plain Old Java Objects) that represent the responses of the API calls we’re going to make.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * Data class to handle the response from the server.
 */</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CryptocurrenciesLatest</span></span>(
        <span class="hljs-keyword">val</span> status: Status,
        <span class="hljs-keyword">val</span> <span class="hljs-keyword">data</span>: List&lt;Data&gt;
) {

    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Data</span></span>(
            <span class="hljs-keyword">val</span> id: <span class="hljs-built_in">Int</span>,
            <span class="hljs-keyword">val</span> name: String,
            <span class="hljs-keyword">val</span> symbol: String,
            <span class="hljs-keyword">val</span> slug: String,
            <span class="hljs-comment">// The annotation to a model property lets you pass the serialized and deserialized</span>
            <span class="hljs-comment">// name as a string. This is useful if you don't want your model class and the JSON</span>
            <span class="hljs-comment">// to have identical naming.</span>
            <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"circulating_supply"</span>)</span>
            <span class="hljs-keyword">val</span> circulatingSupply: <span class="hljs-built_in">Double</span>,
            <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"total_supply"</span>)</span>
            <span class="hljs-keyword">val</span> totalSupply: <span class="hljs-built_in">Double</span>,
            <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"max_supply"</span>)</span>
            <span class="hljs-keyword">val</span> maxSupply: <span class="hljs-built_in">Double</span>,
            <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"date_added"</span>)</span>
            <span class="hljs-keyword">val</span> dateAdded: String,
            <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"num_market_pairs"</span>)</span>
            <span class="hljs-keyword">val</span> numMarketPairs: <span class="hljs-built_in">Int</span>,
            <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"cmc_rank"</span>)</span>
            <span class="hljs-keyword">val</span> cmcRank: <span class="hljs-built_in">Int</span>,
            <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"last_updated"</span>)</span>
            <span class="hljs-keyword">val</span> lastUpdated: String,
            <span class="hljs-keyword">val</span> quote: Quote
    ) {

        <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Quote</span></span>(
                <span class="hljs-comment">// For additional option during deserialization you can specify value or alternative</span>
                <span class="hljs-comment">// values. Gson will check the JSON for all names we specify and try to find one to</span>
                <span class="hljs-comment">// map it to the annotated property.</span>
                <span class="hljs-meta">@SerializedName(value = <span class="hljs-meta-string">"USD"</span>, alternate = [<span class="hljs-meta-string">"AUD"</span>, <span class="hljs-meta-string">"BRL"</span>, <span class="hljs-meta-string">"CAD"</span>, <span class="hljs-meta-string">"CHF"</span>, <span class="hljs-meta-string">"CLP"</span>,
                    <span class="hljs-meta-string">"CNY"</span>, <span class="hljs-meta-string">"CZK"</span>, <span class="hljs-meta-string">"DKK"</span>, <span class="hljs-meta-string">"EUR"</span>, <span class="hljs-meta-string">"GBP"</span>, <span class="hljs-meta-string">"HKD"</span>, <span class="hljs-meta-string">"HUF"</span>, <span class="hljs-meta-string">"IDR"</span>, <span class="hljs-meta-string">"ILS"</span>, <span class="hljs-meta-string">"INR"</span>, <span class="hljs-meta-string">"JPY"</span>,
                    <span class="hljs-meta-string">"KRW"</span>, <span class="hljs-meta-string">"MXN"</span>, <span class="hljs-meta-string">"MYR"</span>, <span class="hljs-meta-string">"NOK"</span>, <span class="hljs-meta-string">"NZD"</span>, <span class="hljs-meta-string">"PHP"</span>, <span class="hljs-meta-string">"PKR"</span>, <span class="hljs-meta-string">"PLN"</span>, <span class="hljs-meta-string">"RUB"</span>, <span class="hljs-meta-string">"SEK"</span>, <span class="hljs-meta-string">"SGD"</span>,
                    <span class="hljs-meta-string">"THB"</span>, <span class="hljs-meta-string">"TRY"</span>, <span class="hljs-meta-string">"TWD"</span>, <span class="hljs-meta-string">"ZAR"</span>])</span>
                <span class="hljs-keyword">val</span> currency: Currency
        ) {

            <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Currency</span></span>(
                    <span class="hljs-keyword">val</span> price: <span class="hljs-built_in">Double</span>,
                    <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"volume_24h"</span>)</span>
                    <span class="hljs-keyword">val</span> volume24h: <span class="hljs-built_in">Double</span>,
                    <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"percent_change_1h"</span>)</span>
                    <span class="hljs-keyword">val</span> percentChange1h: <span class="hljs-built_in">Double</span>,
                    <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"percent_change_24h"</span>)</span>
                    <span class="hljs-keyword">val</span> percentChange24h: <span class="hljs-built_in">Double</span>,
                    <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"percent_change_7d"</span>)</span>
                    <span class="hljs-keyword">val</span> percentChange7d: <span class="hljs-built_in">Double</span>,
                    <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"market_cap"</span>)</span>
                    <span class="hljs-keyword">val</span> marketCap: <span class="hljs-built_in">Double</span>,
                    <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"last_updated"</span>)</span>
                    <span class="hljs-keyword">val</span> lastUpdated: String
            )
        }
    }

    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Status</span></span>(
            <span class="hljs-keyword">val</span> timestamp: String,
            <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"error_code"</span>)</span>
            <span class="hljs-keyword">val</span> errorCode: <span class="hljs-built_in">Int</span>,
            <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"error_message"</span>)</span>
            <span class="hljs-keyword">val</span> errorMessage: String,
            <span class="hljs-keyword">val</span> elapsed: <span class="hljs-built_in">Int</span>,
            <span class="hljs-meta">@SerializedName(<span class="hljs-meta-string">"credit_count"</span>)</span>
            <span class="hljs-keyword">val</span> creditCount: <span class="hljs-built_in">Int</span>
    )
}
</code></pre>
<h4 id="heading-create-a-special-interceptor-class-for-authentication-when-making-a-call-to-the-server"><strong>Create a special interceptor class for authentication when making a call to the server</strong></h4>
<p>This is the case particular for any API that requires authentication to get a successful response. Interceptors are a powerful way to customize your requests. We are going to intercept the actual request and to add individual request headers, which will validate the call with an API Key provided by <a target="_blank" href="https://pro.coinmarketcap.com">CoinMarketCap Professional API Developer Portal</a>. To get yours, you need to register there.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * Interceptor used to intercept the actual request and
 * to supply your API Key in REST API calls via a custom header.
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AuthenticationInterceptor</span> : <span class="hljs-type">Interceptor {</span></span>

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">intercept</span><span class="hljs-params">(chain: <span class="hljs-type">Interceptor</span>.<span class="hljs-type">Chain</span>)</span></span>: Response {

        <span class="hljs-keyword">val</span> newRequest = chain.request().newBuilder()
                <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> Use your API Key provided by CoinMarketCap Professional API Developer Portal.</span>
                .addHeader(<span class="hljs-string">"X-CMC_PRO_API_KEY"</span>, <span class="hljs-string">"CMC_PRO_API_KEY"</span>)
                .build()

        <span class="hljs-keyword">return</span> chain.proceed(newRequest)
    }
}
</code></pre>
<h4 id="heading-finally-add-this-code-to-our-activity-to-see-retrofit-working"><strong>Finally, add this code to our activity to see Retrofit working</strong></h4>
<p>I wanted to get your hands dirty as soon as possible, so I put everything in one place. This is not the correct way, but it’s the fastest instead just to see a visual result quickly.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AddSearchActivity</span> : <span class="hljs-type">AppCompatActivity</span></span>(), Injectable {

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> listView: ListView
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> listAdapter: AddSearchListAdapter

    ...

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)

        ...

        <span class="hljs-comment">// Later we will setup Retrofit correctly, but for now we do all in one place just for quick start.</span>
        setupRetrofitTemporarily()
    }

    ...

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">setupRetrofitTemporarily</span><span class="hljs-params">()</span></span> {

        <span class="hljs-comment">// We need to prepare a custom OkHttp client because need to use our custom call interceptor.</span>
        <span class="hljs-comment">// to be able to authenticate our requests.</span>
        <span class="hljs-keyword">val</span> builder = OkHttpClient.Builder()
        <span class="hljs-comment">// We add the interceptor to OkHttpClient.</span>
        <span class="hljs-comment">// It will add authentication headers to every call we make.</span>
        builder.interceptors().add(AuthenticationInterceptor())
        <span class="hljs-keyword">val</span> client = builder.build()


        <span class="hljs-keyword">val</span> api = Retrofit.Builder() <span class="hljs-comment">// Create retrofit builder.</span>
                .baseUrl(<span class="hljs-string">"https://sandbox-api.coinmarketcap.com/"</span>) <span class="hljs-comment">// Base url for the api has to end with a slash.</span>
                .addConverterFactory(GsonConverterFactory.create()) <span class="hljs-comment">// Use GSON converter for JSON to POJO object mapping.</span>
                .client(client) <span class="hljs-comment">// Here we set the custom OkHttp client we just created.</span>
                .build().create(ApiService::<span class="hljs-keyword">class</span>.java) // We create an API using the <span class="hljs-keyword">interface</span> we defined.


        <span class="hljs-keyword">val</span> adapterData: MutableList&lt;Cryptocurrency&gt; = ArrayList&lt;Cryptocurrency&gt;()

        <span class="hljs-keyword">val</span> currentFiatCurrencyCode = <span class="hljs-string">"EUR"</span>

        <span class="hljs-comment">// Let's make asynchronous network request to get all latest cryptocurrencies from the server.</span>
        <span class="hljs-comment">// For query parameter we pass "EUR" as we want to get prices in euros.</span>
        <span class="hljs-keyword">val</span> call = api.getAllCryptocurrencies(<span class="hljs-string">"EUR"</span>)
        <span class="hljs-keyword">val</span> result = call.enqueue(<span class="hljs-keyword">object</span> : Callback&lt;CryptocurrenciesLatest&gt; {

            <span class="hljs-comment">// You will always get a response even if something wrong went from the server.</span>
            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onFailure</span><span class="hljs-params">(call: <span class="hljs-type">Call</span>&lt;<span class="hljs-type">CryptocurrenciesLatest</span>&gt;, t: <span class="hljs-type">Throwable</span>)</span></span> {

                Snackbar.make(findViewById(android.R.id.content),
                        <span class="hljs-comment">// Throwable will let us find the error if the call failed.</span>
                        <span class="hljs-string">"Call failed! "</span> + t.localizedMessage,
                        Snackbar.LENGTH_INDEFINITE).show()
            }

            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onResponse</span><span class="hljs-params">(call: <span class="hljs-type">Call</span>&lt;<span class="hljs-type">CryptocurrenciesLatest</span>&gt;, response: <span class="hljs-type">Response</span>&lt;<span class="hljs-type">CryptocurrenciesLatest</span>&gt;)</span></span> {

                <span class="hljs-comment">// Check if the response is successful, which means the request was successfully</span>
                <span class="hljs-comment">// received, understood, accepted and returned code in range [200..300).</span>
                <span class="hljs-keyword">if</span> (response.isSuccessful) {

                    <span class="hljs-comment">// If everything is OK, let the user know that.</span>
                    Toast.makeText(<span class="hljs-keyword">this</span><span class="hljs-symbol">@AddSearchActivity</span>, <span class="hljs-string">"Call OK."</span>, Toast.LENGTH_LONG).show();

                    <span class="hljs-comment">// Than quickly map server response data to the ListView adapter.</span>
                    <span class="hljs-keyword">val</span> cryptocurrenciesLatest: CryptocurrenciesLatest? = response.body()
                    cryptocurrenciesLatest!!.<span class="hljs-keyword">data</span>.forEach {
                        <span class="hljs-keyword">val</span> cryptocurrency = Cryptocurrency(it.name, it.cmcRank.toShort(),
                                <span class="hljs-number">0.0</span>, it.symbol, currentFiatCurrencyCode, it.quote.currency.price,
                                <span class="hljs-number">0.0</span>, it.quote.currency.percentChange1h,
                                it.quote.currency.percentChange7d, it.quote.currency.percentChange24h,
                                <span class="hljs-number">0.0</span>)
                        adapterData.add(cryptocurrency)
                    }

                    listView.visibility = View.VISIBLE
                    listAdapter.setData(adapterData)

                }
                <span class="hljs-comment">// Else if the response is unsuccessful it will be defined by some special HTTP</span>
                <span class="hljs-comment">// error code, which we can show for the user.</span>
                <span class="hljs-keyword">else</span> Snackbar.make(findViewById(android.R.id.content),
                        <span class="hljs-string">"Call error with HTTP status code "</span> + response.code() + <span class="hljs-string">"!"</span>,
                        Snackbar.LENGTH_INDEFINITE).show()

            }

        })

    }

   ...
}
</code></pre>
<p>You can explore the code <a target="_blank" href="https://github.com/baruckis/Kriptofolio/tree/4d7946705b8c4dc2db3775bcc000d2918f8f1b73">here</a>. Remember this is only an initial simplified implementation version for you to get the idea better.</p>
<h3 id="heading-final-correct-setup-for-retrofit-2-with-okhttp-3-and-gson">Final correct setup for Retrofit 2 with OkHttp 3 and Gson</h3>
<p>Ok after a quick experiment, it is time to bring this Retrofit implementation to the next level. We already got the data successfully but not correctly. We are missing the states like loading, error and success. Our code is mixed without separation of concerns. It’s a common mistake to write all your code in an activity or a fragment. Our activity class is UI based and should only contain logic that handles UI and operating system interactions.</p>
<p>Actually, after this quick setup, I worked a lot and made many changes. There is no point to put all the code that was changed in the article. Better instead you should browse the final Part 5 code repo <a target="_blank" href="https://github.com/baruckis/Kriptofolio/tree/Part-5">here</a>. I have commented everything very well and my code should be clear for you to understand. But I am going to talk about most important things I have done and why I did them.</p>
<p>The first step to improve was to start using Dependency Injection. Remember from the <a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series-part-4">previous part</a> we already have Dagger 2 implemented inside the project correctly. So I used it for the Retrofit setup.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * AppModule will provide app-wide dependencies for a part of the application.
 * It should initialize objects used across our application, such as Room database, Retrofit, Shared Preference, etc.
 */</span>
<span class="hljs-meta">@Module(includes = [ViewModelsModule::class])</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppModule</span></span>() {
    ...

    <span class="hljs-meta">@Provides</span>
    <span class="hljs-meta">@Singleton</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">provideHttpClient</span><span class="hljs-params">()</span></span>: OkHttpClient {
        <span class="hljs-comment">// We need to prepare a custom OkHttp client because need to use our custom call interceptor.</span>
        <span class="hljs-comment">// to be able to authenticate our requests.</span>
        <span class="hljs-keyword">val</span> builder = OkHttpClient.Builder()
        <span class="hljs-comment">// We add the interceptor to OkHttpClient.</span>
        <span class="hljs-comment">// It will add authentication headers to every call we make.</span>
        builder.interceptors().add(AuthenticationInterceptor())

        <span class="hljs-comment">// Configure this client not to retry when a connectivity problem is encountered.</span>
        builder.retryOnConnectionFailure(<span class="hljs-literal">false</span>)

        <span class="hljs-comment">// Log requests and responses.</span>
        <span class="hljs-comment">// Add logging as the last interceptor, because this will also log the information which</span>
        <span class="hljs-comment">// you added or manipulated with previous interceptors to your request.</span>
        builder.interceptors().add(HttpLoggingInterceptor().apply {
            <span class="hljs-comment">// For production environment to enhance apps performance we will be skipping any</span>
            <span class="hljs-comment">// logging operation. We will show logs just for debug builds.</span>
            level = <span class="hljs-keyword">if</span> (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY <span class="hljs-keyword">else</span> HttpLoggingInterceptor.Level.NONE
        })
        <span class="hljs-keyword">return</span> builder.build()
    }

    <span class="hljs-meta">@Provides</span>
    <span class="hljs-meta">@Singleton</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">provideApiService</span><span class="hljs-params">(httpClient: <span class="hljs-type">OkHttpClient</span>)</span></span>: ApiService {
        <span class="hljs-keyword">return</span> Retrofit.Builder() <span class="hljs-comment">// Create retrofit builder.</span>
                .baseUrl(API_SERVICE_BASE_URL) <span class="hljs-comment">// Base url for the api has to end with a slash.</span>
                .addConverterFactory(GsonConverterFactory.create()) <span class="hljs-comment">// Use GSON converter for JSON to POJO object mapping.</span>
                .addCallAdapterFactory(LiveDataCallAdapterFactory())
                .client(httpClient) <span class="hljs-comment">// Here we set the custom OkHttp client we just created.</span>
                .build().create(ApiService::<span class="hljs-keyword">class</span>.java) <span class="hljs-comment">// We create an API using the interface we defined.</span>
    }

    ...
}
</code></pre>
<p>Now as you see, Retrofit is separated from the activity class as it should be. It will be initialized only once and used app-wide.</p>
<p>As you may have noticed while creating the Retrofit builder instance, we added a special Retrofit calls adapter using <code>addCallAdapterFactory</code>. By default, Retrofit returns a <code>Call&lt;T&gt;</code>, but for our project we require it to return a <code>LiveData&lt;T&gt;</code> type. In order to do that we need to add <code>LiveDataCallAdapter</code> by using <code>LiveDataCallAdapterFactory</code>.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * A Retrofit adapter that converts the Call into a LiveData of ApiResponse.
 * <span class="hljs-doctag">@param</span> &lt;R&gt;
&lt;/R&gt; */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LiveDataCallAdapter</span>&lt;<span class="hljs-type">R</span>&gt;</span>(<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> responseType: Type) :
        CallAdapter&lt;R, LiveData&lt;ApiResponse&lt;R&gt;&gt;&gt; {

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">responseType</span><span class="hljs-params">()</span></span> = responseType

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">adapt</span><span class="hljs-params">(call: <span class="hljs-type">Call</span>&lt;<span class="hljs-type">R</span>&gt;)</span></span>: LiveData&lt;ApiResponse&lt;R&gt;&gt; {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">object</span> : LiveData&lt;ApiResponse&lt;R&gt;&gt;() {
            <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> started = AtomicBoolean(<span class="hljs-literal">false</span>)
            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onActive</span><span class="hljs-params">()</span></span> {
                <span class="hljs-keyword">super</span>.onActive()
                <span class="hljs-keyword">if</span> (started.compareAndSet(<span class="hljs-literal">false</span>, <span class="hljs-literal">true</span>)) {
                    call.enqueue(<span class="hljs-keyword">object</span> : Callback&lt;R&gt; {
                        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onResponse</span><span class="hljs-params">(call: <span class="hljs-type">Call</span>&lt;<span class="hljs-type">R</span>&gt;, response: <span class="hljs-type">Response</span>&lt;<span class="hljs-type">R</span>&gt;)</span></span> {
                            postValue(ApiResponse.create(response))
                        }

                        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onFailure</span><span class="hljs-params">(call: <span class="hljs-type">Call</span>&lt;<span class="hljs-type">R</span>&gt;, throwable: <span class="hljs-type">Throwable</span>)</span></span> {
                            postValue(ApiResponse.create(throwable))
                        }
                    })
                }
            }
        }
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LiveDataCallAdapterFactory</span> : <span class="hljs-type">CallAdapter.Factory</span></span>() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">get</span><span class="hljs-params">(
            returnType: <span class="hljs-type">Type</span>,
            annotations: <span class="hljs-type">Array</span>&lt;<span class="hljs-type">Annotation</span>&gt;,
            retrofit: <span class="hljs-type">Retrofit</span>
    )</span></span>: CallAdapter&lt;*, *&gt;? {
        <span class="hljs-keyword">if</span> (CallAdapter.Factory.getRawType(returnType) != LiveData::<span class="hljs-keyword">class</span>.java) {
            return <span class="hljs-literal">null</span>
        }
        <span class="hljs-keyword">val</span> observableType = CallAdapter.Factory.getParameterUpperBound(<span class="hljs-number">0</span>, returnType <span class="hljs-keyword">as</span> ParameterizedType)
        <span class="hljs-keyword">val</span> rawObservableType = CallAdapter.Factory.getRawType(observableType)
        <span class="hljs-keyword">if</span> (rawObservableType != ApiResponse::<span class="hljs-keyword">class</span>.java) {
            <span class="hljs-keyword">throw</span> IllegalArgumentException(<span class="hljs-string">"type must be a resource"</span>)
        }
        <span class="hljs-keyword">if</span> (observableType !<span class="hljs-keyword">is</span> ParameterizedType) {
            <span class="hljs-keyword">throw</span> IllegalArgumentException(<span class="hljs-string">"resource must be parameterized"</span>)
        }
        <span class="hljs-keyword">val</span> bodyType = CallAdapter.Factory.getParameterUpperBound(<span class="hljs-number">0</span>, observableType)
        <span class="hljs-keyword">return</span> LiveDataCallAdapter&lt;Any&gt;(bodyType)
    }
}
</code></pre>
<p>Now we will get <code>LiveData&lt;T&gt;</code> instead of <code>Call&lt;T&gt;</code> as the return type from Retrofit service methods defined in the <code>ApiService</code> interface.</p>
<p>Another important step to make is to start using the Repository pattern. I have talked about it in <a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series-part-3">Part 3</a>. Check out our MVVM architecture schema from that post to remember where it goes.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/qlI48NPPMqMbOeV47Cpkxop4nhW8RhgfTtjO" alt="Image" width="800" height="640" loading="lazy"></p>
<p>As you see in the picture, Repository is a separate layer for the data. It’s our single source of contact for getting or sending data. When we use Repository, we are following the separation of concerns principle. We can have different data sources (like in our case persistent data from an SQLite database and data from web services), but Repository is always going to be single source of truth for all app data.</p>
<p>Instead of communicating with our Retrofit implementation directly, we are going to use Repository for that. For each kind of entity, we are going to have a separate Repository.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * The class for managing multiple data sources.
 */</span>
<span class="hljs-meta">@Singleton</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CryptocurrencyRepository</span> <span class="hljs-meta">@Inject</span> <span class="hljs-keyword">constructor</span></span>(
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> context: Context,
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> appExecutors: AppExecutors,
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> myCryptocurrencyDao: MyCryptocurrencyDao,
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> cryptocurrencyDao: CryptocurrencyDao,
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> api: ApiService,
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> sharedPreferences: SharedPreferences
) {

    <span class="hljs-comment">// Just a simple helper variable to store selected fiat currency code during app lifecycle.</span>
    <span class="hljs-comment">// It is needed for main screen currency spinner. We set it to be same as in shared preferences.</span>
    <span class="hljs-keyword">var</span> selectedFiatCurrencyCode: String = getCurrentFiatCurrencyCode()


    ...


    <span class="hljs-comment">// The Resource wrapping of LiveData is useful to update the UI based upon the state.</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getAllCryptocurrencyLiveDataResourceList</span><span class="hljs-params">(fiatCurrencyCode: <span class="hljs-type">String</span>, shouldFetch: <span class="hljs-type">Boolean</span> = <span class="hljs-literal">false</span>, callDelay: <span class="hljs-type">Long</span> = <span class="hljs-number">0</span>)</span></span>: LiveData&lt;Resource&lt;List&lt;Cryptocurrency&gt;&gt;&gt; {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">object</span> : NetworkBoundResource&lt;List&lt;Cryptocurrency&gt;, CoinMarketCap&lt;List&lt;CryptocurrencyLatest&gt;&gt;&gt;(appExecutors) {

            <span class="hljs-comment">// Here we save the data fetched from web-service.</span>
            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">saveCallResult</span><span class="hljs-params">(item: <span class="hljs-type">CoinMarketCap</span>&lt;<span class="hljs-type">List</span>&lt;<span class="hljs-type">CryptocurrencyLatest</span>&gt;&gt;)</span></span> {

                <span class="hljs-keyword">val</span> list = getCryptocurrencyListFromResponse(fiatCurrencyCode, item.<span class="hljs-keyword">data</span>, item.status?.timestamp)

                cryptocurrencyDao.reloadCryptocurrencyList(list)
                myCryptocurrencyDao.reloadMyCryptocurrencyList(list)
            }

            <span class="hljs-comment">// Returns boolean indicating if to fetch data from web or not, true means fetch the data from web.</span>
            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">shouldFetch</span><span class="hljs-params">(<span class="hljs-keyword">data</span>: <span class="hljs-type">List</span>&lt;<span class="hljs-type">Cryptocurrency</span>&gt;?)</span></span>: <span class="hljs-built_in">Boolean</span> {
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">data</span> == <span class="hljs-literal">null</span> || shouldFetch
            }

            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">fetchDelayMillis</span><span class="hljs-params">()</span></span>: <span class="hljs-built_in">Long</span> {
                <span class="hljs-keyword">return</span> callDelay
            }

            <span class="hljs-comment">// Contains the logic to get data from the Room database.</span>
            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">loadFromDb</span><span class="hljs-params">()</span></span>: LiveData&lt;List&lt;Cryptocurrency&gt;&gt; {

                <span class="hljs-keyword">return</span> Transformations.switchMap(cryptocurrencyDao.getAllCryptocurrencyLiveDataList()) { <span class="hljs-keyword">data</span> -&gt;
                    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">data</span>.isEmpty()) {
                        AbsentLiveData.create()
                    } <span class="hljs-keyword">else</span> {
                        cryptocurrencyDao.getAllCryptocurrencyLiveDataList()
                    }
                }
            }

            <span class="hljs-comment">// Contains the logic to get data from web-service using Retrofit.</span>
            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createCall</span><span class="hljs-params">()</span></span>: LiveData&lt;ApiResponse&lt;CoinMarketCap&lt;List&lt;CryptocurrencyLatest&gt;&gt;&gt;&gt; = api.getAllCryptocurrencies(fiatCurrencyCode)

        }.asLiveData()
    }


    ...


    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getCurrentFiatCurrencyCode</span><span class="hljs-params">()</span></span>: String {
        <span class="hljs-keyword">return</span> sharedPreferences.getString(context.resources.getString(R.string.pref_fiat_currency_key), context.resources.getString(R.string.pref_default_fiat_currency_value))
                ?: context.resources.getString(R.string.pref_default_fiat_currency_value)
    }


    ...


    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getCryptocurrencyListFromResponse</span><span class="hljs-params">(fiatCurrencyCode: <span class="hljs-type">String</span>, responseList: <span class="hljs-type">List</span>&lt;<span class="hljs-type">CryptocurrencyLatest</span>&gt;?, timestamp: <span class="hljs-type">Date</span>?)</span></span>: ArrayList&lt;Cryptocurrency&gt; {

        <span class="hljs-keyword">val</span> cryptocurrencyList: MutableList&lt;Cryptocurrency&gt; = ArrayList()

        responseList?.forEach {
            <span class="hljs-keyword">val</span> cryptocurrency = Cryptocurrency(it.id, it.name, it.cmcRank.toShort(),
                    it.symbol, fiatCurrencyCode, it.quote.currency.price,
                    it.quote.currency.percentChange1h,
                    it.quote.currency.percentChange7d, it.quote.currency.percentChange24h, timestamp)
            cryptocurrencyList.add(cryptocurrency)
        }

        <span class="hljs-keyword">return</span> cryptocurrencyList <span class="hljs-keyword">as</span> ArrayList&lt;Cryptocurrency&gt;
    }

}
</code></pre>
<p>As you notice in the <code>CryptocurrencyRepository</code> class code, I am using the <code>NetworkBoundResource</code> abstract class. What is it and why do we need it?</p>
<p><code>NetworkBoundResource</code> is a small but very important helper class that will allow us to maintain a synchronization between the local database and the web service. Our goal is to build a modern application that will work smoothly even when our device is offline. Also with the help of this class we will be able to present different network states like errors or loading for the user visually.</p>
<p><code>NetworkBoundResource</code> starts by observing the database for the resource. When the entry is loaded from the database for the first time, it checks whether the result is good enough to be dispatched or if it should be re-fetched from the network. Note that both of these situations can happen at the same time, given that you probably want to show cached data while updating it from the network.</p>
<p>If the network call completes successfully, it saves the response into the database and re-initializes the stream. If the network request fails, the <code>NetworkBoundResource</code> dispatches a failure directly.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * A generic class that can provide a resource backed by both the sqlite database and the network.
 *
 *
 * You can read more about it in the [Architecture
 * Guide](https://developer.android.com/arch).
 * <span class="hljs-doctag">@param</span> &lt;ResultType&gt; - Type for the Resource data.
 * <span class="hljs-doctag">@param</span> &lt;RequestType&gt; - Type for the API response.
&lt;/RequestType&gt;&lt;/ResultType&gt; */</span>

<span class="hljs-comment">// It defines two type parameters, ResultType and RequestType,</span>
<span class="hljs-comment">// because the data type returned from the API might not match the data type used locally.</span>
<span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NetworkBoundResource</span>&lt;<span class="hljs-type">ResultType, RequestType</span>&gt;</span>
<span class="hljs-meta">@MainThread</span> <span class="hljs-keyword">constructor</span>(<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> appExecutors: AppExecutors) {

    <span class="hljs-comment">// The final result LiveData.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> result = MediatorLiveData&lt;Resource&lt;ResultType&gt;&gt;()

    <span class="hljs-keyword">init</span> {
        <span class="hljs-comment">// Send loading state to UI.</span>
        result.value = Resource.loading(<span class="hljs-literal">null</span>)
        <span class="hljs-meta">@Suppress(<span class="hljs-meta-string">"LeakingThis"</span>)</span>
        <span class="hljs-keyword">val</span> dbSource = loadFromDb()
        result.addSource(dbSource) { <span class="hljs-keyword">data</span> -&gt;
            result.removeSource(dbSource)
            <span class="hljs-keyword">if</span> (shouldFetch(<span class="hljs-keyword">data</span>)) {
                fetchFromNetwork(dbSource)
            } <span class="hljs-keyword">else</span> {
                result.addSource(dbSource) { newData -&gt;
                    setValue(Resource.successDb(newData))
                }
            }
        }
    }

    <span class="hljs-meta">@MainThread</span>
    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">setValue</span><span class="hljs-params">(newValue: <span class="hljs-type">Resource</span>&lt;<span class="hljs-type">ResultType</span>&gt;)</span></span> {
        <span class="hljs-keyword">if</span> (result.value != newValue) {
            result.value = newValue
        }
    }

    <span class="hljs-comment">// Fetch the data from network and persist into DB and then send it back to UI.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">fetchFromNetwork</span><span class="hljs-params">(dbSource: <span class="hljs-type">LiveData</span>&lt;<span class="hljs-type">ResultType</span>&gt;)</span></span> {
        <span class="hljs-keyword">val</span> apiResponse = createCall()
        <span class="hljs-comment">// We re-attach dbSource as a new source, it will dispatch its latest value quickly.</span>
        result.addSource(dbSource) { newData -&gt;
            setValue(Resource.loading(newData))
        }

        <span class="hljs-comment">// Create inner function as we want to delay it.</span>
        <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">fetch</span><span class="hljs-params">()</span></span> {
            result.addSource(apiResponse) { response -&gt;
                result.removeSource(apiResponse)
                result.removeSource(dbSource)
                <span class="hljs-keyword">when</span> (response) {
                    <span class="hljs-keyword">is</span> ApiSuccessResponse -&gt; {
                        appExecutors.diskIO().execute {
                            saveCallResult(processResponse(response))
                            appExecutors.mainThread().execute {
                                <span class="hljs-comment">// We specially request a new live data,</span>
                                <span class="hljs-comment">// otherwise we will get immediately last cached value,</span>
                                <span class="hljs-comment">// which may not be updated with latest results received from network.</span>
                                result.addSource(loadFromDb()) { newData -&gt;
                                    setValue(Resource.successNetwork(newData))
                                }
                            }
                        }
                    }
                    <span class="hljs-keyword">is</span> ApiEmptyResponse -&gt; {
                        appExecutors.mainThread().execute {
                            <span class="hljs-comment">// reload from disk whatever we had</span>
                            result.addSource(loadFromDb()) { newData -&gt;
                                setValue(Resource.successDb(newData))
                            }
                        }
                    }
                    <span class="hljs-keyword">is</span> ApiErrorResponse -&gt; {
                        onFetchFailed()
                        result.addSource(dbSource) { newData -&gt;
                            setValue(Resource.error(response.errorMessage, newData))
                        }
                    }
                }
            }
        }

        <span class="hljs-comment">// Add delay before call if needed.</span>
        <span class="hljs-keyword">val</span> delay = fetchDelayMillis()
        <span class="hljs-keyword">if</span> (delay &gt; <span class="hljs-number">0</span>) {
            Handler().postDelayed({ fetch() }, delay)
        } <span class="hljs-keyword">else</span> fetch()

    }

    <span class="hljs-comment">// Called when the fetch fails. The child class may want to reset components</span>
    <span class="hljs-comment">// like rate limiter.</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">open</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onFetchFailed</span><span class="hljs-params">()</span></span> {}

    <span class="hljs-comment">// Returns a LiveData object that represents the resource that's implemented</span>
    <span class="hljs-comment">// in the base class.</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">asLiveData</span><span class="hljs-params">()</span></span> = result <span class="hljs-keyword">as</span> LiveData&lt;Resource&lt;ResultType&gt;&gt;

    <span class="hljs-meta">@WorkerThread</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">open</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">processResponse</span><span class="hljs-params">(response: <span class="hljs-type">ApiSuccessResponse</span>&lt;<span class="hljs-type">RequestType</span>&gt;)</span></span> = response.body

    <span class="hljs-comment">// Called to save the result of the API response into the database.</span>
    <span class="hljs-meta">@WorkerThread</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">saveCallResult</span><span class="hljs-params">(item: <span class="hljs-type">RequestType</span>)</span></span>

    <span class="hljs-comment">// Called with the data in the database to decide whether to fetch</span>
    <span class="hljs-comment">// potentially updated data from the network.</span>
    <span class="hljs-meta">@MainThread</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">shouldFetch</span><span class="hljs-params">(<span class="hljs-keyword">data</span>: <span class="hljs-type">ResultType</span>?)</span></span>: <span class="hljs-built_in">Boolean</span>

    <span class="hljs-comment">// Make a call to the server after some delay for better user experience.</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">open</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">fetchDelayMillis</span><span class="hljs-params">()</span></span>: <span class="hljs-built_in">Long</span> = <span class="hljs-number">0</span>

    <span class="hljs-comment">// Called to get the cached data from the database.</span>
    <span class="hljs-meta">@MainThread</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">loadFromDb</span><span class="hljs-params">()</span></span>: LiveData&lt;ResultType&gt;

    <span class="hljs-comment">// Called to create the API call.</span>
    <span class="hljs-meta">@MainThread</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createCall</span><span class="hljs-params">()</span></span>: LiveData&lt;ApiResponse&lt;RequestType&gt;&gt;
}
</code></pre>
<p>Under the hood, the <code>NetworkBoundResource</code> class is made by using MediatorLiveData and its ability to observe multiple LiveData sources at once. Here we have two LiveData sources: the database and the network call response. Both of those LiveData are wrapped into one MediatorLiveData which is exposed by <code>NetworkBoundResource</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/qbNZeVc-RHe54xa9LSZMOfzmmrBA9rXzhGYo" alt="Image" width="534" height="465" loading="lazy">
<em>NetworkBoundResource</em></p>
<p>Let’s take a closer look how the <code>NetworkBoundResource</code> will work in our app. Imagine the user will launch the app and click on a floating action button on the bottom right corner. The app will launch the add crypto coins screen. Now we can analyze <code>NetworkBoundResource</code>'s usage inside it.</p>
<p>If the app is freshly installed and it is its first launch, then there will not be any data stored inside the local database. Because there is no data to show, a loading progress bar UI will be shown. Meanwhile the app is going to make a request call to the server via a web service to get all the cryptocurrencies list.</p>
<p>If the response is unsuccessful then the error message UI will be shown with the ability to retry a call by pressing a button. When a request call is successful at last, then the response data will be saved to a local SQLite database.</p>
<p>If we come back to the same screen the next time, the app will load data from the database instead of making a call to the internet again. But the user can ask for a new data update by implementing pull-to-refresh functionality. Old data information will be shown whilst the network call is happening. All this is done with the help of <code>NetworkBoundResource</code>.</p>
<p>Another class used in our Repository and <code>LiveDataCallAdapter</code> where all the "magic" happens is <code>ApiResponse</code>. Actually <code>ApiResponse</code> is just a simple common wrapper around the <code>Retrofit2.Response</code> class that converts each response to an instance of LiveData.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * Common class used by API responses. ApiResponse is a simple wrapper around the Retrofit2.Call
 * class that convert responses to instances of LiveData.
 * <span class="hljs-doctag">@param</span> &lt;CoinMarketCapType&gt; the type of the response object
&lt;/T&gt; */</span>
<span class="hljs-meta">@Suppress(<span class="hljs-meta-string">"unused"</span>)</span> <span class="hljs-comment">// T is used in extending classes</span>
<span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiResponse</span>&lt;<span class="hljs-type">CoinMarketCapType</span>&gt; </span>{
    <span class="hljs-keyword">companion</span> <span class="hljs-keyword">object</span> {
        <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-type">&lt;CoinMarketCapType&gt;</span> <span class="hljs-title">create</span><span class="hljs-params">(error: <span class="hljs-type">Throwable</span>)</span></span>: ApiErrorResponse&lt;CoinMarketCapType&gt; {
            <span class="hljs-keyword">return</span> ApiErrorResponse(error.message ?: <span class="hljs-string">"Unknown error."</span>)
        }

        <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-type">&lt;CoinMarketCapType&gt;</span> <span class="hljs-title">create</span><span class="hljs-params">(response: <span class="hljs-type">Response</span>&lt;<span class="hljs-type">CoinMarketCapType</span>&gt;)</span></span>: ApiResponse&lt;CoinMarketCapType&gt; {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">if</span> (response.isSuccessful) {
                <span class="hljs-keyword">val</span> body = response.body()
                <span class="hljs-keyword">if</span> (body == <span class="hljs-literal">null</span> || response.code() == <span class="hljs-number">204</span>) {
                    ApiEmptyResponse()
                } <span class="hljs-keyword">else</span> {
                    ApiSuccessResponse(body = body)
                }
            } <span class="hljs-keyword">else</span> {

                <span class="hljs-comment">// Convert error response to JSON object.</span>
                <span class="hljs-keyword">val</span> gson = Gson()
                <span class="hljs-keyword">val</span> type = <span class="hljs-keyword">object</span> : TypeToken&lt;CoinMarketCap&lt;CoinMarketCapType&gt;&gt;() {}.type
                <span class="hljs-keyword">val</span> errorResponse: CoinMarketCap&lt;CoinMarketCapType&gt; = gson.fromJson(response.errorBody()!!.charStream(), type)

                <span class="hljs-keyword">val</span> msg = errorResponse.status?.errorMessage ?: errorResponse.message
                <span class="hljs-keyword">val</span> errorMsg = <span class="hljs-keyword">if</span> (msg.isNullOrEmpty()) {
                    response.message()
                } <span class="hljs-keyword">else</span> {
                    msg
                }
                ApiErrorResponse(errorMsg ?: <span class="hljs-string">"Unknown error."</span>)
            }
        }
    }
}

<span class="hljs-comment">/**
 * Separate class for HTTP 204 resposes so that we can make ApiSuccessResponse's body non-null.
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiEmptyResponse</span>&lt;<span class="hljs-type">CoinMarketCapType</span>&gt; : <span class="hljs-type">ApiResponse</span>&lt;<span class="hljs-type">CoinMarketCapType</span>&gt;</span>()

<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiSuccessResponse</span>&lt;<span class="hljs-type">CoinMarketCapType</span>&gt;</span>(<span class="hljs-keyword">val</span> body: CoinMarketCapType) : ApiResponse&lt;CoinMarketCapType&gt;()

<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiErrorResponse</span>&lt;<span class="hljs-type">CoinMarketCapType</span>&gt;</span>(<span class="hljs-keyword">val</span> errorMessage: String) : ApiResponse&lt;CoinMarketCapType&gt;()
</code></pre>
<p>Inside this wrapper class, if our response has an error, we use the Gson library to convert the error to a JSON object. However, if the response was successful, then the Gson converter for JSON to POJO object mapping is used. We already added it when creating the retrofit builder instance with <code>GsonConverterFactory</code> inside the Dagger <code>AppModule</code> function <code>provideApiService</code>.</p>
<h3 id="heading-glide-for-image-loading">Glide for image loading</h3>
<p><a target="_blank" href="https://github.com/huyn/glide">What is Glide</a>? From the docs:</p>
<blockquote>
<p>Glide is a fast and efficient open source media management and image loading framework for Android that wraps media decoding, memory and disk caching, and resource pooling into a simple and easy to use interface.</p>
<p>Glide’s primary focus is on making scrolling any kind of a list of images as smooth and fast as possible, but it is also effective for almost any case where you need to fetch, resize, and display a remote image.</p>
</blockquote>
<p>Sounds like a complicated library which offers many useful features that you would not want to develop all by yourself. In My Crypto Coins app, we have several list screens where we need to show multiple cryptocurrency logos — pictures taken from the internet all at once — and still ensure a smooth scrolling experience for the user. So this library fits our needs perfectly. Also this library is very popular among Android developers.</p>
<p>Steps to setup Glide on My Crypto Coins app project:</p>
<h4 id="heading-declare-dependencies"><strong>Declare dependencies</strong></h4>
<p>Get the latest <a target="_blank" href="https://bumptech.github.io/glide">Glide version</a>. Again versions is a separate file <code>versions.gradle</code> for the project.</p>
<pre><code class="lang-gradle">// Glide
implementation "com.github.bumptech.glide:glide:$versions.glide"
kapt "com.github.bumptech.glide:compiler:$versions.glide"
// Glide's OkHttp3 integration.
implementation "com.github.bumptech.glide:okhttp3-integration:$versions.glide"+"@aar"
</code></pre>
<p>Because we want to use the networking library OkHttp in our project for all network operations, we need to include the specific Glide integration for it instead of the default one. Also since Glide is going to perform a network request to load images via the internet, we need to include the permission <code>INTERNET</code> in our <code>AndroidManifest.xml</code> file — but we already did that with the Retrofit setup.</p>
<h4 id="heading-create-appglidemodule"><strong>Create AppGlideModule</strong></h4>
<p>Glide v4, which we will be using, offers a generated API for Applications. It will use an annotation processor to generate an API that allows applications to extend Glide’s API and include components provided by integration libraries. For any app to access the generated Glide API we need to include an appropriately annotated <code>AppGlideModule</code> implementation. There can be only a single implementation of the generated API and only one <code>AppGlideModule</code> per application.</p>
<p>Let’s create a class extending <code>AppGlideModule</code> somewhere in your app project:</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * Glide v4 uses an annotation processor to generate an API that allows applications to access all
 * options in RequestBuilder, RequestOptions and any included integration libraries in a single
 * fluent API.
 *
 * The generated API serves two purposes:
 * Integration libraries can extend Glide’s API with custom options.
 * Applications can extend Glide’s API by adding methods that bundle commonly used options.
 *
 * Although both of these tasks can be accomplished by hand by writing custom subclasses of
 * RequestOptions, doing so is challenging and produces a less fluent API.
 */</span>
<span class="hljs-meta">@GlideModule</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppGlideModule</span> : <span class="hljs-type">AppGlideModule</span></span>()
</code></pre>
<p>Even if our application is not changing any additional settings or implementing any methods in <code>AppGlideModule</code>, we still need to have its implementation to use Glide. You're not required to implement any of the methods in <code>AppGlideModule</code> for the API to be generated. You can leave the class blank as long as it extends <code>AppGlideModule</code> and is annotated with <code>@GlideModule</code>.</p>
<h4 id="heading-use-glide-generated-api"><strong>Use Glide-generated API</strong></h4>
<p>When using <code>AppGlideModule</code>, applications can use the API by starting all loads with <code>GlideApp.with()</code>. This is the code that shows how I have used Glide to load and show cryptocurrency logos in the add crypto coins screen all cryptocurrencies list.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AddSearchListAdapter</span></span>(<span class="hljs-keyword">val</span> context: Context, <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> cryptocurrencyClickCallback: ((Cryptocurrency) -&gt; <span class="hljs-built_in">Unit</span>)?) : BaseAdapter() {

    ...

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getView</span><span class="hljs-params">(position: <span class="hljs-type">Int</span>, convertView: <span class="hljs-type">View</span>?, parent: <span class="hljs-type">ViewGroup</span>?)</span></span>: View {
        ...

        <span class="hljs-keyword">val</span> itemBinding: ActivityAddSearchListItemBinding

        ...

        <span class="hljs-comment">// We make an Uri of image that we need to load. Every image unique name is its id.</span>
        <span class="hljs-keyword">val</span> imageUri = Uri.parse(CRYPTOCURRENCY_IMAGE_URL).buildUpon()
                .appendPath(CRYPTOCURRENCY_IMAGE_SIZE_PX)
                .appendPath(cryptocurrency.id.toString() + CRYPTOCURRENCY_IMAGE_FILE)
                .build()

        <span class="hljs-comment">// Glide generated API from AppGlideModule.</span>
        GlideApp
                <span class="hljs-comment">// We need to provide context to make a call.</span>
                .with(itemBinding.root)
                <span class="hljs-comment">// Here you specify which image should be loaded by providing Uri.</span>
                .load(imageUri)
                <span class="hljs-comment">// The way you combine and execute multiple transformations.</span>
                <span class="hljs-comment">// WhiteBackground is our own implemented custom transformation.</span>
                <span class="hljs-comment">// CircleCrop is default transformation that Glide ships with.</span>
                .transform(MultiTransformation(WhiteBackground(), CircleCrop()))
                <span class="hljs-comment">// The target ImageView your image is supposed to get displayed in.</span>
                .into(itemBinding.itemImageIcon.imageview_front)

        ...

        <span class="hljs-keyword">return</span> itemBinding.root
    }

    ...

}
</code></pre>
<p>As you see, you can start using Glide with just few lines of code and let it do all the hard work for you. It is pretty straightforward.</p>
<h3 id="heading-kotlin-coroutines">Kotlin Coroutines</h3>
<p>While building this app, we are going to face situations when we will run time consuming tasks such as writing data to a database or reading from it, fetching data from the network and other. All these common tasks take longer to complete than allowed by the Android framework’s main thread.</p>
<p>The main thread is a single thread that handles all updates to the UI. Developers are required not to block it to avoid the app freezing or even crashing with an Application Not Responding dialog. Kotlin coroutines is going to solve this problem for us by introducing main thread safety. It is the last missing piece that we want to add for My Crypto Coins app.</p>
<p>Coroutines are a Kotlin feature that convert async callbacks for long-running tasks, such as database or network access, into sequential code. With coroutines, you can write asynchronous code, which was traditionally written using the Callback pattern, using a synchronous style. The return value of a function will provide the result of the asynchronous call. Code written sequentially is typically easier to read, and can even use language features such as exceptions.</p>
<p>So we are going to use coroutines everywhere in this app where we need to wait until a result is available from a long-running task and than continue execution. Let’s see one exact implementation for our ViewModel where we will retry getting the latest data from the server for our cryptocurrencies presented on the main screen.</p>
<p>First add coroutines to the project:</p>
<pre><code class="lang-gradle">// Coroutines support libraries for Kotlin.

// Dependencies for coroutines.
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$versions.coroutines"

// Dependency is for the special UI context that can be passed to coroutine builders that use
// the main thread dispatcher to dispatch events on the main thread.
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$versions.coroutines"
</code></pre>
<p>Then we will create abstract class which will become the base class to be used for any ViewModel that needs to have common functionality like coroutines in our case:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BaseViewModel</span> : <span class="hljs-type">ViewModel</span></span>() {

    <span class="hljs-comment">// In Kotlin, all coroutines run inside a CoroutineScope.</span>
    <span class="hljs-comment">// A scope controls the lifetime of coroutines through its job.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> viewModelJob = Job()
    <span class="hljs-comment">// Since uiScope has a default dispatcher of Dispatchers.Main, this coroutine will be launched</span>
    <span class="hljs-comment">// in the main thread.</span>
    <span class="hljs-keyword">val</span> uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)


    <span class="hljs-comment">// onCleared is called when the ViewModel is no longer used and will be destroyed.</span>
    <span class="hljs-comment">// This typically happens when the user navigates away from the Activity or Fragment that was</span>
    <span class="hljs-comment">// using the ViewModel.</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCleared</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">super</span>.onCleared()
        <span class="hljs-comment">// When you cancel the job of a scope, it cancels all coroutines started in that scope.</span>
        <span class="hljs-comment">// It's important to cancel any coroutines that are no longer required to avoid unnecessary</span>
        <span class="hljs-comment">// work and memory leaks.</span>
        viewModelJob.cancel()
    }
}
</code></pre>
<p>Here we create specific coroutine scope, which will control the lifetime of coroutines through its job. As you see, scope allows you to specify a default dispatcher that controls which thread runs a coroutine. When the ViewModel is no longer used, we cancel <code>viewModelJob</code> and with that every coroutine started by <code>uiScope</code> will be cancelled as well.</p>
<p>Finally, implement the retry functionality:</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way.
 * The ViewModel class allows data to survive configuration changes such as screen rotations.
 */</span>

<span class="hljs-comment">// ViewModel will require a CryptocurrencyRepository so we add @Inject code into ViewModel constructor.</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainViewModel</span> <span class="hljs-meta">@Inject</span> <span class="hljs-keyword">constructor</span></span>(<span class="hljs-keyword">val</span> context: Context, <span class="hljs-keyword">val</span> cryptocurrencyRepository: CryptocurrencyRepository) : BaseViewModel() {

    ...

    <span class="hljs-keyword">val</span> mediatorLiveDataMyCryptocurrencyResourceList = MediatorLiveData&lt;Resource&lt;List&lt;MyCryptocurrency&gt;&gt;&gt;()
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> liveDataMyCryptocurrencyResourceList: LiveData&lt;Resource&lt;List&lt;MyCryptocurrency&gt;&gt;&gt;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> liveDataMyCryptocurrencyList: LiveData&lt;List&lt;MyCryptocurrency&gt;&gt;

    ...

    <span class="hljs-comment">// This is additional helper variable to deal correctly with currency spinner and preference.</span>
    <span class="hljs-comment">// It is kept inside viewmodel not to be lost because of fragment/activity recreation.</span>
    <span class="hljs-keyword">var</span> newSelectedFiatCurrencyCode: String? = <span class="hljs-literal">null</span>

    <span class="hljs-comment">// Helper variable to store state of swipe refresh layout.</span>
    <span class="hljs-keyword">var</span> isSwipeRefreshing: <span class="hljs-built_in">Boolean</span> = <span class="hljs-literal">false</span>


    <span class="hljs-keyword">init</span> {
        ...

        <span class="hljs-comment">// Set a resource value for a list of cryptocurrencies that user owns.</span>
        liveDataMyCryptocurrencyResourceList = cryptocurrencyRepository.getMyCryptocurrencyLiveDataResourceList(cryptocurrencyRepository.getCurrentFiatCurrencyCode())


        <span class="hljs-comment">// Declare additional variable to be able to reload data on demand.</span>
        mediatorLiveDataMyCryptocurrencyResourceList.addSource(liveDataMyCryptocurrencyResourceList) {
            mediatorLiveDataMyCryptocurrencyResourceList.value = it
        }

        ...
    }

   ...

    <span class="hljs-comment">/**
     * On retry we need to run sequential code. First we need to get owned crypto coins ids from
     * local database, wait for response and only after it use these ids to make a call with
     * retrofit to get updated owned crypto values. This can be done using Kotlin Coroutines.
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">retry</span><span class="hljs-params">(newFiatCurrencyCode: <span class="hljs-type">String</span>? = <span class="hljs-literal">null</span>)</span></span> {

        <span class="hljs-comment">// Here we store new selected currency as additional variable or reset it.</span>
        <span class="hljs-comment">// Later if call to server is unsuccessful we will reuse it for retry functionality.</span>
        newSelectedFiatCurrencyCode = newFiatCurrencyCode

        <span class="hljs-comment">// Launch a coroutine in uiScope.</span>
        uiScope.launch {
            <span class="hljs-comment">// Make a call to the server after some delay for better user experience.</span>
            updateMyCryptocurrencyList(newFiatCurrencyCode, SERVER_CALL_DELAY_MILLISECONDS)
        }
    }

    <span class="hljs-comment">// Refresh the data from local database.</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">refreshMyCryptocurrencyResourceList</span><span class="hljs-params">()</span></span> {
        refreshMyCryptocurrencyResourceList(cryptocurrencyRepository.getMyCryptocurrencyLiveDataResourceList(cryptocurrencyRepository.getCurrentFiatCurrencyCode()))
    }

    <span class="hljs-comment">// To implement a manual refresh without modifying your existing LiveData logic.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">refreshMyCryptocurrencyResourceList</span><span class="hljs-params">(liveData: <span class="hljs-type">LiveData</span>&lt;<span class="hljs-type">Resource</span>&lt;<span class="hljs-type">List</span>&lt;<span class="hljs-type">MyCryptocurrency</span>&gt;&gt;&gt;)</span></span> {
        mediatorLiveDataMyCryptocurrencyResourceList.removeSource(liveDataMyCryptocurrencyResourceList)
        liveDataMyCryptocurrencyResourceList = liveData
        mediatorLiveDataMyCryptocurrencyResourceList.addSource(liveDataMyCryptocurrencyResourceList)
        { mediatorLiveDataMyCryptocurrencyResourceList.value = it }
    }

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">updateMyCryptocurrencyList</span><span class="hljs-params">(newFiatCurrencyCode: <span class="hljs-type">String</span>? = <span class="hljs-literal">null</span>, callDelay: <span class="hljs-type">Long</span> = <span class="hljs-number">0</span>)</span></span> {

        <span class="hljs-keyword">val</span> fiatCurrencyCode: String = newFiatCurrencyCode
                ?: cryptocurrencyRepository.getCurrentFiatCurrencyCode()

        isSwipeRefreshing = <span class="hljs-literal">true</span>

        <span class="hljs-comment">// The function withContext is a suspend function. The withContext immediately shifts</span>
        <span class="hljs-comment">// execution of the block into different thread inside the block, and back when it</span>
        <span class="hljs-comment">// completes. IO dispatcher is suitable for execution the network requests in IO thread.</span>
        <span class="hljs-keyword">val</span> myCryptocurrencyIds = withContext(Dispatchers.IO) {
            <span class="hljs-comment">// Suspend until getMyCryptocurrencyIds() returns a result.</span>
            cryptocurrencyRepository.getMyCryptocurrencyIds()
        }

        <span class="hljs-comment">// Here we come back to main worker thread. As soon as myCryptocurrencyIds has a result</span>
        <span class="hljs-comment">// and main looper is available, coroutine resumes on main thread, and</span>
        <span class="hljs-comment">// [getMyCryptocurrencyLiveDataResourceList] is called.</span>
        <span class="hljs-comment">// We wait for background operations to complete, without blocking the original thread.</span>
        refreshMyCryptocurrencyResourceList(
                cryptocurrencyRepository.getMyCryptocurrencyLiveDataResourceList
                (fiatCurrencyCode, <span class="hljs-literal">true</span>, myCryptocurrencyIds, callDelay))
    }

    ...
}
</code></pre>
<p>Here we call a function marked with a special Kotlin keyword <code>suspend</code> for coroutines. This means that the function suspends execution until the result is ready, then it resumes where it left off with the result. While it is suspended waiting for a result, it unblocks the thread that it is running on.</p>
<p>Also, in one suspend function we can call another suspend function. As you see we do that by calling new suspend function marked <code>withContext</code> that is executed on different thread.</p>
<p>The idea of all this code is that we can combine multiple calls to form nice-looking sequential code. First we request to get the ids of the cryptocurrencies we own from the local database and wait for the response. Only after we get it do we use the response ids to make a new call with Retrofit to get those updated cryptocurrency values. That is our retry functionality.</p>
<h3 id="heading-we-made-it-final-thoughts-repository-app-amp-presentation">We made it! Final thoughts, repository, app &amp; presentation</h3>
<p>Congratulations, I am happy if you managed to reach to the end. All the most significant points for creating this app have been covered. There was plenty of new stuff done in this part and a lot of that is not covered by this article, but I commented my code everywhere very well so you should not get lost in it. Check out final code for this part 5 here on GitHub:</p>
<p><a target="_blank" href="https://github.com/baruckis/Kriptofolio/tree/Part-5">View Source On GitHub</a>.</p>
<p>The biggest challenge for me personally was not to learn new technologies, not to develop the app, but to write all these articles. Actually I am very happy with myself that I completed this challenge. Learning and developing is easy compared to teaching others, but that is where you can understand the topic even better. My advice if you are looking for the best way to learn new things is to start creating something yourself immediately. I promise you will learn a lot and quickly.</p>
<p>All these articles are based on version 1.0.0 of “Kriptofolio” (previously “My Crypto Coins”) app which you can download as a separate APK file <a target="_blank" href="https://github.com/baruckis/Kriptofolio/releases">here</a>. But I will be very happy if you install and rate the latest app version from the store directly:</p>
<h4 id="heading-get-it-on-google-playhttpsplaygooglecomstoreappsdetailsidcombaruckiskriptofolio"><a target="_blank" href="https://play.google.com/store/apps/details?id=com.baruckis.kriptofolio">Get It On Google Play</a></h4>
<p>Also please feel free to visit this simple presentation website that I made for this project:</p>
<h4 id="heading-kriptofolioapphttpskriptofolioapp"><a target="_blank" href="https://kriptofolio.app">Kriptofolio.app</a></h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/xeMQGQ5yGL06eNvYuuDFjGw0cmNBU85dBjXE" alt="Image" width="800" height="710" loading="lazy"></p>
<hr>
<p><strong><em>Ačiū! Thanks for reading! I originally published this post for my personal blog <a target="_blank" href="https://www.baruckis.com/android/kriptofolio-app-series-part-5/">www.baruckis.com</a> on May 11, 2019.</em></strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to build a cryptobot in Python and connect it to Facebook messenger ]]>
                </title>
                <description>
                    <![CDATA[ By Paul Pinard Meet Sato the Cryptobot, who is able to fetch any cryptocurrency price from an external API! Chatbots have an incredible potential. Yet, for bots to be efficient, they must integrate and exchange data with existing services and proces... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-cryptobot-in-python-and-connect-it-to-facebook-messenger-4bba14107fcc/</link>
                <guid isPermaLink="false">66c34f5ba7aea9fc97bdfb7e</guid>
                
                    <category>
                        <![CDATA[ #chatbots ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 30 Apr 2019 17:03:57 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*bXgJOdnBncMGMKKJVPCbmw.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Paul Pinard</p>
<h4 id="heading-meet-sato-the-cryptobot-who-is-able-to-fetch-any-cryptocurrency-price-from-an-external-api">Meet Sato the Cryptobot, who is able to fetch any cryptocurrency price from an external API!</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/nkzd3jArmXtaw3vlJ2FJzSBC6ba6qnreD4nM" alt="Image" width="800" height="434" loading="lazy"></p>
<p>Chatbots have an incredible potential. Yet, for bots to be efficient, they must integrate and exchange data with existing services and processes.</p>
<p><strong>The ability to fetch data from external API allows for more complex use case that a simple Q&amp;A logic</strong>. Moreover, this ability combined with NLP offers even more opportunities.</p>
<p>For instance, Sato — the cryptobot we’ll be building today — is able to recognize all cryptocurrencies, even those not even listed yet. I won’t have to do anything for him to be able to process queries on crypto appearing even years from now, because Sato, deep-down, understood what a cryptocurrency symbol is (after being fed with thousands of them).</p>
<h3 id="heading-what-are-we-building-today">What are we building today?</h3>
<p>By the end of this tutorial, we will have a bot able to fetch data from a third party API depending on what our users input, and reply to them with the value fetched. Here’s the end-result of what we’ll build today: a cryptobot aka a chatbot able to fetch any cryptocurrency price.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/mVEyhtJ375H0xIgX8Wiu6h2FgHfbnIKz5Rb6" alt="Image" width="711" height="979" loading="lazy">
<em>What you’ll have by the end of this tutorial</em></p>
<p>In a rush? Here is all you need to build your own:</p>
<ul>
<li>A chatbot created with <a target="_blank" href="https://medium.freecodecamp.org/how-to-build-your-first-chatbot-with-the-sap-conversational-ai-9a1a2bd44e3c">SAP Conversational AI</a>. Sign up <a target="_blank" href="https://cai.tools.sap/signup?utm_source=freecodecamp&amp;utm_medium=blog&amp;utm_campaign=LG2019">here</a>, it’s totally free!</li>
<li><a target="_blank" href="https://github.com/Ahirice/sato/">The GitHub repo</a></li>
</ul>
<p>Need to see it to believe it? That’s wise! Click <a target="_blank" href="https://www.messenger.com/login.php?next=https%3A%2F%2Fwww.messenger.com%2Ft%2Fsatofolio">here</a>!</p>
<p>Or if you would rather understand how it was made, go through with the tutorial.</p>
<h3 id="heading-1-build-the-base-of-your-chatbot-choose-your-path">1. Build the base of your chatbot: choose your path</h3>
<p>The goal today is to build bot able to recognize a question about pricing on any cryptocurrency. Let your imagination flow, <strong>it could be really anything there is involving data available on third party APIs</strong>.</p>
<p>Before we dive in the tutorial, let me give you some information on how Sato works.</p>
<h4 id="heading-meet-sato-the-cryptobot">Meet Sato, the cryptobot</h4>
<p>Sato is a bot made to answer basic questions about cryptocurrencies and fetch their prices. Here’s an overview of what he can do:</p>
<ol>
<li>Fetch cryptocurrencies prices (what we’ll build today): Sato recognizes cryptocurrencies symbol (“ETH”, “BTC”) and fetch their price on <a target="_blank" href="https://www.cryptocompare.com/api/">cryptocompare API</a> to finally return BTC and USD value to the user.</li>
<li>Answer the users’ questions about wallets — online wallets, exchange wallets, cold wallets and hardware wallets.</li>
<li>Address questions about private and public keys as well as the security of cryptocurrencies.</li>
<li>Briefly present the main cryptocurrencies, currently BTC, ETH, BCH and LTC.</li>
</ol>
<h4 id="heading-inside-sato">Inside Sato</h4>
<p>Today, we’ll focus on the skill fetching the crypto prices, as it requires an external API call. Essentially, Sato needs three things to be able to detect a question about crypto price and return the value asked:</p>
<p>Firstly, he needs an intent <a target="_blank" href="https://cai.tools.sap/ahirice/sato-cryptobot/train/crypto_price?utm_source=blog&amp;utm_campaign=sato">(@crypto_price</a>) with diverse expressions and cryptocurrencies mentioned, so he can efficiently recognize these questions. Here are some of the expressions used to define the @crypto_price intent:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/9xvqHOnxa19Q2lJZALPpNX3Drn9ji7GvnPsc" alt="Image" width="450" height="733" loading="lazy">
_A sample of the expressions used to define the @crypto<em>price intent</em></p>
<p>Secondly, for Sato to be able to recognize all cryptocurrencies, he’ll need the biggest list you can find. I found 1200+ on CoinMarketCap which is good enough to begin with. I created a gazette of the crypto names to improve its understanding.</p>
<p>Thirdly, we’ll need to build a skill which triggers when the @ask_price intent or #crypto_name entity is recognized:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ODAOHbkV4oNuDxMlCBybhtorXtXsrbPDBmdr" alt="Image" width="800" height="333" loading="lazy">
_Sato — Cryptobot / crypto<em>main skill triggers</em></p>
<p>You can also add #crypto_name as a requirements, to make sure no API called is fired without parameters:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/bpD4Pbv-Tuxr47GSwC2fqGyhMe-SqHG6uTC4" alt="Image" width="779" height="576" loading="lazy">
_Sato — Cryptobot / crypto<em>main skill requirements</em></p>
<p>This skill must also call your webhook that we’ll setup below:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/135D8rog-svOYx2Ypr0trbn0TtGLHM4T6n-w" alt="Image" width="800" height="291" loading="lazy">
_Sato — Cryptobot / crypto<em>main skill actions</em></p>
<p>Don’t forget to add a memory reset after the webhook trigger, it’s required to clean the memory after each answer.</p>
<p>Finally, we’ll test our bot straight in Messenger, so you’ll need to create a page and an app and connect it. Everything is documented in the <code>CONNECT</code> tab and in the <a target="_blank" href="https://cai.tools.sap/blog/build-your-first-bot-with-sap-conversational-ai/">getting started tutorial</a>.</p>
<p>To keep it concise<strong>, this tutorial will not detail the creation of a bot</strong>. We’ll start from a functioning bot already.</p>
<p>To meet me there, you have two options:</p>
<ul>
<li>Option A: build your own bot (who doesn’t have to be a cryptobot) by following the getting started tutorial and creating an <a target="_blank" href="https://cai.tools.sap/signup?utm_source=freecodecamp&amp;utm_medium=blog&amp;utm_campaign=LG2019">account on SAP Conversational AI</a>.</li>
<li>Option B: <a target="_blank" href="https://cai.tools.sap/ahirice/sato-cryptobot/train/intents">fork Sato</a> and start from here. That’s why SAP Conversational AI is a collaborative chatbot platform. It works pretty much like GitHub!</li>
</ul>
<p><img src="https://cdn-media-1.freecodecamp.org/images/QZmtXl1BvCSUOw71M02FiAvKyzYnU0tqrYuN" alt="Image" width="800" height="123" loading="lazy">
<em>Forking a bot on SAP Conversational AI</em></p>
<h3 id="heading-2-basic-server-code-and-requirements">2. Basic server code and requirements</h3>
<p>Since we want to interact with our bot, we’ll need a server to be able to receive the results of the NLP made by SAP Conversational AI and send our responses back.</p>
<p>On the <a target="_blank" href="https://cai.tools.sap/bot-builder">bot builder</a>, go to the <code>CODE</code> tab to find an example of base code required to start your API. We give examples in Node.JS, PHP, Python and Ruby. This tutorial will be Python only.</p>
<p>Here’s the base code for Python:</p>
<pre><code><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, request, jsonify <span class="hljs-keyword">import</span> json app = Flask(__name__) port = <span class="hljs-string">'5000'</span> @app.route(<span class="hljs-string">'/'</span>, methods=[<span class="hljs-string">'POST'</span>]) def index():   print(json.loads(request.get_data()))   <span class="hljs-keyword">return</span> jsonify(     status=<span class="hljs-number">200</span>,     replies=[{       <span class="hljs-string">'type'</span>: <span class="hljs-string">'text'</span>,       <span class="hljs-string">'content'</span>: <span class="hljs-string">'Roger that'</span>,     }]  )  @app.route(<span class="hljs-string">'/errors'</span>, methods=[<span class="hljs-string">'POST'</span>]) def errors():   print(json.loads(request.get_data()))   <span class="hljs-keyword">return</span> jsonify(status=<span class="hljs-number">200</span>)  app.run(port=port)
</code></pre><p>Take some time to look at the code to get a better understanding of what we’ll be doing: we’ll build on this code during this tutorial. You can save it in your favorite text editor for now.</p>
<h4 id="heading-requirements">Requirements</h4>
<p>As you can see, the server script uses the <a target="_blank" href="http://flask.pocoo.org/">Flask as a web framework</a>, so we’ll need it.</p>
<p>For the API call, we’ll also use <a target="_blank" href="http://docs.python-requests.org/en/master/">Requests</a>. Let’s go ahead and install both:</p>
<pre><code>pip install Flaskpip install requests
</code></pre><h3 id="heading-3-test-the-server-ngrok">3. Test the server: NGROK</h3>
<p>Now that we have the base server, let’s make it run and test it. It will allow us to be more incremental in the process so the debugging (if any) is simplified.</p>
<p>To expose our local server to the internet, we’ll need ngrok.</p>
<p>_Note: If you are using Windows like me, there is awesome package manager, <a target="_blank" href="https://chocolatey.org/">Chocolatey</a> which works pretty much like apt-get on UNIX. With it, you’ll be able to install ngrok in one line <code>choco install ngrok_portable</code>. Moreover, Chocolatey adds ngrok to your PATH, allowing you to start ngrok from any terminal simply by typing <code>ngrok</code>._</p>
<p>Now is the time to start our server and test it, this implies:</p>
<ol>
<li>Set a webhook trigger in your bot (detailed in step 1)</li>
<li>Run your python script</li>
<li>Expose port 5000 to the internet with ngrok: <code>ngrok http 5000</code></li>
<li>Copy the forwarding URL form ngrok and past it as your bot base URL on SAP Conversational AI</li>
</ol>
<h3 id="heading-4-preparing-the-external-api-call">4. Preparing the external API call</h3>
<p>It’s about time to start building! Let’s have a look at the api call we’ll be doing to get the price of any cryptocurrency. Several APIs are available for this purpose so I just went ahead and picked one: <a target="_blank" href="https://www.cryptocompare.com/api/">Cryptocompare API</a>.</p>
<p><a target="_blank" href="https://www.cryptocompare.com/api/">Cryptocompare API</a> offers thousands of possibilities, but for the sake of simplicity, we’ll stick with the basics. <strong>We want the price of the matched crypto in BTC, USD and EUR</strong>.</p>
<p>Here’s how the call is structured (here for ETH):</p>
<p><code>https://min-api.cryptocompare.com/data/price?fsym="ETH"&amp;tsyms=BTC,USD,EUR"</code></p>
<p>You have two parameters:</p>
<ul>
<li><code>fsym</code>: the symbol of the cryptocurrency, this is where we’ll need to fetch the crypto_name recognized in the #crypto_name entity.</li>
<li><code>tsyms</code>: the currency in which the price will be returned. We chose BTC, USD and EUR here.</li>
</ul>
<p>So, in our case, we’ll only need to adapt the <code>fsym</code> parameter to the recognized cryptocurrency, while the rest of the call stays the same.</p>
<h3 id="heading-5-adapt-the-api-call-to-include-the-symbol-recognized-in-the-user-input">5. Adapt the API call to include the symbol recognized in the user input</h3>
<p>Now that we know how to fetch the prices, we need to go back to our server code and upgrade it so it can:</p>
<ul>
<li>Know the #crypto_name recognized by SAP Conversational AI.</li>
<li>Make an API call to Cryptocompare using the #crypto_name.</li>
</ul>
<p>Let’s get started!</p>
<h4 id="heading-step-1-finding-our-data-in-sap-conversational-ai-json">Step 1: Finding our data in SAP Conversational AI JSON</h4>
<p>Let’s have a look at the data returned by SAP Conversational AI on a user input. To do so, you click the <code>CHAT WITH YOUR BOT</code> button present on all pages, on the bottom-right corner. Then, you can switch between the conversation and the JSON view by clicking on the orange information circle as below:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/L640-OoPuVyK3rF5SAEYQXI2ss4qv2sTE4Cf" alt="Image" width="371" height="272" loading="lazy">
<em>Check the JSON of the conversation.</em></p>
<p>Here, our symbol is accessible with <code>['conversation']['memory']['crypto']['raw']</code>. Since the value and the raw and identical in this case, you can use either.</p>
<p>On our server, the JSON returned by the website test panel is <strong>encapsulated into the <code>data</code> dictionary</strong> (see server code). So we need an extra step to retrieve it on our server:</p>
<pre><code># FETCH THE CRYPTO NAMEcrypto_name = data[<span class="hljs-string">'conversation'</span>][<span class="hljs-string">'memory'</span>][<span class="hljs-string">'crypto'</span>][<span class="hljs-string">'value'</span>]
</code></pre><h4 id="heading-step-2-make-an-api-call-using-the-recognized-entity">Step 2: Make an API call using the recognized entity</h4>
<pre><code><span class="hljs-keyword">import</span> requestsr = requests.get(<span class="hljs-string">"https://min-api.cryptocompare.com/data/price?fsym="</span>+crypto_name+<span class="hljs-string">"&amp;tsyms=BTC,USD,EUR"</span>)
</code></pre><p>Go ahead and print it, but you may be disappointed:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/AN1-kvadGRTMSbUU3P0oyVnnHAnvmpcYrOFo" alt="Image" width="194" height="60" loading="lazy"></p>
<p>Indeed, if you want to get the values returned by the call, you need to print <code>r.json()</code>. The good news is that JSON returned by Cryptocompare is really as simple as it could be:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/aDUzK6ox4aFmpZgkZul3M8KKFNZbtyGawLjH" alt="Image" width="800" height="84" loading="lazy">
<em>Cryptocompare JSON</em></p>
<p>Great! Now, we just have one last step to figure out: returning the prices to the user.</p>
<h4 id="heading-step-3-returning-the-data-fetched-to-the-user">Step 3: Returning the data fetched to the user</h4>
<p>Now, it’s time to finish our base server code upgrade: we need to edit the replies returned to include our freshly fetched data. To do so, we’ll edit the message returned by our server code:</p>
<pre><code><span class="hljs-keyword">return</span> jsonify(     status=<span class="hljs-number">200</span>,     replies=[{       <span class="hljs-string">'type'</span>: <span class="hljs-string">'text'</span>,       <span class="hljs-string">'content'</span>: <span class="hljs-string">'Roger that'</span>,     }],
</code></pre><p>We’ll be editing the replies only, to include the prices we fetched:</p>
<pre><code>replies=[{      <span class="hljs-string">'type'</span>: <span class="hljs-string">'text'</span>,      <span class="hljs-string">'content'</span>: <span class="hljs-string">'The price of %s is %f BTC and %f USD'</span> % (crypto_name, r.json()[<span class="hljs-string">'BTC'</span>], r.json()[<span class="hljs-string">'USD'</span>])    }],
</code></pre><p>Since the reply is a string, we must use the modulo (%) operator to include our prices in the string. Here, the first %s tells Python to look for a string while the two following %f indicates floats.</p>
<p>Our upgraded server is now finished, here’s the whole code:</p>
<pre><code><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, request, jsonifyimport jsonimport requestsapp = Flask(__name__)port = <span class="hljs-string">'5000'</span>@app.route(<span class="hljs-string">'/'</span>, methods=[<span class="hljs-string">'POST'</span>])def index():  data = json.loads(request.get_data())  # FETCH THE CRYPTO NAME  crypto_name = data[<span class="hljs-string">'conversation'</span>][<span class="hljs-string">'memory'</span>][<span class="hljs-string">'crypto'</span>][<span class="hljs-string">'raw'</span>]  # FETCH BTC/USD/EUR PRICES  r = requests.get(<span class="hljs-string">"https://min-api.cryptocompare.com/data/price?fsym="</span>+crypto_name+<span class="hljs-string">"&amp;tsyms=BTC,USD,EUR"</span>)  <span class="hljs-keyword">return</span> jsonify(    status=<span class="hljs-number">200</span>,    replies=[{      <span class="hljs-string">'type'</span>: <span class="hljs-string">'text'</span>,      <span class="hljs-string">'content'</span>: <span class="hljs-string">'The price of %s is %f BTC and %f USD'</span> % (crypto_name, r.json()[<span class="hljs-string">'BTC'</span>], r.json()[<span class="hljs-string">'USD'</span>])    }]  )@app.route(<span class="hljs-string">'/errors'</span>, methods=[<span class="hljs-string">'POST'</span>])def errors():  print(json.loads(request.get_data()))  <span class="hljs-keyword">return</span> jsonify(status=<span class="hljs-number">200</span>)app.run(port=port)
</code></pre><p>With our new server completed, we now have all the pieces of our puzzle. Let’s assemble it:</p>
<ol>
<li>Run your python script,</li>
<li>Expose port 5000 to the internet with ngrok: <code>ngrok http 5000</code>,</li>
<li>Copy the forwarding URL form ngrok and past it as your bot base URL on SAP Conversational AI</li>
</ol>
<p>Now that you have the basics to build a bot able to fetch third party data, what’s it gonna be? You show us!</p>
<p>PS: Since this tutorial uses ngrok, your computer must be on and ngrok must be running for your bot to function.</p>
<p>Originally published on <a target="_blank" href="https://cai.tools.sap/blog/python-cryptobot/">SAP Conversational AI blog</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Four architecture pattern candidates for Blockchain-based decentralized applications ]]>
                </title>
                <description>
                    <![CDATA[ By Srinath Perera Blockchain has a diverse set of use cases, ranging from finance to a decentralized Internet. However, most blockchain use cases can be implemented using relatively few patterns. For example, A Pattern Collection for Blockchain-based... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/https-medium-com-srinathperera-blockchain-patterns-6cf58fdc2d9b/</link>
                <guid isPermaLink="false">66d4614b706b9fb1c166b9b1</guid>
                
                    <category>
                        <![CDATA[ Bitcoin ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Blockchain ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software architecture ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 23 Apr 2019 15:49:36 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*iCv3PnwJ3jvu2pDhEq3ZhQ.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Srinath Perera</p>
<p>Blockchain has a diverse set of use cases, ranging from finance to a decentralized Internet. However, most blockchain use cases can be implemented using relatively few patterns. For example, <a target="_blank" href="https://www.researchgate.net/publication/325439030_A_Pattern_Collection_for_Blockchain-based_Applications">A Pattern Collection for Blockchain-based Applications</a> provides a list of 15 Blockchain patterns.</p>
<p>Fine-grained patterns, such as described above, are useful. However, system design needs a much higher level of abstractions. It is useful also to have more coarse-grained macro patterns, which we call architecture patterns. This post describes four such architecture patterns.</p>
<p>Let’s get started. To describe patterns, I will use the template described in by Aleksandra Tešanovic in <a target="_blank" href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.123.1162&amp;rep=rep1&amp;type=pdf">What is a Pattern</a>?</p>
<h3 id="heading-architecture-pattern-for-iam">Architecture Pattern for IAM.</h3>
<p><strong>Context:</strong> IAM environments include many users and service providers. IAM systems give each user an account and set of capabilities enabling users to go to service providers, demonstrate their ownership of accounts, and then receive services based on their capabilities.</p>
<p><strong>Forces:</strong> Need to implement a decentralized IAM environment where a single rogue user or few users can’t significantly affect the system.</p>
<p><strong>Solution:</strong> Proposed pattern candidate uses World Wide Web Consortium (W3C) DID specification and W3C Verifiable Claims specification in the following manner.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/lUMFQa8e5GZRqE9PVExbKKUBq43VTd0LCauy" alt="Image" width="800" height="760" loading="lazy">
<em>Figure 1: Blockchain-based IAM Architecture Pattern</em></p>
<p>Let’s assume Alice needs an identity (DID, which is a unique identifier). As shown by the figure for creating a new DID, Alice creates an entry in the blockchain. This entry includes a randomly generated identifier, a link to the repository with her profile data, and a hash of the profile data. The user profile contains a public key and a set of verifiable claims. The generated random identifier now becomes Alice’s DID because only she owns the private key that corresponds to the public key.</p>
<p>Verifiable claims are delegation tokens signed by a competent authority. The creator also records them in a blockchain together with the hash of the claim in a manner similar to the DID.</p>
<p>Alice obtains the verifiable claims in the first place by going to authorities. For example, the department of personal registration or equivalent is the proper authority for verifiable claims of name, address, and date of birth. Assuming authorities issue verifiable claims, Alice first demonstrates her ownership of the DID uses a challenge-response-protocol. Then she submits requests for verifiable claims for her attributes, which may, for example, include her name, address, degree, and date of birth. To update her profile data, Alice will add a new entry to the blockchain with a new hash of the profile.</p>
<p>In the challenge-response-protocol, the validator generates a random seed, encrypts it using Alice’s public key, and then challenges Alice to demonstrate that she has the private key by decrypting the encrypted seed. Since Alice has the private key, she must be the owner of the DID.</p>
<p>A different user or an organization (authenticator), Bob, who wants to identify Alice, first receives the DID from Alice, read all entries related to that DID from the blockchain, retrieve Alice’s profile data, and verify them. Bob can verify the identity of Alice (identification) again using challenge-response-protocol. Then Bob can confirm the verifiable claims and be assured that the claims about Alice are true.</p>
<p>We can layer most IAM use cases on top of this architecture pattern. For example, we can achieve access control either by issuing verifiable claims for actions we want users to perform or by only accepting users who have certain properties (e.g., age, job description, group membership) in their verifiable claims. An implementation may choose to cache relevant subsets of the profile data in a database to improve performance.</p>
<h3 id="heading-architecture-pattern-for-auditable-history-or-workspace">Architecture Pattern for Auditable History or Workspace</h3>
<p><strong>Context:</strong> A two or more parties perform transactions or works together, and their activities need to be recorded in an indisputable manner.</p>
<p><strong>Forces:</strong> Need to implement a decentralized audit log or a workspace where a single rogue user or few users can’t significantly affect the system.</p>
<p><strong>Solution:</strong> The proposed system records activities and creates entries in the blockchain for those records. The entry contains the hash of activity records, and therefore, the records can’t be disputed later.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/iF-qjFAl8ERHYc8MkajFeVnIUK10RiWz2RVG" alt="Image" width="800" height="692" loading="lazy">
<em>Figure 2: Blockchain based Auditable History or Workspace Architecture Pattern</em></p>
<p>For example, let’s assume Alice wants to pay a tax. Tax Server accepts the payment application, creates a digital receipt, records its hash in the blockchain, and sends the receipt to Alice. Alice can verify the receipt by calculating the hash and checking against the value stored in the blockchain. After this, Bob can’t deny the receipt because the receipt hash and time are recorded in the blockchain.</p>
<p>If the activities are numerous, there may be a need to workaround blockchain performance limitations. Therefore, some implementations may record a hash of several activity records as a block instead of a single activity record.</p>
<h3 id="heading-architecture-pattern-for-registry-or-marketplace">Architecture Pattern for Registry or Marketplace</h3>
<p><strong>Context:</strong> A registry is a collection of data entries that can be searched and retrieved over the network. A market place is a registry that allows users to buy the services or products represented by data entries. For example, a registry may be a catalog of available APIs.</p>
<p><strong>Forces:</strong> Need to implement a decentralized environment where a single rogue user or few users can’t significantly affect the system.</p>
<p><strong>Solution:</strong> The proposed pattern works as follows.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/PxrO0b03JFpQ-JuWXHXtzkfq56xJHND3gesV" alt="Image" width="800" height="564" loading="lazy">
<em>Figure 3: Blockchain based Registry Architecture Pattern</em></p>
<p>Let’s first consider a registry. With the proposed architecture, when a user issues a registry update (to add or modify an entry), the client records the change in the blockchain. If data in the update is large, the blockchain record may contain a link to the data and a hash value of the data. If data stored in the registry needs to be amended, the registry client adds a new record to the blockchain with amended information.</p>
<p>In the diagram above, each user has a registry client running in the local machine (e.g., laptop or phone). Each registry client reads the update records from the blockchain, verifies the update data against the hash included in the records, and reconstructs the most current view of records from updates. For example, by reading blockchain records about APIs, their additions, amendments, and removals, the registry client can create a view that shows current APIs included in the registry. To avoid having to read and verify all records every time the registry is used, clients might store data in a database and index it. The client should periodically check the blockchain and update the registry.</p>
<p>Blockchain works well as a “service marketplace,” since the same service may be sold many times. However, due to performance limitations, blockchain-based marketplaces are not suitable for items that can be sold only once.</p>
<p>To illustrate, the functionality of a blockchain-based registry, let’s look at when Alice wants to subscribe to “weather news service” in the blockchain marketplace. When she submits her request, the registry creates credentials for the service and shares it with Alice. The payment may happen in one of several ways: using Bitcoins, via a smart contract where payments are made on a timely basis, or by some out-of-bound means.</p>
<h3 id="heading-architecture-pattern-for-smart-contracts-and-managed-things">Architecture Pattern for Smart Contracts and Managed Things</h3>
<p>Under this pattern, we consider two cases. First, we consider smart contracts, and as the second, we consider a common special case of smart contracts: “Managed Things.”</p>
<h4 id="heading-smart-contracts-pattern">Smart Contracts Pattern</h4>
<p><strong>Context:</strong> Multiple users want to abide by a contract, described as an executable program. Contract undergoes state transitions as per conditions defined in the contract, and at a given time, everyone can agree on the current status of the contract.</p>
<p><strong>Forces:</strong> need to implement an environment where a single rogue user or few users can’t significantly affect the system.</p>
<p><strong>Solution:</strong> Smart contacts are part of blockchain technologies and supported by blockchain implementations, such as Ethereum. A contract is described using a smart contract language and distributed to all participants. As conditions defined in the contract changes, each participant executes the contract and records the current status in the blockchain using the consensus algorithm.</p>
<h4 id="heading-managed-things-pattern">Managed Things Pattern</h4>
<p><strong>Context:</strong> We need to track the ownership of real-world smart things. Here smart things are real-world objects that are capable of running computing logic within them. The owner is allowed to control and perform actions on the real world things. Also, the owner may transfer his ownership to someone else.</p>
<p><strong>Forces:</strong> need to implement an environment where a single rogue user or few users can’t significantly affect the system.</p>
<p><strong>Solution:</strong> Following describes the implementation of the pattern using Car as the managed thing as an example.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/8je7rRiQV0zVRuuvCXjnHJHMNlnNjOrv29r4" alt="Image" width="800" height="470" loading="lazy">
<em>Figure 4: Blockchain based Managed Things Architecture Pattern</em></p>
<p>We can implement a blockchain for a managed thing, in this case, a car, in two steps. First, the manufacturer records the DID and the public key of the owner of the car. When ownership changes, the owner adds a new record in the blockchain specifying the new owner. Second, when checking for ownership, the car first retrieves all records in the blockchain and verifies that each record is added by the owner at that time. This is done by checking the public key of the user who wrote the record against the public key included in the previous ownership record. The last owner in this valid chain is the current owner.</p>
<p>After determining the owner, the car logs in the current owner, Alice, by retrieving her public key and carrying out a challenge-response-protocol-based login with Alice’s phone, which has Alice’s private key.</p>
<p>Such a system reduces the risks associated with remotely controlled artifacts. For example, in a non-blockchain implementation, someone with access can change the ownership of your car. However, with the blockchain-based model, to remotely control the car, a would-be attacker must change the ownership record in the blockchain, which is very hard to achieve without being the owner.</p>
<p>However, it is hard to stop someone who has access to the “thing” from physically changing the logic running inside (e.g., by replacing the firmware of the car). One solution to this problem is to build some form of self-destruct that triggers when tampering into the artifact is detected.</p>
<p>For example, Alice buys the car from Bob using a smart contract that pays Bob and updates the ownership of the vehicle. After the transaction, Alice walks to the car, which reads Alice’s DID from the phone, retrieves her public key, authenticates her using a challenge-response-protocol by communicating with the phone that has Alice’s private key, verifies her ownership, and unlocks the car.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>We discussed four blockchain based architecture patterns. The GitHub document, <a target="_blank" href="https://github.com/wso2/ETAC/blob/master/blockchain/blockchain-usecases.md">Blockchain-based Integration Use Cases</a>, shows these patterns in action, describing how 30-plus blockchain use cases can be implemented using these four patterns.</p>
<p>If you have opinions about the above patterns or know about other patterns, I would really like to hear about them.</p>
<p>I hope this was useful. If you like this, you might also like a detailed blockchain analysis in our recently published paper, “<a target="_blank" href="https://peerj.com/preprints/27529/">A use case centric survey of Blockchain: status quo and future directions</a>.”</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The most popular programming languages used in blockchain development ]]>
                </title>
                <description>
                    <![CDATA[ By Michael Draper We’re currently in the midst of a new burgeoning industry with blockchain development. Blockchain technology is very much in a nascent stage, however this disruptive technology has already managed to take the world by storm and has ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-most-popular-programming-languages-used-in-blockchain-development-5133a0a207dc/</link>
                <guid isPermaLink="false">66c361d10cede4e9b1329ce2</guid>
                
                    <category>
                        <![CDATA[ Bitcoin ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Blockchain ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 18 Jan 2019 16:36:39 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*NAV5EQqx0pxMr1tb" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Michael Draper</p>
<p>We’re currently in the midst of a new burgeoning industry with blockchain development.</p>
<p>Blockchain technology is very much in a nascent stage, however this disruptive technology has already managed to take the world by storm and has experienced a boom like no other in recent times.</p>
<p>With many well-funded projects now eager to build out their blockchain network and deploy decentralized applications on top of them, there’s a great shortage of capable, competent blockchain developers.</p>
<p>With billions having been funneled into this sector, the pay and demand for blockchain developers has escalated with projects bidding against each other to attract the best blockchain talent that is left on the market.</p>
<p>This gold rush may leave some developers wondering if they have what it takes to dive into this industry, and especially what programming languages are most sought after in this new industry. Almost all popular programming languages are used in the blockchain industry, however developers have to consider what type of development they would like to undertake as different languages are used for certain blockchain projects and applications.</p>
<p>Here’s a brief rundown of the different languages and projects that are utilizing them to serve as a basic understanding and foundation for those looking to dive deeper into this industry.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/RevQpoRAiseiZCE6uyQtPkt5fDB8HD8l8BvK" alt="Image" width="320" height="445" loading="lazy"></p>
<p><a target="_blank" href="https://solidity.readthedocs.io/en/v0.5.1/"><strong>Solidity</strong></a> — A new and simple programming language that is popular amongst Ethereum developers, as it is the language used for developing Ethereum smart contracts. <strong>Solidity</strong> is a contract-oriented Turing-complete programming language and <a target="_blank" href="https://www.trustnodes.com/2018/07/22/ethereums-ecosystem-estimated-200000-developers-truffle-seeing-80000-downloads-month">the number of developers is estimated at over 200,000</a>.</p>
<p>As Ethereum has taken the head start on smart contracts, many alternative blockchain platforms are ensuring that they are Solidity (or ERC-20) compatible, thus allowing smart contracts to be easily ported from Ethereum into their new blockchain networks.</p>
<p><a target="_blank" href="https://www.ethereum.org/"><strong>Ethereum</strong></a> <strong>—</strong> Technically Ethereum functions as an Ethereum Virtual Machine (EVM) as a “world computer”, and is made up of multiple languages including C++, Python, Ruby, Go, and Java. JavaScript serves as the backbone of Ethereum as it functions as a runtime environment with script execution.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/453Z55OmBXoA7bZWXbNMwXDKErgEWfjUzInx" alt="Image" width="256" height="256" loading="lazy"></p>
<p><strong>Java</strong> — A general-purpose programming language that is concurrent, object-oriented, and class-based is designed in such a way that Java has few implementation dependencies. Since its launch in 1995, Java has become one of the top 3 programming languages and rightly so with <a target="_blank" href="http://infomory.com/numbers/number-of-java-developers/">over 9 million developers</a>. <a target="_blank" href="https://nem.io/"><strong>NEM’s</strong></a> core blockchain network has been written solely in Java (soon to be C++).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/bzwFfhuDu9UYcOnLazlQ9r4moMBEE5-MQ3Pw" alt="Image" width="300" height="288" loading="lazy"></p>
<p><strong>C#</strong> — An object-oriented language known to enable developers to build robust applications that run on the .NET Framework with at least <a target="_blank" href="https://blogs.msdn.microsoft.com/zxue/2016/10/24/how-many-developers-use-c-vs-c-vs-other-programming-languages/">2M developers worldwide</a>. C# was developed back in 2000. Since its inception, it has become a popular programming language used to build powerful cross platform code that works over multiple operating systems such as Windows, Mac, Linux, and Android. Blockchain projects written with C# include:</p>
<ul>
<li><a target="_blank" href="https://stratisplatform.com/"><strong>Stratis</strong></a> a Blockchain-as-a-Service provider backed by Microsoft, allows enterprises to build their own private blockchain systems.</li>
<li><a target="_blank" href="https://neo.org/"><strong>NEO</strong></a> was written in C#, however it also supports a variety of programming languages such as Javascript, Java, Python, and Go.</li>
</ul>
<p><img src="https://cdn-media-1.freecodecamp.org/images/gA2Klhnw9OxLGs8tfY2nGb1Sw1QKVw0bzIdX" alt="Image" width="280" height="280" loading="lazy"></p>
<p><strong>Javascript —</strong> Often abbreviated as JS, this is a multi-paradigm language that supports event-driven, functional, and imperative (including object-oriented and prototype-based) programming styles. It is one of the most popular programming languages in the world used by at least <a target="_blank" href="https://appdevelopermagazine.com/9.7m-developers-use-javascript/">9.7M developers worldwide</a>.</p>
<p><a target="_blank" href="https://lisk.io/"><strong>Lisk’s</strong></a> SideChain Development Kit (SDK) is written in JavaScript and allows developers to build applications on top of Lisk’s blockchain platform.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/q0XCGHR7jwZtmBosEjQVxZBG2NTJKNt1bB-P" alt="Image" width="369" height="303" loading="lazy"></p>
<p><strong>SQL —</strong> Structured Query Language or ‘’Sequel’’ is a programming language developed by IBM used to communicate with databases that store, query, and manipulate data. There is an estimated <a target="_blank" href="https://blog.jetbrains.com/datagrip/2015/12/23/how-many-sql-developers-is-out-there-a-jetbrains-report/">7 million developers</a> for SQL today. Popular databases such as MySQL, PostgreSQL, SQL Server, DB2, Oracle and more all use SQL to develop applications. A blockchain project that incorporates SQL is:</p>
<ul>
<li><a target="_blank" href="https://www.aergo.io/"><strong>Aergo</strong></a> <strong>—</strong> An entreprise-ready blockchain solution developed by Blocko under their proprietary Coinstack technology utilizes SQL smart contracts. The <strong>Aergo</strong> chain features a <strong>SQL</strong>-based smart contract platform that will allow enterprise entities to create and execute advanced smart contracts in commercial business environments.</li>
</ul>
<p><img src="https://cdn-media-1.freecodecamp.org/images/-7ltSXVwZ-2XGhF6mV9lRDJ7aawZBBuvUVMy" alt="Image" width="200" height="200" loading="lazy"></p>
<p><strong>C++</strong> — A general-purpose programming language with an estimated <a target="_blank" href="https://blog.jetbrains.com/clion/2015/07/infographics-cpp-facts-before-clion/">4.4 million developers</a>, it’s greatest strength lies in the capability to scale resource intensive applications and enable them to run smoothly, thus making it a very popular programming language for 3D games. Blockchain projects using C++ include:</p>
<ul>
<li><a target="_blank" href="https://eos.io/"><strong>EOS</strong></a> — C++ is the main programming language of EOS preferred for its flexibility to run extensive applications on top of the blockchain. EOS also supports any language that compiles into WebAssembly (WASM)</li>
</ul>
<blockquote>
<p><em>Random Fact: Bitcoin core’s network is programmed in C++.</em></p>
</blockquote>
<p><img src="https://cdn-media-1.freecodecamp.org/images/xDJHI4g0ZABEz-1rADp4Q7rWpRNmYdzjZeE-" alt="Image" width="607" height="318" loading="lazy"></p>
<p><a target="_blank" href="https://golang.org/"><strong>Golang</strong></a> — An open source general programming language loosely based on the syntax of the C programming language, Golang is easy for developers to learn, and for testers to understand. Currently there is an estimated <a target="_blank" href="https://research.swtch.com/gophercount">800,000+ developers</a> on the Golang language that is used by the consortium network:</p>
<ul>
<li><a target="_blank" href="https://hyperledger-fabric.readthedocs.io/en/release-1.3/"><strong>HyperLedger Fabric</strong></a> <strong>—</strong> Most of the chaincode (smart contracts built using HyperLedger Fabrics) is written in Golang. They also have a Java SDK for developing blockchain applications.</li>
</ul>
<p>Hopefully this has provided you with a basic overview of where to start and what to dig into further if the blockchain industry is something that interests you. There is little doubt that this industry will continue to further explode over the next decade or so as advancements are made and real-world adoption use cases emerge.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to create an iOS crypto tracking app with push notifications using Swift and Laravel ]]>
                </title>
                <description>
                    <![CDATA[ By Neo Ighodaro Part 2 _Photo by [Unsplash](https://unsplash.com/photos/iGYiBhdNTpE?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" rel="noopener" target="_blank" title="">André François McKenzie on <a href="https://unsplash.com/... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/create-a-cryptocurrency-tracking-app-with-push-notifications-using-swift-and-laravel-part-2-the-6275674a12f/</link>
                <guid isPermaLink="false">66c347f2790a62b5fbf7b8b2</guid>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ iOS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Laravel ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Swift ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 20 Dec 2018 16:39:02 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*cQl1eHoplkcQF2dTaWo5FA.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Neo Ighodaro</p>
<h4 id="heading-part-2">Part 2</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/IGYplFvYpzyybbPqcGLune2bODwCxmj9bc8v" alt="Image" width="800" height="534" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/photos/iGYiBhdNTpE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="_blank" title=""&gt;André François McKenzie on &lt;a href="https://unsplash.com/search/photos/bitcoin?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="<em>blank" title=")</em></p>
<blockquote>
<p>You will need the following installed on your machine: Xcode, the Laravel CLI, SQLite and Cocoapods. Familiarity with the Xcode IDE will be helpful. You should have completed part one of the series.</p>
</blockquote>
<p>In the <a target="_blank" href="https://medium.freecodecamp.org/how-to-create-the-backend-of-a-crypto-tracking-app-using-swift-and-laravel-1d9122bc290b">first part</a> of this article, we started developing our cryptocurrency alert application. We developed the backend of the application that will power the iOS application. As it stands, our backend application can return settings for a device based on its UUID, save the settings for a device based on its UUID and also figure out what devices to send push notifications to when the currencies update.</p>
<p>In this part, we will focus on creating the iOS application using Swift and Xcode.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>To follow along you need the following requirements:</p>
<ul>
<li>Completed <a target="_blank" href="https://medium.freecodecamp.org/how-to-create-the-backend-of-a-crypto-tracking-app-using-swift-and-laravel-1d9122bc290b">part one</a> of this article.</li>
<li><a target="_blank" href="https://developer.apple.com/xcode">Xcode</a> installed on your machine.</li>
<li>Knowledge of the Xcode IDE.</li>
<li>Basic knowledge using the <a target="_blank" href="https://laravel.com/">Laravel framework</a>.</li>
<li>Basic knowledge of the <a target="_blank" href="http://developer.apple.com/swift">Swift programming language</a>.</li>
<li><a target="_blank" href="https://laravel.com/docs/5.6/installation">Laravel CLI</a> installed on your machine.</li>
<li>SQLite installed on your machine. <a target="_blank" href="http://www.sqlitetutorial.net/download-install-sqlite/">Installation guide</a>.</li>
<li><a target="_blank" href="https://guides.cocoapods.org/using/getting-started.html">Cocoapods</a> installed on your machine.</li>
<li><a target="_blank" href="https://pusher.com/beams">Pusher Beams</a> and <a target="_blank" href="https://pusher.com/channels">Channels</a> application.</li>
</ul>
<h3 id="heading-what-we-will-be-building">What we will be building</h3>
<p>We already started out by building the backend of the application using Laravel. So next, we will build the iOS application using Swift. If you want to test the push notifications then you will need to run the application on a live device.</p>
<h3 id="heading-how-the-client-application-will-work">How the client application will work</h3>
<p>For the client app, the iOS application, we will create a simple list that will display the available currencies and the current prices to the dollar. Whenever the price of the cryptocurrency changes, we will trigger an event using Pusher Channels so the prices are updated.</p>
<p>From the application, you will be able to set a minimum and maximum price change when you want to be alerted. For instance, you can configure the application to send a push notification to the application when the price of one Etherium (ETH) goes below $500. You can also configure the application to receive a notification when the price of Bitcoin goes above $5000.</p>
<h3 id="heading-how-the-application-will-look">How the application will look</h3>
<p>When we are done with the application, here’s how the application will look:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ynnaEkKLDhpnaZBrt7pd4aw5gxGjUYK89hNT" alt="Image" width="800" height="708" loading="lazy"></p>
<p>Let’s get started.</p>
<h3 id="heading-setting-up-your-client-application">Setting up your client application</h3>
<p>Launch Xcode and click <strong>Create a new Xcode project</strong>. Select <strong>Single View App</strong> and click <strong>Next</strong>. Enter your <strong>Product Name</strong>, we will call our project <em>cryptoalat</em>, and select <strong>Swift</strong> from the <strong>Language</strong> options. You can also change any other detail you wish to on the screen then click <strong>Next</strong>.</p>
<h3 id="heading-installing-dependencies">Installing dependencies</h3>
<p>Now you have your Xcode project. Close Xcode and open a terminal window. <code>cd</code> to the iOS project directory in terminal and run the command below to create a Podfile:</p>
<pre><code class="lang-bash">$ pod init
</code></pre>
<blockquote>
<p><em>The Podfile is a specification that describes the dependencies of the targets of one or more Xcode projects. The file should simply be named Podfile. All the examples in the guides are based on CocoaPods version 1.0 and onwards. — <a target="_blank" href="https://guides.cocoapods.org/using/the-podfile.html">Cocoapods Guides</a></em></p>
</blockquote>
<p>This will generate a new file called <code>Podfile</code> in the root of your project. Open this file in any editor and update the file as seen below:</p>
<pre><code class="lang-bash">// File: Podfile
platform :ios, <span class="hljs-string">'11.0'</span>

target <span class="hljs-string">'cryptoalat'</span> <span class="hljs-keyword">do</span>
  use_frameworks!

  pod <span class="hljs-string">'Alamofire'</span>, <span class="hljs-string">'~&gt; 4.7.2'</span>
  pod <span class="hljs-string">'PushNotifications'</span>, <span class="hljs-string">'~&gt; 0.10.8'</span>
  pod <span class="hljs-string">'PusherSwift'</span>, <span class="hljs-string">'~&gt; 6.1.0'</span>
  pod <span class="hljs-string">'NotificationBannerSwift'</span>, <span class="hljs-string">'~&gt; 1.6.3'</span>
end
</code></pre>
<blockquote>
<p><em>If you used a project name other than cryptoalat, then change it in the Podfile to match your project’s target name.</em></p>
</blockquote>
<p>Go to terminal and run the command below to install your dependencies:</p>
<pre><code class="lang-bash">$ pod install
</code></pre>
<p>When the installation is complete, you will have a <code>*.xcworkspace</code> file in the root of your project. Open this file in Xcode and let’s start developing our cryptocurrency alert application.</p>
<h3 id="heading-building-the-ios-application">Building the iOS application</h3>
<h4 id="heading-creating-our-storyboard">Creating our storyboard</h4>
<p>The first thing we need to do is design our storyboard for the application. This is what we want the storyboard to look like when we are done.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/JZxbqFnKDBwtADJ8tJcYigBx9V0zq04dbu0N" alt="Image" width="800" height="420" loading="lazy"></p>
<p>Open the <code>Main.storyboard</code> file and design as seen above.</p>
<p>Above we have three scenes. The first scene, which is the entry point, is the launch scene. We then draw a manual segue with an identifier called <strong>Main</strong>. Then we set the segue <strong>Kind</strong> to <strong>Present Modally</strong>. This will present the next scene which is a navigation view controller. Navigation controllers already have an attached root view controller by default.</p>
<p>We will use this attached view controller, which is a <code>TableViewController</code>, as the main view for our application. It’ll list the available currencies and show us a text field that allows us to change the setting for that currency when it is tapped.</p>
<p>On the third scene, we set the reuse identifier of the cells to <strong>coin</strong> and we drag two labels to the prototype cell. The first label will be for the coin name and the second label will be for the price.</p>
<p>Now that we have the scenes, let’s create some controllers and view classes and connect them to our storyboard scenes.</p>
<h4 id="heading-creating-your-controllers">Creating your controllers</h4>
<p>In Xcode, create a new class <code>LaunchViewController</code> and paste the contents of the file below into it:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">import</span> UIKit

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LaunchViewController</span>: <span class="hljs-title">UIViewController</span> </span>{

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">viewDidAppear</span><span class="hljs-params">(<span class="hljs-number">_</span> animated: Bool)</span></span> {
        <span class="hljs-keyword">super</span>.viewDidAppear(animated)

        <span class="hljs-type">SettingsService</span>.shared.loadSettings {
            <span class="hljs-keyword">self</span>.routeToMainController()
        }
    }

    <span class="hljs-keyword">fileprivate</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">routeToMainController</span><span class="hljs-params">()</span></span> {
        performSegue(withIdentifier: <span class="hljs-string">"Main"</span>, sender: <span class="hljs-keyword">self</span>)
    }
}
</code></pre>
<blockquote>
<p><em>Set the controller as the custom class for the first scene in the <code>Main.storyboard</code> file.</em></p>
</blockquote>
<p>In the code, we load the settings using a <code>SettingsService</code> class we will create later. When the settings are loaded for the device, we then call the <code>routeToMainController</code> method, which routes the application to the main controller using the <strong>Main</strong> segue we created earlier.</p>
<p>The next controller we will be creating will be the <code>CoinsTableViewController</code>. This will be the controller that will be tied to the third scene which is the main scene.</p>
<p>Create the <code>CoinsTableViewController</code> and replace the contents with the following code:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">import</span> UIKit
<span class="hljs-keyword">import</span> PusherSwift
<span class="hljs-keyword">import</span> NotificationBannerSwift

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Coin</span> </span>{
    <span class="hljs-keyword">let</span> name: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> rate: <span class="hljs-type">Float</span>
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CoinsTableViewController</span>: <span class="hljs-title">UITableViewController</span> </span>{

    <span class="hljs-keyword">var</span> coins: [<span class="hljs-type">Coin</span>] = []

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">viewDidLoad</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">super</span>.viewDidLoad()
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">numberOfSections</span><span class="hljs-params">(<span class="hljs-keyword">in</span> tableView: UITableView)</span></span> -&gt; <span class="hljs-type">Int</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">tableView</span><span class="hljs-params">(<span class="hljs-number">_</span> tableView: UITableView, numberOfRowsInSection section: Int)</span></span> -&gt; <span class="hljs-type">Int</span> {
        <span class="hljs-keyword">return</span> coins.<span class="hljs-built_in">count</span>
    }

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">tableView</span><span class="hljs-params">(<span class="hljs-number">_</span> tableView: UITableView, cellForRowAt indexPath: IndexPath)</span></span> -&gt; <span class="hljs-type">UITableViewCell</span> {
        <span class="hljs-keyword">let</span> coin = coins[indexPath.row]
        <span class="hljs-keyword">let</span> cell = tableView.dequeueReusableCell(withIdentifier: <span class="hljs-string">"coin"</span>, <span class="hljs-keyword">for</span>: indexPath) <span class="hljs-keyword">as</span>! <span class="hljs-type">CoinTableViewCell</span>

        cell.name.text = <span class="hljs-string">"1 \(coin.name) ="</span>
        cell.amount.text = <span class="hljs-string">"$\(String(coin.rate))"</span>

        <span class="hljs-keyword">return</span> cell
    }
}
</code></pre>
<blockquote>
<p><em>Set the controller as the custom class for the first scene in the <code>Main.storyboard</code> file.</em></p>
</blockquote>
<p>Above we have defined the <code>Coin</code> struct and it has a <code>name</code> and <code>rate</code> property. We have the controller which we define the <code>coins</code> property as an array of <code>Coin</code>s. We then have some boilerplate code that comes with creating a table view controller.</p>
<p>The <code>numberOfSections</code> method specifies how many sections the table will have. In the first <code>tableView</code> method, we return the number of <code>coins</code> available and in the second <code>tableView</code> method, we define how we want each row to be handled.</p>
<h4 id="heading-creating-other-supporting-classes">Creating other supporting classes</h4>
<p>If you noticed in the code above, we referenced a <code>CoinTableViewCell</code> as the class for each row in the last <code>tableView</code> method. Let’s create that.</p>
<p>Create a <code>CoinTableViewCell</code> class and paste the following code into it:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CoinTableViewCell</span>: <span class="hljs-title">UITableViewCell</span> </span>{
    <span class="hljs-meta">@IBOutlet</span> <span class="hljs-keyword">weak</span> <span class="hljs-keyword">var</span> name: <span class="hljs-type">UILabel!</span>    
    <span class="hljs-meta">@IBOutlet</span> <span class="hljs-keyword">weak</span> <span class="hljs-keyword">var</span> amount: <span class="hljs-type">UILabel!</span>
}
</code></pre>
<p>Open the <code>Main.storyboard</code> file and set the class as the custom class for the prototype cell in the third scene of the <code>Main.storyboard</code> file. When you have set the class, connect the <code>@IBOutlet</code>s as specified in the cell class above.</p>
<p>The next class we need to create is the <code>SettingsService</code>. This class will be responsible for updating and fetching the settings for the device.</p>
<p>Create a new <code>SettingsService</code> class and replace the contents with the following code:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">import</span> Foundation
<span class="hljs-keyword">import</span> Alamofire
<span class="hljs-keyword">import</span> NotificationBannerSwift

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SettingsService</span> </span>{
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">let</span> key = <span class="hljs-string">"CryptoAlat"</span>
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">let</span> shared = <span class="hljs-type">SettingsService</span>()

    <span class="hljs-keyword">var</span> settings: <span class="hljs-type">Settings?</span> {
        <span class="hljs-keyword">get</span> {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>.getCachedSettings()
        }
        <span class="hljs-keyword">set</span>(settings) {
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> settings = settings {
                <span class="hljs-keyword">self</span>.updateCachedSettings(settings)
            }
        }
    }

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">init</span>() {}

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">loadSettings</span><span class="hljs-params">(completion: @escaping<span class="hljs-params">()</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
        fetchRemoteSettings { settings <span class="hljs-keyword">in</span>
            <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> settings = settings <span class="hljs-keyword">else</span> {
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>.saveSettings(<span class="hljs-keyword">self</span>.defaultSettings()) { <span class="hljs-number">_</span> <span class="hljs-keyword">in</span>
                    completion()
                }
            }

            <span class="hljs-keyword">self</span>.updateCachedSettings(settings)
            completion()
        }
    }

    <span class="hljs-keyword">fileprivate</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">defaultSettings</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Settings</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-type">Settings</span>(
            btc_min_notify: <span class="hljs-number">0</span>, 
            btc_max_notify: <span class="hljs-number">0</span>, 
            eth_min_notify: <span class="hljs-number">0</span>, 
            eth_max_notify: <span class="hljs-number">0</span>
        )
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">saveSettings</span><span class="hljs-params">(<span class="hljs-number">_</span> settings: Settings, completion: @escaping<span class="hljs-params">(Bool)</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
        updateRemoteSettings(settings, completion: { saved <span class="hljs-keyword">in</span>
            <span class="hljs-keyword">if</span> saved {
                <span class="hljs-keyword">self</span>.updateCachedSettings(settings)
            }

            completion(saved)
        })
    }

    <span class="hljs-keyword">fileprivate</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fetchRemoteSettings</span><span class="hljs-params">(completion: @escaping <span class="hljs-params">(Settings?)</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
        <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> deviceID = <span class="hljs-type">AppConstants</span>.deviceIDFormatted <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">return</span> completion(<span class="hljs-literal">nil</span>)
        }

        <span class="hljs-keyword">let</span> url = <span class="hljs-string">"\(AppConstants.API_URL)?u=\(deviceID)"</span>
        <span class="hljs-type">Alamofire</span>.request(url).validate().responseJSON { resp <span class="hljs-keyword">in</span>
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> data = resp.data, resp.result.isSuccess {
                <span class="hljs-keyword">let</span> decoder = <span class="hljs-type">JSONDecoder</span>()
                <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> settings = <span class="hljs-keyword">try</span>? decoder.decode(<span class="hljs-type">Settings</span>.<span class="hljs-keyword">self</span>, from: data) {
                    <span class="hljs-keyword">return</span> completion(settings)
                }
            }

            completion(<span class="hljs-literal">nil</span>)
        }
    }

    <span class="hljs-keyword">fileprivate</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updateRemoteSettings</span><span class="hljs-params">(<span class="hljs-number">_</span> settings: Settings, completion: @escaping<span class="hljs-params">(Bool)</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
        <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> deviceID = <span class="hljs-type">AppConstants</span>.deviceIDFormatted <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">return</span> completion(<span class="hljs-literal">false</span>)
        }

        <span class="hljs-keyword">let</span> params = settings.toParams()
        <span class="hljs-keyword">let</span> url = <span class="hljs-string">"\(AppConstants.API_URL)?u=\(deviceID)"</span>
        <span class="hljs-type">Alamofire</span>.request(url, method: .post, parameters: params).validate().responseJSON { resp <span class="hljs-keyword">in</span>
            <span class="hljs-keyword">guard</span> resp.result.isSuccess, <span class="hljs-keyword">let</span> res = resp.result.value <span class="hljs-keyword">as</span>? [<span class="hljs-type">String</span>: <span class="hljs-type">String</span>] <span class="hljs-keyword">else</span> {
                <span class="hljs-keyword">return</span> <span class="hljs-type">StatusBarNotificationBanner</span>(title: <span class="hljs-string">"Failed to update settings."</span>, style: .danger).show()
            }

            completion((res[<span class="hljs-string">"status"</span>] == <span class="hljs-string">"success"</span>))
        }
    }

    <span class="hljs-keyword">fileprivate</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updateCachedSettings</span><span class="hljs-params">(<span class="hljs-number">_</span> settings: Settings)</span></span> {
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> encodedSettings = <span class="hljs-keyword">try</span>? <span class="hljs-type">JSONEncoder</span>().encode(settings) {
            <span class="hljs-type">UserDefaults</span>.standard.<span class="hljs-keyword">set</span>(encodedSettings, forKey: <span class="hljs-type">SettingsService</span>.key)
        }
    }

    <span class="hljs-keyword">fileprivate</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getCachedSettings</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Settings?</span> {
        <span class="hljs-keyword">let</span> defaults = <span class="hljs-type">UserDefaults</span>.standard
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> data = defaults.object(forKey: <span class="hljs-type">SettingsService</span>.key) <span class="hljs-keyword">as</span>? <span class="hljs-type">Data</span> {
            <span class="hljs-keyword">let</span> decoder = <span class="hljs-type">JSONDecoder</span>()
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> decodedSettings = <span class="hljs-keyword">try</span>? decoder.decode(<span class="hljs-type">Settings</span>.<span class="hljs-keyword">self</span>, from: data) {
                <span class="hljs-keyword">return</span> decodedSettings
            }
        }

        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
    }
}
</code></pre>
<p>Above we have the <code>SettingsService</code>. The first method <code>loadSettings</code> loads the settings from the API and then saves it locally. If there is no setting remotely, it calls the <code>defaultSettings</code> method and saves the response to the API.</p>
<p>The <code>saveSettings</code> method saves the <code>Settings</code> remotely using <code>updateRemoteSettings</code> and then locally using <code>updateCachedSettings</code>. The <code>fetchRemoteSettings</code> gets the settings from the API and decodes the response using the <a target="_blank" href="https://blog.pusher.com/swift-4-decoding-json-codable/">Swift decodable API</a>.</p>
<p>Next, let’s define the <code>Settings</code> struct and have it extend <code>Codable</code>. In the same file for the <code>SettingsService</code>, add this above the <code>SettingsService</code> class definition:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Settings</span>: <span class="hljs-title">Codable</span> </span>{
    <span class="hljs-keyword">var</span> btc_min_notify: <span class="hljs-type">Int?</span>
    <span class="hljs-keyword">var</span> btc_max_notify: <span class="hljs-type">Int?</span>
    <span class="hljs-keyword">var</span> eth_min_notify: <span class="hljs-type">Int?</span>
    <span class="hljs-keyword">var</span> eth_max_notify: <span class="hljs-type">Int?</span>

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">toParams</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Parameters</span> {
        <span class="hljs-keyword">var</span> params: <span class="hljs-type">Parameters</span> = [:]

        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> btcMin = btc_min_notify { params[<span class="hljs-string">"btc_min_notify"</span>] = btcMin }
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> btcMax = btc_max_notify { params[<span class="hljs-string">"btc_max_notify"</span>] = btcMax }
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> ethMin = eth_min_notify { params[<span class="hljs-string">"eth_min_notify"</span>] = ethMin }
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> ethMax = eth_max_notify { params[<span class="hljs-string">"eth_max_notify"</span>] = ethMax }

        <span class="hljs-keyword">return</span> params
    }
}
</code></pre>
<p>Above we have a simple <code>Settings</code> struct that conforms to <code>Codable</code>. We also have a <code>toParams</code> method that converts the properties to a <code>Parameters</code> type so we can use it with <a target="_blank" href="https://github.com/Alamofire/Alamofire">Alamofire</a> when making requests.</p>
<p>One last class we need to create is <code>AppConstants</code>. We will use this class to keep all the data that we expect to remain constant and unchanged throughout the lifetime of the application.</p>
<p>Create a <code>AppConstants</code> file and paste the following code:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">import</span> UIKit

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">AppConstants</span> </span>{
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">let</span> <span class="hljs-type">API_URL</span> = <span class="hljs-string">"http://127.0.0.1:8000/api/settings"</span>
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">let</span> deviceID = <span class="hljs-type">UIDevice</span>.current.identifierForVendor?.uuidString
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">let</span> deviceIDFormatted = <span class="hljs-type">AppConstants</span>.deviceID?.replacingOccurrences(of: <span class="hljs-string">"-"</span>, with: <span class="hljs-string">"_"</span>).lowercased()
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">let</span> <span class="hljs-type">PUSHER_INSTANCE_ID</span> = <span class="hljs-string">"PUSHER_BEAMS_INSTANCE_ID"</span>
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">let</span> <span class="hljs-type">PUSHER_APP_KEY</span> = <span class="hljs-string">"PUSHER_APP_KEY"</span>
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">let</span> <span class="hljs-type">PUSHER_APP_CLUSTER</span> = <span class="hljs-string">"PUSHER_APP_CLUSTER"</span>
}
</code></pre>
<blockquote>
<p><em>Replace the `PUSHER</em>*` keys with the values gotten from the Pusher Channels and Beams dashboard._</p>
</blockquote>
<h4 id="heading-updating-the-settings-for-the-device">Updating the settings for the device</h4>
<p>Now that we have defined the settings service, let’s update our controller so the user can set the minimum and maximum prices for each currency.</p>
<p>Open the <code>CoinsTableViewController</code> class and add the following method:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">tableView</span><span class="hljs-params">(<span class="hljs-number">_</span> tableView: UITableView, didSelectRowAt indexPath: IndexPath)</span></span> {
    <span class="hljs-keyword">let</span> coin = coins[indexPath.row]

    <span class="hljs-keyword">var</span> minTextField: <span class="hljs-type">UITextField?</span>
    <span class="hljs-keyword">var</span> maxTextField: <span class="hljs-type">UITextField?</span>

    <span class="hljs-keyword">let</span> title = <span class="hljs-string">"Manage \(coin.name) alerts"</span>
    <span class="hljs-keyword">let</span> message = <span class="hljs-string">"Notification will be sent to you when price exceeds or goes below minimum and maximum price. Set to zero to turn off notification."</span>

    <span class="hljs-keyword">let</span> alert = <span class="hljs-type">UIAlertController</span>(title: title, message: message, preferredStyle: .alert)

    alert.addTextField { textfield <span class="hljs-keyword">in</span>
        minTextField = textfield
        textfield.placeholder = <span class="hljs-string">"Alert when price is below"</span>
    }

    alert.addTextField { textfield <span class="hljs-keyword">in</span>
        maxTextField = textfield
        textfield.placeholder = <span class="hljs-string">"Alert when price is above"</span>
    }

    alert.addAction(<span class="hljs-type">UIAlertAction</span>(title: <span class="hljs-string">"Cancel"</span>, style: .cancel, handler: <span class="hljs-literal">nil</span>))

    alert.addAction(<span class="hljs-type">UIAlertAction</span>(title: <span class="hljs-string">"Save"</span>, style: .<span class="hljs-keyword">default</span>, handler: { action <span class="hljs-keyword">in</span>
        <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> minPrice = minTextField?.text, <span class="hljs-keyword">let</span> maxPrice = maxTextField?.text <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">return</span> <span class="hljs-type">StatusBarNotificationBanner</span>(title: <span class="hljs-string">"Invalid min or max price"</span>, style: .danger).show()
        }

        <span class="hljs-keyword">var</span> btcMin: <span class="hljs-type">Int?</span>, btcMax: <span class="hljs-type">Int?</span>, ethMin: <span class="hljs-type">Int?</span>, ethMax: <span class="hljs-type">Int?</span>

        <span class="hljs-keyword">switch</span> coin.name {
        <span class="hljs-keyword">case</span> <span class="hljs-string">"BTC"</span>:
            btcMin = <span class="hljs-type">Int</span>(minPrice)
            btcMax = <span class="hljs-type">Int</span>(maxPrice)
        <span class="hljs-keyword">case</span> <span class="hljs-string">"ETH"</span>:
            ethMin = <span class="hljs-type">Int</span>(minPrice)
            ethMax = <span class="hljs-type">Int</span>(maxPrice)
        <span class="hljs-keyword">default</span>:
            <span class="hljs-keyword">return</span>
        }

        <span class="hljs-keyword">let</span> settings = <span class="hljs-type">Settings</span>(
            btc_min_notify: btcMin,
            btc_max_notify: btcMax,
            eth_min_notify: ethMin,
            eth_max_notify: ethMax
        )

        <span class="hljs-type">SettingsService</span>.shared.saveSettings(settings, completion: { saved <span class="hljs-keyword">in</span>
            <span class="hljs-keyword">if</span> saved {
                <span class="hljs-type">StatusBarNotificationBanner</span>(title: <span class="hljs-string">"Saved successfully"</span>).show()
            }
        })
    }))

    present(alert, animated: <span class="hljs-literal">true</span>, completion: <span class="hljs-literal">nil</span>)
}
</code></pre>
<p>The method above is automatically called when a row is selected. In this method, we display a <code>UIAlertController</code> with two text fields for the minimum price and the maximum price. When the prices are submitted, the <code>SettingsService</code> we created earlier takes care of updating the values both locally and remotely.</p>
<h4 id="heading-adding-realtime-cryptocurrency-update-support">Adding realtime cryptocurrency update support</h4>
<p>Open the <code>CoinsTableViewController</code> and add the <code>pusher</code> property to the class as seen below:</p>
<pre><code><span class="hljs-keyword">var</span> pusher: Pusher!
</code></pre><p>Then replace the <code>viewDidLoad</code> method with the following code:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">viewDidLoad</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">super</span>.viewDidLoad()

    pusher = <span class="hljs-type">Pusher</span>(
        key: <span class="hljs-type">AppConstants</span>.<span class="hljs-type">PUSHER_APP_KEY</span>, 
        options: <span class="hljs-type">PusherClientOptions</span>(host: .cluster(<span class="hljs-type">AppConstants</span>.<span class="hljs-type">PUSHER_APP_CLUSTER</span>))
    )

    <span class="hljs-keyword">let</span> channel = pusher.subscribe(<span class="hljs-string">"currency-update"</span>)

    <span class="hljs-keyword">let</span> <span class="hljs-number">_</span> = channel.bind(eventName: <span class="hljs-string">"currency.updated"</span>) { data <span class="hljs-keyword">in</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> data = data <span class="hljs-keyword">as</span>? [<span class="hljs-type">String</span>: [<span class="hljs-type">String</span>: [<span class="hljs-type">String</span>: <span class="hljs-type">Float</span>]]] {
            <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> payload = data[<span class="hljs-string">"payload"</span>] <span class="hljs-keyword">else</span> { <span class="hljs-keyword">return</span> }

            <span class="hljs-keyword">self</span>.coins = []

            <span class="hljs-keyword">for</span> (coin, deets) <span class="hljs-keyword">in</span> payload {
                <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> currentPrice = deets[<span class="hljs-string">"current"</span>] <span class="hljs-keyword">else</span> { <span class="hljs-keyword">return</span> }
                <span class="hljs-keyword">self</span>.coins.append(<span class="hljs-type">Coin</span>(name: coin, rate: currentPrice))
            }

            <span class="hljs-type">Dispatch</span>.main.async {
                <span class="hljs-keyword">self</span>.tableView.reloadData()
            }
        }
    }

    pusher.connect()
}
</code></pre>
<p>In the code above, we are using the <a target="_blank" href="https://pusher.com/docs/ios_quick_start">Pusher Swift SDK</a> to subscribe to our <code>currency-update</code> Pusher Channel. We then subscribe to the <code>currency.updated</code> event on that channel. Whenever that event is triggered, we refresh the price of the cryptocurrency in realtime.</p>
<h3 id="heading-adding-push-notifications-to-our-ios-new-application">Adding push notifications to our iOS new application</h3>
<p>To add push notification support, open the <code>AppDelegate</code> class and replace the contents with the following:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">import</span> UIKit
<span class="hljs-keyword">import</span> PushNotifications

<span class="hljs-meta">@UIApplicationMain</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppDelegate</span>: <span class="hljs-title">UIResponder</span>, <span class="hljs-title">UIApplicationDelegate</span> </span>{

    <span class="hljs-keyword">var</span> window: <span class="hljs-type">UIWindow?</span>

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">application</span><span class="hljs-params">(<span class="hljs-number">_</span> application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: <span class="hljs-keyword">Any</span>]?)</span></span> -&gt; <span class="hljs-type">Bool</span> {
        <span class="hljs-type">PushNotifications</span>.shared.start(instanceId: <span class="hljs-type">AppConstants</span>.<span class="hljs-type">PUSHER_INSTANCE_ID</span>)
        <span class="hljs-type">PushNotifications</span>.shared.registerForRemoteNotifications()
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">application</span><span class="hljs-params">(<span class="hljs-number">_</span> application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)</span></span> {
        <span class="hljs-type">PushNotifications</span>.shared.registerDeviceToken(deviceToken) {
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> deviceID = <span class="hljs-type">AppConstants</span>.deviceIDFormatted {
                <span class="hljs-keyword">try</span>? <span class="hljs-type">PushNotifications</span>.shared.subscribe(interest: <span class="hljs-string">"\(deviceID)_eth_changed"</span>)
                <span class="hljs-keyword">try</span>? <span class="hljs-type">PushNotifications</span>.shared.subscribe(interest: <span class="hljs-string">"\(deviceID)_btc_changed"</span>)
            }
        }
    }
}
</code></pre>
<p>In the class above, we use the <a target="_blank" href="https://docs.pusher.com/push-notifications/reference/ios">Pusher Beams Swift SDK</a> to register the device for push notifications. We then subscribe to the <code>*_eth_changed</code> and <code>*_btc_changed</code> interests, where <code>*</code> is the device’s unique UUID.</p>
<p>Now that we have completed the logic for the application, let’s enable push notifications on the application in Xcode.</p>
<p>In the project navigator, select your project, and click on the <strong>Capabilities</strong> tab. <a target="_blank" href="http://help.apple.com/xcode/mac/current/#/devdfd3d04a1">Enable Push Notifications</a> by turning the switch ON.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/4Kd00J1IvFFj633HSm-WbwTxm5pHFxhPRY82" alt="Image" width="800" height="217" loading="lazy"></p>
<p>This will create an entitlements file in the root of your project. With that, you have provisioned your application to fully receive push notifications.</p>
<h3 id="heading-allowing-our-application-to-connect-locally">Allowing our application to connect locally</h3>
<p>If you are going to be testing the app’s backend using a local server, then there is one last thing we need to do. Open the <code>info.plist</code> file and add an entry to the <code>plist</code> file to allow connection to our local server:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/973kwkgkzdbbxkJQzMEePM3vR2yCwC2J-FRn" alt="Image" width="800" height="479" loading="lazy"></p>
<p>That’s all. We can run our application. However, <strong>remember that to demo the push notifications, you will need an actual iOS device as simulators cannot receive push notifications.</strong> If you are using a physical device, you’ll need to expose your local API using <a target="_blank" href="https://ngrok.com">Ngrok</a> and then change the <code>API_URL</code> <strong>in</strong> <code>AppConstants</code>.</p>
<p>Anytime you want to update the currency prices, run the command below manually in your Laravel application:</p>
<pre><code class="lang-bash">$ php artisan schedule:run
</code></pre>
<p>Here is a screen recording of the application in action:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/OBlHx04eWtcmomYWEAXfZlr3N2kM9ZC90Wym" alt="Image" width="800" height="708" loading="lazy"></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In this article, we have been able to see how easy it is to create a cryptocurrency alert website using Laravel, Swift, Pusher Channels and Pusher Beams. The source code to the application built in this article is available on <a target="_blank" href="https://github.com/neoighodaro/cryptocurrency-alert-ios-app">GitHub</a>.</p>
<p>This article was first published on <a target="_blank" href="https://pusher.com/tutorials/cryptocurrency-tracking-swift-laravel-part-2">Pusher</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to create the backend of a crypto tracking app using Swift and Laravel ]]>
                </title>
                <description>
                    <![CDATA[ By Neo Ighodaro Part 1 _Photo by [Unsplash](https://unsplash.com/photos/aUHr4gcQCCE?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" rel="noopener" target="_blank" title="">André François McKenzie on <a href="https://unsplash.com/... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-the-backend-of-a-crypto-tracking-app-using-swift-and-laravel-1d9122bc290b/</link>
                <guid isPermaLink="false">66c35148f41767c3c96bad10</guid>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Laravel ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Swift ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 19 Dec 2018 17:28:20 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*U-_YZ407G1keDN56lNaXtQ.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Neo Ighodaro</p>
<h4 id="heading-part-1">Part 1</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/qYBbPa7FXKpFgfQUGtLv0UAzONrnqtSdBl-5" alt="Image" width="800" height="534" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/photos/aUHr4gcQCCE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="_blank" title=""&gt;André François McKenzie on &lt;a href="https://unsplash.com/search/photos/cryptocurrency?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="<em>blank" title=")</em></p>
<blockquote>
<p>You will need the following installed on your machine: Xcode, the Laravel CLI, SQLite and Cocoapods. Familiarity with the Xcode IDE will be helpful.</p>
</blockquote>
<h3 id="heading-introduction">Introduction</h3>
<p>Cryptocurrency has been and is still one of the biggest trends this year. With currencies like Bitcoin reaching record highs and new companies creating tokens and offerings, it’s showing just how much potential cryptocurrencies have. However, cryptocurrency prices are erratic and can fall or climb at a moment’s notice, so it’s always a good idea to keep tabs on the changes.</p>
<p>In this article, we will be building an application that keeps tabs on changes to the crypto market. The application will focus on BTC and ETH and will allow users of the application to set minimum and maximum amounts when they would like to be notified about the coin’s current price. The application will be built using Swift, Laravel, Pusher Channels, and Pusher Beams.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>To follow along you need the following requirements:</p>
<ul>
<li><a target="_blank" href="https://developer.apple.com/xcode">Xcode</a> installed on your machine.</li>
<li>Knowledge of the Xcode IDE.</li>
<li>Basic knowledge using the <a target="_blank" href="https://laravel.com/">Laravel framework</a>.</li>
<li>Basic knowledge of the <a target="_blank" href="http://developer.apple.com/swift">Swift programming language</a>.</li>
<li><a target="_blank" href="https://laravel.com/docs/5.6/installation">Laravel CLI</a> installed on your machine.</li>
<li>SQLite installed on your machine. <a target="_blank" href="https://www.tutorialspoint.com/sqlite/sqlite_installation.htm">Installation guide</a>.</li>
<li><a target="_blank" href="https://guides.cocoapods.org/using/getting-started.html">Cocoapods</a> installed on your machine.</li>
<li><a target="_blank" href="https://pusher.com/beams">Pusher Beams</a> and <a target="_blank" href="https://pusher.com/channels">Channels</a> application.</li>
</ul>
<h3 id="heading-what-we-will-be-building">What we will be building</h3>
<p>We will start out by building the backend of the application using Laravel. Then we will build the iOS application using Swift. If you want to test the push notifications then you will need to run the application on a live device.</p>
<h3 id="heading-how-the-client-application-will-work">How the client application will work</h3>
<p>For the client app, the iOS application, we will create a simple list that will display the available currencies and the current prices to the dollar. Whenever the price of the cryptocurrency changes, we will trigger an event using Pusher Channels so the prices are updated.</p>
<p>From the application, you will be able to set a minimum and maximum price change when you want to be alerted. For instance, you can configure the application to send a push notification to the application when the price of one Etherium (ETH) goes below $500. You can also configure the application to receive a notification when the price of Bitcoin goes above $5000.</p>
<h3 id="heading-how-the-backend-application-will-work">How the backend application will work</h3>
<p>For the backend application, we will be using Laravel and we will create endpoints that allow a user update the settings and load the settings for a device. The API will be responsible for checking the current prices of the cryptocurrency and sending both a Channels update and a Beams notification when the price changes.</p>
<p>However, because the prices don’t change very predictably, we will be simulating the currency changes so we can preview the application in action. We will also be using <a target="_blank" href="https://laravel.com/docs/5.6/scheduling">task scheduling</a> in Laravel to trigger the checks for the current currency prices.</p>
<p>In a production environment we will set the scheduler as a cronjob, but because we are in development, we will manually run the command to trigger price changes.</p>
<h3 id="heading-how-the-application-will-look">How the application will look</h3>
<p>When we are done with the application, here’s how the application will look:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/mRQw2yNxaOb3PXYPtqYV7qHp5J5BqIWdal9C" alt="Image" width="800" height="708" loading="lazy"></p>
<p>Let’s get started.</p>
<h3 id="heading-setting-up-pusher-beams-and-channels">Setting up Pusher Beams and Channels</h3>
<h4 id="heading-setting-up-pusher-channels">Setting up Pusher Channels</h4>
<p>Log in to your <a target="_blank" href="https://dashboard.pusher.com">Pusher dashboard</a>. If you don’t have an account, create one. Your dashboard should look like this:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/RS-2j91z505-2KRm2sSUYa46oVM1jh9WYR0v" alt="Image" width="800" height="422" loading="lazy"></p>
<p>Create a new Channels app. You can easily do this by clicking the big <strong>Create new Channels app</strong> card at the bottom right. When you create a new app, you are provided with keys. Keep them safe as you will soon need them.</p>
<h4 id="heading-setting-up-pusher-beams">Setting up Pusher Beams</h4>
<p>Next, log in to the new <a target="_blank" href="https://dash.pusher.com/">Pusher dashboard</a>, in here we will create a Pusher Beams instance. You should sign up if you don’t have an account yet. Click on the <strong>Beams</strong> button on the sidebar then click <strong>Create</strong>, this will launch a pop up to <strong>Create a new Beams instance</strong>. Name it <code>cryptoalat</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/yOT20aNZkSLD15v7dv6szLwe0yAcU-dBQj1b" alt="Image" width="800" height="445" loading="lazy"></p>
<p>As soon as you create the instance, you will be presented with a quickstart guide. Select the <strong>IOS</strong> quickstart and follow through the wizard.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/F21GIadi91kKhGTlWN8O6KMCQJ-bTt5bjjqo" alt="Image" width="800" height="533" loading="lazy"></p>
<p>When you are done creating the Beams application, you will be provided with an instance ID and a secret key, we will need these later.</p>
<h3 id="heading-setting-up-your-backend-application">Setting up your backend application</h3>
<p>In your terminal, run the command below to create a new Laravel project:</p>
<pre><code class="lang-bash">$ laravel new cryptoapi
</code></pre>
<p>This command will create a new Laravel project and install all the required Laravel dependencies.</p>
<p>Next, let’s install some of the project specific dependencies. Open the <code>composer.json</code> file and in the <code>require</code> property, add the following dependencies:</p>
<pre><code class="lang-json"><span class="hljs-comment">// File: composer.json</span>
    <span class="hljs-string">"require"</span>: {
        [...]

        <span class="hljs-attr">"neo/pusher-beams"</span>: <span class="hljs-string">"^1.0"</span>,
        <span class="hljs-attr">"pusher/pusher-php-server"</span>: <span class="hljs-string">"~3.0"</span>
    },
</code></pre>
<p>Now run the command below to install these dependencies.</p>
<pre><code class="lang-bash">$ composer update
</code></pre>
<p>When the installation is complete, open the project in a text editor of your choice. <a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a> is pretty nice.</p>
<h3 id="heading-setting-up-our-pusher-beams-library">Setting up our Pusher Beams library</h3>
<p>The first thing we want to do is set up the <a target="_blank" href="https://github.com/neoighodaro/pusher-beams">Pusher Beams library</a> we just pulled in using composer. To set up, open the <code>.env</code> file and add the following keys:</p>
<pre><code>PUSHER_BEAMS_SECRET_KEY=<span class="hljs-string">"PUSHER_BEAMS_SECRET_KEY"</span>
    PUSHER_BEAMS_INSTANCE_ID=<span class="hljs-string">"PUSHER_BEAMS_INSTANCE_ID"</span>
</code></pre><p>You should replace the <code>PUSHER_BEAMS_*</code> placeholders with the keys you got when setting up your Beams application.</p>
<p>Next, open the <code>config/broadcasting.php</code> file and scroll until you see the <code>connections</code> key. In there, you’ll have the <code>pusher</code> settings, add the following to the <code>pusher</code> configuration:</p>
<pre><code class="lang-php"><span class="hljs-string">'pusher'</span> =&gt; [
        <span class="hljs-comment">// [...]</span>

        <span class="hljs-string">'beams'</span> =&gt; [
            <span class="hljs-string">'secret_key'</span> =&gt; env(<span class="hljs-string">'PUSHER_BEAMS_SECRET_KEY'</span>),
            <span class="hljs-string">'instance_id'</span> =&gt; env(<span class="hljs-string">'PUSHER_BEAMS_INSTANCE_ID'</span>),
        ],
    ],
</code></pre>
<h3 id="heading-setting-up-our-pusher-channels-library">Setting up our Pusher Channels library</h3>
<p>The next step is to set up Pusher Channels. Laravel comes with native support for Pusher Channels so we do not need to do much to set it up.</p>
<p>Open the <code>.env</code> file and update the following keys below:</p>
<pre><code>BROADCAST_DRIVER=pusher

    <span class="hljs-comment">// [...]</span>

    PUSHER_APP_ID=<span class="hljs-string">"PUSHER_APP_ID"</span>
    PUSHER_APP_KEY=<span class="hljs-string">"PUSHER_APP_KEY"</span>
    PUSHER_APP_SECRET=<span class="hljs-string">"PUSHER_APP_SECRET"</span>
    PUSHER_APP_CLUSTER=<span class="hljs-string">"PUSHER_APP_CLUSTER"</span>
</code></pre><p>Above you set the <code>BROADCAST_DRIVER</code> to <code>pusher</code> and then for the other <code>PUSHER_APP_*</code> keys, replace the placeholders with the keys gotten from your Pusher dashboard. That’s all we need to do to set up Pusher Channels for this application.</p>
<h3 id="heading-building-the-backend-application">Building the backend application</h3>
<p>Now that we have set up all the dependencies, we can start building the application. We will start by creating the routes. However, instead of creating controllers to hook into the routes, we will be adding the logic directly to the routes.</p>
<h4 id="heading-setting-up-the-database-migration-and-model">Setting up the database, migration, and model</h4>
<p>Since we will be working with a database, we need to set up the database we are going to be working with. To make things easy we will be using SQLite. Create an empty <code>database.sqlite</code> file in the <code>database</code> directory.</p>
<p>Open the <code>.env</code> file and replace:</p>
<pre><code>DB_CONNECTION=mysql
    DB_HOST=<span class="hljs-number">127.0</span><span class="hljs-number">.0</span><span class="hljs-number">.1</span>
    DB_PORT=<span class="hljs-number">3306</span>
    DB_DATABASE=homestead
    DB_USERNAME=homestead
    DB_PASSWORD=secret
</code></pre><p>With</p>
<pre><code>DB_CONNECTION=sqlite
    DB_DATABASE=<span class="hljs-regexp">/full/</span>path/to/your/database.sqlite
</code></pre><p>Next, let’s create a migration for the <code>devices</code> table. We will use this table to store devices and their notification settings. This will help us know what devices to send push notifications to.</p>
<p>Run the command below to create the migration and model:</p>
<pre><code class="lang-bash">$ php artisan make:model Device -m
</code></pre>
<blockquote>
<p><em>The <code>-m</code> flag will instruct artisan to create a migration alongside the model.</em></p>
</blockquote>
<p>This command will generate two files, the migration file in the <code>database/migrations</code> and the model in the <code>app</code> directory. Let’s edit the migration file first.</p>
<p>Open the <code>*_create_devices_table.php</code> migration file in the <code>database/migrations</code> directory and replace the contents with the following:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Schema</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Schema</span>\<span class="hljs-title">Blueprint</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Migrations</span>\<span class="hljs-title">Migration</span>;

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreateDevicesTable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
    </span>{
        <span class="hljs-comment">/**
         * Run the migrations.
         *
         * <span class="hljs-doctag">@return</span> void
         */</span>
        <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span>(<span class="hljs-params"></span>)
        </span>{
            Schema::create(<span class="hljs-string">'devices'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
                $table-&gt;increments(<span class="hljs-string">'id'</span>);
                $table-&gt;string(<span class="hljs-string">'uuid'</span>)-&gt;unique();
                $table-&gt;float(<span class="hljs-string">'btc_min_notify'</span>)-&gt;default(<span class="hljs-number">0</span>);
                $table-&gt;float(<span class="hljs-string">'btc_max_notify'</span>)-&gt;default(<span class="hljs-number">0</span>);
                $table-&gt;float(<span class="hljs-string">'eth_min_notify'</span>)-&gt;default(<span class="hljs-number">0</span>);
                $table-&gt;float(<span class="hljs-string">'eth_max_notify'</span>)-&gt;default(<span class="hljs-number">0</span>);
            });
        }

        <span class="hljs-comment">/**
         * Reverse the migrations.
         *
         * <span class="hljs-doctag">@return</span> void
         */</span>
        <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span>(<span class="hljs-params"></span>)
        </span>{
            Schema::dropIfExists(<span class="hljs-string">'devices'</span>);
        }
    }
</code></pre>
<p>In the <code>up</code> method, we have defined the structure of the <code>devices</code> table. We have the <code>uuid</code> field which will be a unique string for each device registered. We have two <code>btc_notify</code> fields which are there to save the minimum and maximum prices of BTC at which point the device should be notified. Same applies to the<em> `eth_</em>_notify` fields.</p>
<p>To run the migration, run the command below:</p>
<pre><code class="lang-bash">$ php artisan migrate
</code></pre>
<p>Open the <code>app/Device.php</code> model and replace the contents with the code below:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
    <span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>;

    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Eloquent</span>\<span class="hljs-title">Model</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Notifications</span>\<span class="hljs-title">Notifiable</span>;

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Device</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span>
    </span>{
        <span class="hljs-keyword">use</span> <span class="hljs-title">Notifiable</span>;

        <span class="hljs-keyword">public</span> $timestamps = <span class="hljs-literal">false</span>;

        <span class="hljs-keyword">protected</span> $fillable = [
            <span class="hljs-string">'uuid'</span>, 
            <span class="hljs-string">'btc_min_notify'</span>, 
            <span class="hljs-string">'btc_max_notify'</span>, 
            <span class="hljs-string">'eth_min_notify'</span>, 
            <span class="hljs-string">'eth_max_notify'</span>,
        ];

        <span class="hljs-keyword">protected</span> $cast = [
            <span class="hljs-string">'btc_min_notify'</span> =&gt; <span class="hljs-string">'float'</span>,
            <span class="hljs-string">'btc_max_notify'</span> =&gt; <span class="hljs-string">'float'</span>,
            <span class="hljs-string">'eth_min_notify'</span> =&gt; <span class="hljs-string">'float'</span>,
            <span class="hljs-string">'eth_max_notify'</span> =&gt; <span class="hljs-string">'float'</span>
        ];

        <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">scopeAffected</span>(<span class="hljs-params">$query, <span class="hljs-keyword">string</span> $currency, $currentPrice</span>)
        </span>{
            <span class="hljs-keyword">return</span> $query-&gt;where(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$q</span>) <span class="hljs-title">use</span> (<span class="hljs-params">$currency, $currentPrice</span>) </span>{
                $q-&gt;where(<span class="hljs-string">"${currency}_min_notify"</span>, <span class="hljs-string">'&gt;'</span>, <span class="hljs-number">0</span>)
                  -&gt;where(<span class="hljs-string">"${currency}_min_notify"</span>, <span class="hljs-string">'&gt;'</span>, $currentPrice);
            })-&gt;orWhere(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$q</span>) <span class="hljs-title">use</span> (<span class="hljs-params">$currency, $currentPrice</span>) </span>{
                $q-&gt;where(<span class="hljs-string">"${currency}_max_notify"</span>, <span class="hljs-string">'&gt;'</span>, <span class="hljs-number">0</span>)
                  -&gt;where(<span class="hljs-string">"${currency}_max_notify"</span>, <span class="hljs-string">'&lt;'</span>, $currentPrice);
            });
        }
    }
</code></pre>
<p>In the model above, we have set the <code>$timestamps</code> property to <code>false</code> to make sure that Eloquent does not try to update the <code>created_at</code> and <code>updated_at</code> fields, which is the normal behavior.</p>
<p>We also have the <code>scopeAffected</code> method which is an example of an <a target="_blank" href="https://laravel.com/docs/5.6/eloquent#local-scopes">Eloquent scope</a>. We use this to get the affected devices after a price change has occurred on a currency. So if, for instance, BTC’s price drops, this method will check the devices and the settings to see the devices that need to be notified of this change.</p>
<blockquote>
<p><em>Local scopes allow you to define common sets of constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all users that are considered “popular”. To define a scope, prefix an Eloquent model method with <code>scope</code>. - <a target="_blank" href="https://laravel.com/docs/5.6/eloquent#local-scopes">Laravel documentation</a>.</em></p>
</blockquote>
<p>We will use this scope later in our application when we need to know what devices to send push notifications to.</p>
<h4 id="heading-creating-the-routes">Creating the routes</h4>
<p>Open the <code>routes/api.php</code> file and replace the contents of the file with the following code:</p>
<pre><code class="lang-php"><span class="hljs-comment">// File: routes/api.php</span>
    <span class="hljs-meta">&lt;?php</span>
    <span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Device</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Request</span>;
</code></pre>
<p>Next, let’s add the first route. Append the code below to the routes file:</p>
<pre><code class="lang-php"><span class="hljs-comment">// File: routes/api.php</span>
    Route::get(<span class="hljs-string">'/settings'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Request $request</span>) </span>{
        <span class="hljs-keyword">return</span> Device::whereUuid($request-&gt;query(<span class="hljs-string">'u'</span>))-&gt;firstOrFail()[<span class="hljs-string">'settings'</span>];
    });
</code></pre>
<p>In the route above, we are returning the settings for the device supplied in the <code>u</code> query parameter. This means if a registered device hits the <code>/settings</code> endpoint and passes the device UUID through the <code>u</code> parameter, the settings for that device will be returned.</p>
<p>Next, in the same routes file, paste the following at the bottom of the file:</p>
<pre><code class="lang-php">Route::post(<span class="hljs-string">'/settings'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Request $request</span>) </span>{
        $settings = $request-&gt;validate([
            <span class="hljs-string">'btc_min_notify'</span> =&gt; <span class="hljs-string">'int|min:0'</span>,
            <span class="hljs-string">'btc_max_notify'</span> =&gt; <span class="hljs-string">'int|min:0'</span>,
            <span class="hljs-string">'eth_min_notify'</span> =&gt; <span class="hljs-string">'int|min:0'</span>,
            <span class="hljs-string">'eth_max_notify'</span> =&gt; <span class="hljs-string">'int|min:0'</span>,
        ]);

        $settings = array_filter($settings, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$value</span>) </span>{ <span class="hljs-keyword">return</span> $value &gt; <span class="hljs-number">0</span>; });

        $device = Device::firstOrNew([<span class="hljs-string">'uuid'</span> =&gt; $request-&gt;query(<span class="hljs-string">'u'</span>)]);
        $device-&gt;fill($settings);
        $saved = $device-&gt;save();

        <span class="hljs-keyword">return</span> response()-&gt;json([
            <span class="hljs-string">'status'</span> =&gt; $saved ? <span class="hljs-string">'success'</span> : <span class="hljs-string">'failure'</span>
        ], $saved ? <span class="hljs-number">200</span> : <span class="hljs-number">400</span>);
    });
</code></pre>
<p>Above, we have defined the route for the <code>POST /settings</code> route. This route saves settings to the database. It will create a new entry if the setting does not already exist or will update the existing one if it does.</p>
<p>That’s all for the routes.</p>
<h4 id="heading-creating-the-jobs-events-and-notifiers">Creating the jobs, events, and notifiers</h4>
<p>Next, we need to create the <a target="_blank" href="https://laravel.com/docs/5.6/queues#creating-jobs">Laravel job</a> that will run at intervals to check if there is a change in the currency price.</p>
<p>Run the command below to create a new Laravel job:</p>
<pre><code class="lang-bash">$ php artisan make:job CheckPrices
</code></pre>
<p>This will create a new <code>CheckPrices</code> class in the <code>app</code> directory. Open that class and replace the contents with the following:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

    <span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Jobs</span>;

    <span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Device</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Bus</span>\<span class="hljs-title">Queueable</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Queue</span>\<span class="hljs-title">SerializesModels</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Queue</span>\<span class="hljs-title">InteractsWithQueue</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Contracts</span>\<span class="hljs-title">Queue</span>\<span class="hljs-title">ShouldQueue</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Foundation</span>\<span class="hljs-title">Bus</span>\<span class="hljs-title">Dispatchable</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Events</span>\<span class="hljs-title">CurrencyUpdated</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Notifications</span>\<span class="hljs-title">CoinPriceChanged</span>;

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CheckPrices</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ShouldQueue</span>
    </span>{
        <span class="hljs-keyword">use</span> <span class="hljs-title">Dispatchable</span>, <span class="hljs-title">InteractsWithQueue</span>, <span class="hljs-title">Queueable</span>, <span class="hljs-title">SerializesModels</span>;

        <span class="hljs-keyword">protected</span> $supportedCurrencies = [<span class="hljs-string">'ETH'</span>, <span class="hljs-string">'BTC'</span>];

        <span class="hljs-comment">/**
         * Execute the job.
         *
         * <span class="hljs-doctag">@return</span> void
         */</span>
        <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handle</span>(<span class="hljs-params"></span>)
        </span>{
            $payload = <span class="hljs-keyword">$this</span>-&gt;getPricesForSupportedCurrencies();

            <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">empty</span>($payload)) {
                <span class="hljs-keyword">$this</span>-&gt;triggerPusherUpdate($payload);
                <span class="hljs-keyword">$this</span>-&gt;triggerPossiblePushNotification($payload);
            }
        }

        <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">triggerPusherUpdate</span>(<span class="hljs-params">$payload</span>)
        </span>{
            event(<span class="hljs-keyword">new</span> CurrencyUpdated($payload));
        }

        <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">triggerPossiblePushNotification</span>(<span class="hljs-params">$payload</span>)
        </span>{
            <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">$this</span>-&gt;supportedCurrencies <span class="hljs-keyword">as</span> $currency) {
                $currentPrice = $payload[$currency][<span class="hljs-string">'current'</span>];

                $currency = strtolower($currency);

                <span class="hljs-keyword">foreach</span> (Device::affected($currency, $currentPrice)-&gt;get() <span class="hljs-keyword">as</span> $device) {
                    $device-&gt;notify(<span class="hljs-keyword">new</span> CoinPriceChanged($currency, $device, $payload));
                }
            }
        }

        <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPricesForSupportedCurrencies</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
        </span>{
            $payload = [];

            <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">$this</span>-&gt;supportedCurrencies <span class="hljs-keyword">as</span> $currency) {
                <span class="hljs-keyword">if</span> (config(<span class="hljs-string">'app.debug'</span>) === <span class="hljs-literal">true</span>) {
                    $response = [
                        $currency =&gt; [
                            <span class="hljs-string">'USD'</span> =&gt; (<span class="hljs-keyword">float</span>) rand(<span class="hljs-number">100</span>, <span class="hljs-number">15000</span>)
                        ]
                    ];
                } <span class="hljs-keyword">else</span> {
                    $url = <span class="hljs-string">"https://min-api.cryptocompare.com/data/pricehistorical?fsym=<span class="hljs-subst">{$currency}</span>&amp;tsyms=USD&amp;ts=<span class="hljs-subst">{$timestamp}</span>"</span>;

                    $response = json_decode(file_get_contents($url), <span class="hljs-literal">true</span>);
                }

                <span class="hljs-keyword">if</span> (json_last_error() === JSON_ERROR_NONE) {
                    $currentPrice = $response[$currency][<span class="hljs-string">'USD'</span>];

                    $previousPrice = cache()-&gt;get(<span class="hljs-string">"PRICE_${currency}"</span>, <span class="hljs-literal">false</span>);

                    <span class="hljs-keyword">if</span> ($previousPrice == <span class="hljs-literal">false</span> <span class="hljs-keyword">or</span> $previousPrice !== $currentPrice) {
                        $payload[$currency] = [
                            <span class="hljs-string">'current'</span> =&gt; $currentPrice,
                            <span class="hljs-string">'previous'</span> =&gt; $previousPrice,
                        ];
                    }

                    cache()-&gt;put(<span class="hljs-string">"PRICE_${currency}"</span>, $currentPrice, (<span class="hljs-number">24</span> * <span class="hljs-number">60</span> * <span class="hljs-number">60</span>));
                }
            }

            <span class="hljs-keyword">return</span> $payload;
        }
    }
</code></pre>
<p>In the class above, we implement the <code>ShouldQueue</code> interface. This makes it so that the job can and will be queued. In a production server, queueing jobs makes your application faster as it queues jobs that might take a while to execute for later execution.</p>
<p>We have four methods in this class. The first one is the <code>handle</code> method. This one is called automatically when the job is executed. In this method, we fetch the prices for the available currencies and then check if the price has changed. If it has, we publish a Pusher Channel event and then check if there are any devices that need to be notified based on the user’s settings. If there are any, we send a push notification to that device.</p>
<p>We have the <code>triggerPusherUpdate</code> method which triggers a <code>CurrencyUpdated</code> event. We will create this event in the next section. We also have a <code>triggerPossiblePushNotification</code> method which gets the list of devices which should be notified of the currency change and then notifies the user using the <code>CoinPriceChanged</code> class, which we will create in the next section.</p>
<p>Lastly, we have the <code>getPricesForSupportedCurrencies</code> method which just fetches the current price of a currency. In this method, we have a debug mode that simulates the current price of a currency.</p>
<p>To make sure this class we just created is scheduled properly, open the <code>app/Console/Kernel.php</code> file and in the <code>schedule</code> method, add the following code to the <code>schedule</code> method:</p>
<pre><code class="lang-php">$schedule-&gt;job(<span class="hljs-keyword">new</span> \App\Jobs\CheckPrices)-&gt;everyMinute();
</code></pre>
<p>Now every time we run the command <code>php artisan schedule:run</code> all the jobs in this <code>schedule</code> method will be run. Normally, in a production environment, we will need to add the schedule command as a cronjob, however, we will run this command manually.</p>
<p>The next thing to do will be to create the notifiers and events. In your terminal, run the following commands:</p>
<pre><code class="lang-bash">$ php artisan make:event CurrencyUpdated    $ php artisan make:notification CoinPriceChanged
</code></pre>
<p>This will create a class in the <code>Events</code> and <code>Notifications</code> directories.</p>
<p>In the <a target="_blank" href="https://laravel.com/docs/5.6/events">event</a> class, <code>CurrencyUpdated</code> paste the following code:</p>
<pre><code>&lt;?php

    namespace App\Events;

    use Illuminate\Broadcasting\Channel;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CurrencyUpdated</span> <span class="hljs-title">implements</span> <span class="hljs-title">ShouldBroadcast</span>
    </span>{
        use Dispatchable, InteractsWithSockets, SerializesModels;

        public $payload;

        public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">$payload</span>)
        </span>{
            $this-&gt;payload = $payload;
        }

        public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">broadcastOn</span>(<span class="hljs-params"></span>)
        </span>{
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Channel(<span class="hljs-string">'currency-update'</span>);
        }

        public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">broadcastAs</span>(<span class="hljs-params"></span>)
        </span>{
            <span class="hljs-keyword">return</span> <span class="hljs-string">'currency.updated'</span>;
        }
    }
</code></pre><p>In the event class above, we have the <code>broadcastOn</code> method that specifies the Pusher channel we want to broadcast an event on. We also have the <code>broadcastAs</code> method which specifies the name of the event we want to broadcast to the channel.</p>
<p>In the <code>CoinPriceChanged</code> <a target="_blank" href="https://laravel.com/docs/5.6/notifications">notification</a> class, replace the contents with the following code:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

    <span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Notifications</span>;

    <span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Device</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Bus</span>\<span class="hljs-title">Queueable</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Neo</span>\<span class="hljs-title">PusherBeams</span>\<span class="hljs-title">PusherBeams</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Neo</span>\<span class="hljs-title">PusherBeams</span>\<span class="hljs-title">PusherMessage</span>;
    <span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Notifications</span>\<span class="hljs-title">Notification</span>;

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CoinPriceChanged</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Notification</span>
    </span>{
        <span class="hljs-keyword">use</span> <span class="hljs-title">Queueable</span>;

        <span class="hljs-keyword">private</span> $currency;
        <span class="hljs-keyword">private</span> $device;
        <span class="hljs-keyword">private</span> $payload;

        <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $currency, Device $device, <span class="hljs-keyword">array</span> $payload</span>)
        </span>{
            <span class="hljs-keyword">$this</span>-&gt;currency = $currency;
            <span class="hljs-keyword">$this</span>-&gt;device = $device;
            <span class="hljs-keyword">$this</span>-&gt;payload = $payload;
        }

        <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">via</span>(<span class="hljs-params">$notifiable</span>)
        </span>{
            <span class="hljs-keyword">return</span> [PusherBeams::class];
        }

        <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">toPushNotification</span>(<span class="hljs-params">$notifiable</span>)
        </span>{
            $currentPrice = <span class="hljs-keyword">$this</span>-&gt;payload[strtoupper(<span class="hljs-keyword">$this</span>-&gt;currency)][<span class="hljs-string">'current'</span>];

            $previousPrice = <span class="hljs-keyword">$this</span>-&gt;payload[strtoupper(<span class="hljs-keyword">$this</span>-&gt;currency)][<span class="hljs-string">'current'</span>];

            $direction = $currentPrice &gt; $previousPrice ? <span class="hljs-string">'climbed'</span> : <span class="hljs-string">'dropped'</span>;

            $currentPriceFormatted = number_format($currentPrice);

            <span class="hljs-keyword">return</span> PusherMessage::create()
                    -&gt;iOS()
                    -&gt;sound(<span class="hljs-string">'success'</span>)
                    -&gt;title(<span class="hljs-string">"Price of <span class="hljs-subst">{$this-&gt;currency}</span> has <span class="hljs-subst">{$direction}</span>"</span>)
                    -&gt;body(<span class="hljs-string">"The price of <span class="hljs-subst">{$this-&gt;currency}</span> has <span class="hljs-subst">{$direction}</span> and is now \$<span class="hljs-subst">{$currentPriceFormatted}</span>"</span>);
        }

        <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">pushNotificationInterest</span>(<span class="hljs-params"></span>)
        </span>{
            $uuid = strtolower(str_replace(<span class="hljs-string">'-'</span>, <span class="hljs-string">'_'</span>, <span class="hljs-keyword">$this</span>-&gt;device-&gt;uuid));

            <span class="hljs-keyword">return</span> <span class="hljs-string">"<span class="hljs-subst">{$uuid}</span>_<span class="hljs-subst">{$this-&gt;currency}</span>_changed"</span>;
        }
    }
</code></pre>
<p>In the class above we have the <code>toPushNotification</code> class which prepares the push notification using the Pusher Beams library. We also have the <code>pushNotificationInterest</code> method which sets the name for the interest of the push notification depending on the currency and device ID.</p>
<p>That’s all for the backend, now just run the command below to start the server:</p>
<pre><code>$ php artisan serve
</code></pre><p>This will start a PHP server with our application running. Also if you need to manually trigger a currency change, run the command below:</p>
<pre><code class="lang-bash">$ php artisan schedule:run
</code></pre>
<p>Now that we are done with the backend, we can create the application using Swift and Xcode.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In this part of the article, we have created the backend for our cryptocurrency alert application. <a target="_blank" href="https://pusher.com/tutorials/cryptocurrency-tracking-swift-laravel-part-2">In the next part</a>, we will be seeing how we can create the application that will consume the API we just created in this part.</p>
<p>The source code to this application is available on <a target="_blank" href="https://github.com/neoighodaro/cryptocurrency-alert-ios-app">GitHub</a>.</p>
<p>This article was first published to <a target="_blank" href="https://pusher.com/tutorials/cryptocurrency-tracking-swift-laravel-part-1">pusher.</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How does tokenization work, anyway? ]]>
                </title>
                <description>
                    <![CDATA[ By Albert Ho Not everything will be tokenized, but that which can be will be. 2017 saw the hype of utility tokens and ICOs. 2018 marks the hyped start of asset tokenization and the launch of securities tokens/platforms. This trend is notably huge in... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-does-tokenization-work-anyway-afb5fed1ac47/</link>
                <guid isPermaLink="false">66c34d124f7405e6476b01d8</guid>
                
                    <category>
                        <![CDATA[ Bitcoin ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Blockchain ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ethereum ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tokenization ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 20 Oct 2018 13:06:04 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*7pMYW1axSFq7uO09x3UoqA.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Albert Ho</p>
<h4 id="heading-not-everything-will-be-tokenized-but-that-which-can-be-will-be"><strong>Not everything will be tokenized, but that which can be will be.</strong></h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/3S1xyeWzGYjjVeZp5EGSY1S6gFYFUEyYLl12" alt="Image" width="800" height="533" loading="lazy"></p>
<p>2017 saw the hype of utility tokens and ICOs. 2018 marks the hyped start of asset tokenization and the launch of securities tokens/platforms. This trend is notably huge in the U.S, given how A16z and GGV Capital invested in the likes of tokenization platforms like <a target="_blank" href="https://blog.trusttoken.com/trusttoken-raises-20-million-usd-in-strategic-round-88912d1dbc71">TrustToken</a>, <a target="_blank" href="https://techcrunch.com/2018/04/17/harbor-securities-tokenization/">Harbor</a>, and <a target="_blank" href="https://www.businessinsider.sg/a-startup-raised-59-million-in-a-token-sale-to-usher-in-the-next-generation-of-crypto-2018-2/?r=US&amp;IR=T">Polymath</a>.</p>
<p>In Asia, the trend is starting to pick up too. For instance, <a target="_blank" href="https://rate3.network">Rate3 Network</a> was funded by various notable Asian VCs that include Matrix Partners China and Fenbushi Capital.</p>
<p>Conceptually, tokenization <em>might seem</em> easy: Issue an ERC-20 token (or any other blockchain tokens), imbue legal rights and ownership rights in the tokens, and you can trade them easily. However, this warrants a much deeper look: how do you distinguish claim rights and ownership rights? What are the differences in tokenization between different asset classes? What is impeding tokenization from adoption?</p>
<p>Thinking comprehensively about tokenization requires an understanding of blockchains and smart contracts, legal, finance, and economics. There has already been in-depth research on each of these components.</p>
<p>In this piece, I want to give a comprehensive introduction to tokenization through using real estate as a primary example. Here’s what we’ll discuss:</p>
<ul>
<li><a class="post-section-overview" href="#8381">What <em>exactly</em> is Tokenization?</a> <em>(Is it not just securitization?)</em></li>
<li><a class="post-section-overview" href="#ccc3">What are the <em>real</em> benefits of tokenization?</a> <em>(Why do we even bother?)</em></li>
<li><a class="post-section-overview" href="#9264">What are some of the <em>tougher</em> issues to think about?</a> <em>(How do we ask the right questions?)</em></li>
<li><a class="post-section-overview" href="#57ff">What are the <em>challenges</em> for tokenization?</a> <em>(What’s stopping adoption?)</em></li>
<li><a class="post-section-overview" href="#789d">How will the tokenized <em>future</em> be?</a> <em>(What are some elements?)</em></li>
</ul>
<p><strong>Let’s get started!</strong></p>
<h3 id="heading-what-is-tokenization">What is Tokenization?</h3>
<h4 id="heading-isnt-tokenization-just-securitization">Isn’t Tokenization just securitization?</h4>
<p>For structured finance professionals, tokenization <em>might</em> seem like securitization. In summary, securitization consists of a few steps:</p>
<ol>
<li>Originator (owner of the assets) collects the assets in a pool and transfers the pool to a legal entity (usually a special purpose vehicle). Through this legal structure, assets are not exposed to counter-party risks or risk of bankruptcy of the originator bank</li>
<li>The SPV structures the assets within the pool into several tranches, according to different risk levels and characteristics usually. Securities are issued, and backed by the cash flows generated by the underlying assets.</li>
<li>After issuing the securities, the SPV sells the securities to investors, whilst transferring the proceeds to the originator afterwards.</li>
</ol>
<h4 id="heading-securitization-has-various-flaws"><strong>Securitization</strong> has various flaws.</h4>
<p>The classic <strong>securitization</strong> process is extremely costly and takes up a lot of time. The entire process might cost up to millions of dollars and takes up to a year. The securitization process requires agreements with various parties under conditions of asymmetric information, as well as a heterogeneous structure of asset data.</p>
<p>Furthermore, there might be a lack of full transparency in the various stages of securitization, all of which hinder auditing and rating of the underlying assets. In the sub-prime mortgage crisis, there is no transparency on the credit pool nor the audit process that lead to defaults on the bonds issued.</p>
<h4 id="heading-clearly-tokenization-securitization">Clearly, tokenization =/= securitization</h4>
<p>Tokenization — in its simplest definition — refers to converting an asset into a digital token on the blockchain system. The biggest difference between tokenization and securitization, is how programmability is introduced into the tokenized asset. This way, business logic can be introduced, reducing the need for manual settlements. Smart contracts can have functions for automatic transactions, formulas for calculating asset prices and other specific features.</p>
<h3 id="heading-what-are-the-real-benefits-of-tokenization-then">What are the real benefits of Tokenization then?</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/-W6AlP3OdocdH7XlQG3vxR6Ki2ifpbdwyCfS" alt="Image" width="800" height="532" loading="lazy">
<em>Photo by @sanfrancisco, Unsplash</em></p>
<p>Numerous research pieces have talked about various benefits of tokenization, but these various benefits can be categorized into three core principles: 1) <strong>liquidity</strong>, 2) <strong>programmability</strong> and 3) <strong>immutable proof of ownership</strong>.</p>
<h4 id="heading-key-principle-1-liquidity">Key Principle 1: Liquidity</h4>
<p><a target="_blank" href="http://www3.weforum.org/docs/WEF_GAC15_Technological_Tipping_Points_report_2015.pdf">World Economic Forum</a> predicts that over the next ten years, 10% of the world’s GDP will be stored in crypto assets, amounting to $10 trillion. This is primarily due to increased fractional ownership, and unlocking of liquidity premiums.</p>
<p>Assuming no legal and regulatory barriers, tokenization allows for increased fractional ownership. Most tokens can be broken into 18 decimals, as compared to fiat which can be broken down to $0.01 only. Fractional ownership lowers the barriers of entry for new investors. For instance, instead of paying $1 million for a new apartment, I can pay $50,000 for a tokenized fraction of the real estate. For investors, fractional ownership and lower barriers help them to increase portfolio diversification and construct a “truer” market portfolio.</p>
<p>The increase in liquidity helps unlock value for markets through liquidity premiums. When illiquid assets become more liquid, a <a target="_blank" href="http://people.stern.nyu.edu/adamodar/pdfiles/country/illiquidity.pdf">liquidity premium</a> of approximately ~20–30% is unlocked. One example is real estate: Even a fractional improvement in the sales price of such investments could result in trillions of dollars of new value for issuers and resellers.</p>
<h4 id="heading-key-principle-2-programmability-built-into-tokens">Key Principle 2: Programmability built into tokens</h4>
<p>Programmability refers to the ability to introduce <em>certain</em> business logic into smart contracts, allowing for automated events to occur. Tokenization can also lead to easier management of investors and their rights. Secondary transactions can be easily tracked by collaborating with third-party exchanges, allowing investors to receive distributions and exercise their other rights (e.g., voting) through the blockchain.</p>
<p>Programmability is especially useful in increasing the speed of settlements. In traditional finance, settlements refer to the process of documentation of the transfer of asset ownership before the ownership of assets actually changes hands. Compliance can be programmed into the tokens, if all participants have a digital identity that has gone through the relevant compliance/KYC/AML checks.</p>
<h4 id="heading-key-principle-3-immutable-proof-of-ownership">Key Principle 3: Immutable proof of ownership</h4>
<p>Blockchains are immutable and keep a public trace of every transfer, and owner. This digital trace of transactions not only proves the history of ownership but also helps to ensure less fraud. The immutable structure makes it impossible for a token-holder to “double-sell” a token — accepting a transfer for the same token to two different sources. This helps assure investors that no one can falsify transactions after the transaction has happened.</p>
<h3 id="heading-lets-dive-deeper-into-tokenization">Let’s dive deeper into tokenization.</h3>
<p><em>Tokenization is the process of digitally storing the property rights to a thing of value (asset) on a blockchain or distributed ledger, so that ownership can be transferred via the blockchain’s protocol. What are the other challenges?</em></p>
<h4 id="heading-issue-1-what-are-the-requirements-for-tokenization-to-take-place">Issue #1: What are the requirements for tokenization to take place?</h4>
<p>There are 3 fundamental requirements:</p>
<ol>
<li><strong>The rights to an asset can be stored digitally on a blockchain</strong></li>
</ol>
<p>Let’s go back to the real estate example. If I want to tokenize my house, I must be able to record my ownership of my house on a token itself. This means that to regulatory authorities, holding a token represents an ownership right or claim right on the house itself. <em>(We will go into these rights in a bit.)</em></p>
<p><strong>2. These rights can be legally transferred via blockchains</strong></p>
<p>Whilst I can document my rights to my house in a legally-recognized way, I should be able to transfer these rights to anyone I want and that person will have legal ownership of my house, assuming my tokens are imbued with ownership rights.</p>
<p><strong>3. Tokens can be easily exchanged for value, giving the assets “value”</strong></p>
<p>Lastly, like any security, I must be able to exchange my real estate token for value easily — so I can subscribe value to the asset.</p>
<h4 id="heading-issue-2-what-are-the-other-legal-issues-to-consider">Issue #2: What are the other legal issues to consider?</h4>
<p>Apart from the 3 requirements, what is more crucial to take note is the exact asset you are tokenizing: Does the token represent a claim on the asset or does the token represent actual ownership of the asset itself? Investors and token issuers must think carefully about what exactly a token represents.</p>
<p><strong>The truth is: it depends on what you want to tokenize. Tokenization is flexible.</strong> Using real estate as an example again, what can be tokenized could be direct ownership in the real estate (being a partial equity owner), right to rental income, or even the right to use an asset (renting the apartment).</p>
<p>Hence, a token could represent <em>ownership</em> of the underlying real asset, an <em>interest in a debt</em> secured by the asset, an <em>equity interest</em> in a legal entity that owns that asset, or a <em>right to the cash flow</em> from the asset.</p>
<h3 id="heading-there-are-3-basic-categories-of-rights-to-understand">There are 3 basic categories of rights to understand.</h3>
<p>The rights bestowed by tokenized securities (or security token) can be very complex to understand. However, tokenized securities can include claims to the assets (and usually the resulting cash flows), direct ownership rights, governance rights or a combination of all.</p>
<ol>
<li><strong>Claim rights:</strong> Claims to only certain specific uses (and claims) of the asset</li>
<li><strong>Ownership rights:</strong> Equity ownership and control of the asset</li>
<li><strong>Governance:</strong> System by which a group of people can come to unified decisions</li>
</ol>
<h4 id="heading-lets-illustrate-this-with-real-estate-again-with-a-few-examples-on-the-token-holders-rights">Let’s illustrate this with real estate again, with a few examples on the token holders’ rights:</h4>
<ol>
<li><strong>Claim rights, but no ownership rights</strong>: Token holders are entitled to cash flows from ongoing leases, but they have no ‘equity’ and ‘ownership’ of the underlying real estate</li>
<li><strong>Claim rights, AND ownership rights</strong>: Token holders are the ‘owners’ of the underlying real estate with claims to the cash flows. They can make decisions directly: how much to charge for rent, investments made to maintain the real estate, hiring staff and given the proceeds from the sale of the real estate.</li>
<li><strong>Only ownership rights:</strong> This example is rarely the case, but it means that token holders are now the ‘equity owners’ of the real estate.</li>
</ol>
<h4 id="heading-what-are-the-challenges-that-arise-from-these-different-rights">What are the challenges that arise from these different rights?</h4>
<p>It is possible that there is a separation of claim rights and ownership rights, and this creates misaligned incentives between both parties.</p>
<p><strong>What if… the tokens have ownership rights for token holders?</strong> How do 1,000 token holders make decisions collectively for the best of the assets? Is there a need for delegated voting or decision making?</p>
<p><strong>What if… the tokens only imbue claim rights for token holders?</strong> The token issuers (owners) can reduce profits and cash flows to the token holders, by re-investing the profits. This will be to the detriment of token holders who originally look towards the future cash flow.</p>
<p>The smart contract geek might ask: <em>can’t one automate all these logic in smart contracts?</em></p>
<h3 id="heading-no-smart-contracts-cannot-solve-all-these-issues">No, smart contracts cannot solve all these issues.</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/lP3pwrUqO9p3X0gH66HrJVmelSsIPHUmAh18" alt="Image" width="800" height="458" loading="lazy"></p>
<p>Contracts and smart contracts are <strong><em>incomplete:</em></strong></p>
<ol>
<li><em>Contracts are only enforceable when events and actions can be verified by a third party</em></li>
</ol>
<p>This is the long-standing problem of “<strong><em>oracles</em></strong>” in tokenization. There are some events that can be captured in code, but near impossible for any arbiter to determine if they really happened.</p>
<p>For instance, I issued out real estate tokens to holders so they can receive a portion of the rental income. However, it is possible that I do not document down all the rental agreements so token holders do not know what the real amount of rental income is. If this cannot be enforced effectively, there is no rational reason for parties to abide by the smart contract.</p>
<p><em>2. It is near impossible to write a contract that contains all possible conditions and events, hence achieving “completeness”</em></p>
<p>The problem with contracts is not what is in them, it is what is not in them. It is very costly and operationally challenging to write down every condition and event. Furthermore, events and conditions change in real life — and contracts have to adapt to these real-life changes.</p>
<p>Given the limitations of smart contracts as inherently incomplete, certain asset types should not be tokenized.</p>
<h3 id="heading-what-should-not-be-tokenized">What should not be tokenized?</h3>
<ol>
<li><strong>When the blockchain cannot fully capture the change of ownership of assets</strong></li>
</ol>
<p>There are some assets in markets where I can sell the physical asset outside of the protocol directly, despite it being tokenized. For instance, I can tokenize real estate and transfer the token (with ownership rights) to you, but it is possible I can also legally sell the same real estate to another.</p>
<p>There are also other cases when I can trade tokens, but have no guarantees that I can verify the authenticity of the underlying asset. In the case of real estate, it is easier to verify, but other examples include gold bars. If it takes a lot of costs and resources to verify the authenticity, tokenization might not be a viable solution.</p>
<p><strong>2. When the use of prices impede the protocol from achieving its objectives</strong></p>
<p>There are some situations in which we don’t <em>want</em> prices to determine who gets what. Sometimes, prices do not capture external societal benefits and costs, and might not be the most equitable way to allocate resources. Examples include social goods, for instance.</p>
<p><strong>3. Sometimes, we just <em>do not want</em> to tokenize some ‘assets’ and rights</strong></p>
<p>For instance, rights to birth certificates or educational records should not be tokenized since they represent a <em>unique</em> right. We do not, and should not tokenize these ‘assets’.</p>
<p>Clearly, there are some asset classes that _should no_t be tokenized, given real-life limitations.</p>
<h3 id="heading-how-do-you-really-tokenize">How do you really tokenize?</h3>
<p>We have walked through the <em>what</em> and <em>why of tokenization,</em> now let’s talk a little about the <em>how</em> of tokenization.</p>
<p>There are a few categories of assets that have been tokenized:</p>
<ul>
<li><strong>Fiat currencies</strong></li>
</ul>
<p>The tokenization of fiat currencies gave rise to stablecoins. <a target="_blank" href="https://tether.to">Tether</a> is the first example, creating USDT. However, there are inherent challenges with Tether. For a good, updated summary on stablecoins, I suggest this:</p>
<p><a target="_blank" href="https://blog.goodaudience.com/stablecoins-are-now-officially-in-vogue-again-131383ab8db9"><strong>Stablecoins are now officially in vogue again</strong></a><br><a target="_blank" href="https://blog.goodaudience.com/stablecoins-are-now-officially-in-vogue-again-131383ab8db9">_With seemingly one new project unveiling multi-million-dollar funding every other week, no one will blame you for…_blog.goodaudience.com</a></p>
<ul>
<li><strong>Gold</strong></li>
</ul>
<p>An example of a gold tokenization project is <a target="_blank" href="https://digix.global/dgx/">Digix</a>.</p>
<p>Each DGX token is 1:1 gold-backed, and 1 token represent 1 gram of 99.99% gold from London Bullion Market Association-certified refiners, with gold stored in The Safehouse vault. Purchasing 1 DGX token is equivalent to purchasing actual gold itself.</p>
<ul>
<li><strong>Real Estate</strong></li>
</ul>
<p>My primary interest lies in real estate, given the analogy between REITs and tokenized real estate. A few interesting examples are <a target="_blank" href="https://www.forbes.com/sites/rachelwolfson/2018/10/03/a-first-for-manhattan-30m-real-estate-property-tokenized-with-blockchain/#537f78784895">how a Manhattan real estate property was most recently tokenized</a>, or <a target="_blank" href="https://venturebeat.com/2018/10/09/elevated-returns-gets-18-million-for-st-regis-aspen-resort-tokenized-real-estate/">how a portion of the St. Regis Aspen is tokenized</a>. In the case of St. Regis Aspen, each Aspen token represents an indirect ownership interest in a common stock of the St. Regis Aspen REIT. According to Elevated Returns, the “REIT provides tax efficient structure while the blockchain provides peer-to-peer investing and cross-border transaction made simpler for investors.”</p>
<h3 id="heading-clearly-there-are-many-challenges-associated-with-tokenization">Clearly, there are many challenges associated with tokenization.</h3>
<h4 id="heading-1-lack-of-tokenization-standards-and-legal-infrastructure">1. Lack of tokenization standards and legal infrastructure</h4>
<p>Tokenization is not simply the creation of a token — any Solidity developer can do it. Instead, it’s about the design of the whole system, including understanding the various rights and issues we’ve talked about previously.</p>
<p>How do tokenization standards cater for these issues:</p>
<ul>
<li>Incentives (claim rights, ownership rights, governance)</li>
<li>Privileges of users and system admins (who operate the token contracts)</li>
<li>Life-cycle management of an asset (issuance, payouts, withdrawal)</li>
<li>Security management</li>
<li>Integration of KYC/AML requirements across different jurisdictions</li>
<li>Integration with exchanges</li>
<li>Interoperability between different public chains</li>
</ul>
<p>In the case of cross-chain interoperability, we do see different chains with different nascent characteristics. For instance, Ethereum has scalability issues but provides for more complex Turing-complete smart contracts. How about other public blockchain networks like Stellar or IOST or Zilliqa?</p>
<p><em>How can tokenized assets (in the form of tokens) be interoperable across these different chains?</em></p>
<h4 id="heading-2-digital-identity-thats-globally-and-legally-recognized">2. Digital identity that’s globally and legally-recognized</h4>
<p>From a regulatory point of view, it is a regulatory nightmare for assets to be issued and transferred across citizens of different legal jurisdictions.</p>
<p>Suppose I am an EU resident looking to tokenize my real estate and the token only imbues claim rights. How do I transfer this token to U.S persons, whilst taking into account their identity, KYC/AML issues, U.S regulations, taxes and all the other issues?</p>
<p><em>How can I reasonably and easily deal with a verified, attested U.S person in a legally-compliant way for both our national jurisdictions?</em></p>
<h4 id="heading-3-tokenization-does-not-mean-instant-liquidity">3. Tokenization does not mean instant liquidity</h4>
<p>Liquidity is the biggest challenge in the security token space and it does not happen organically. History has given us various examples of financial markets and instruments that have not yet achieved significant levels of liquidity. Helping to create liquidity through allowing institutional investors or accredited retail investors — through custodian solutions will be key. Of course, the underlying asset must be useful.</p>
<p><em>How do we introduce long-term, sustainable solutions for large institutional investors — the market makers — to create and maintain liquidity?</em></p>
<h3 id="heading-what-does-a-tokenized-future-look-like">What does a tokenized future look like?</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/VROVXufGdaPXFsGlBxX3mnk1zyqtHrnrX0Wi" alt="Image" width="800" height="519" loading="lazy"></p>
<p>I’m generally bullish on a tokenized future: a fairer, more equitable world with lower barrier to entry and capital requirements for individuals or businesses.</p>
<p>Through capturing value in tokenized assets, we can re-create all the sophistication of the existing financial and operational world we live in, with far less operational costs and complexities. When combining tokenization with reasonably complex business logic enabled by smart contracts, we can represent complex business interactions faithfully and more efficiently.</p>
<h4 id="heading-there-will-be-interoperability-through-standardization">There will be interoperability, through standardization</h4>
<p><strong>ERC 20 for token standards, as an example</strong></p>
<p>If the ecosystem for global assets becomes interoperable, it means we can hold ownership claims to a commercial building, early-stage equity, corporate bonds, a T-bill, a single-family residence, and a decentralized network on the same platform.</p>
<p>Different assets can reference each other contractually and interact in an automated way. It means an increased liquidity for all (tokenized) asset classes.</p>
<p><strong>ERC 725 for Identity, as another</strong></p>
<p><a target="_blank" href="https://twitter.com/feindura?lang=en">Fabian Vogelstellar</a> — creator of the ERC 20 standard — is leading the front for a unique decentralized identity for “humans, groups, objects and machines”. Quoting directly from the ERC 725 Github itself, “ This identity can hold keys to sign actions (transactions, documents, logins, access, etc), and claims, which are attested from third parties (issuers) and self-attested (<a target="_blank" href="https://github.com/ethereum/EIPs/issues/735">#ERC735</a>), as well as a proxy function to act directly on the blockchain”.</p>
<p>You can read more here about <em>ERC 725</em> here:</p>
<p><a target="_blank" href="https://github.com/ethereum/EIPs/issues/725"><strong>ERC: Identity · Issue #725 · ethereum/EIPs</strong></a><br><a target="_blank" href="https://github.com/ethereum/EIPs/issues/725">_eip: title: ERC-725 Identity author: Fabian Vogelsteller (@frozeman) discussions-to…_github.com</a></p>
<p>There are notable projects that have been working on implementing ERC 725 identity contracts. A few examples are: <a target="_blank" href="https://www.originprotocol.com/en">Origin Protocol</a> and <a target="_blank" href="https://rate3.network">Rate3 Network</a>.</p>
<p><a target="_blank" href="https://medium.com/originprotocol/managing-identity-with-a-ui-for-erc-725-5c7422b38c09"><strong>Managing Identity with a UI for ERC 725</strong></a><br><a target="_blank" href="https://medium.com/originprotocol/managing-identity-with-a-ui-for-erc-725-5c7422b38c09">_At Origin, we’re building a platform for decentralized, peer-to-peer marketplaces. You can imagine a future Airbnb-like…_medium.com</a><a target="_blank" href="https://medium.com/official-rate3/rate3-cross-chain-identity-protocol-identity-and-claims-erc-725-erc735-c6e51f422e7b"><strong>Rate3 Cross-Chain Identity Protocol — Identity and Claims (ERC 725, ERC735)</strong></a><br><a target="_blank" href="https://medium.com/official-rate3/rate3-cross-chain-identity-protocol-identity-and-claims-erc-725-erc735-c6e51f422e7b">_At Rate3, we initially wanted to build a blockchain-based settlement and clearance network for businesses. We…_medium.com</a></p>
<h3 id="heading-the-future-of-tokenization-is-not-here-yet-but-it-will-be-sooner-than-we-know">The future of tokenization is not here (yet), but it will be sooner than we know</h3>
<p>We are optimistic and bullish for the future of tokenization and tokenized securities. There are many elements of the envisioned tokenized future that we observe today:</p>
<ol>
<li><strong>Governments are increasingly partnering with private companies to create infrastructural solutions</strong></li>
</ol>
<p>One such example is the collaboration between <em>NASDAQ</em>, <em>Monetary Authority of Singapore</em> (Singapore’s Central Bank) and <em>Singapore Exchange</em> (Singapore’s main stock exchange) to develop Delivery versus Payment capabilities for settlement of tokenized assets across different blockchain platforms to improve operational efficiency and reduce settlement risks.</p>
<p><a target="_blank" href="http://www.mas.gov.sg/News-and-Publications/Media-Releases/2018/MAS-and-SGX-partner-Anquan-Deloitte-and-Nasdaq-to-harness-blockchain-technology.aspx"><strong>MAS and SGX partner Anquan Deloitte and Nasdaq to harness blockchain technology</strong></a><br><a target="_blank" href="http://www.mas.gov.sg/News-and-Publications/Media-Releases/2018/MAS-and-SGX-partner-Anquan-Deloitte-and-Nasdaq-to-harness-blockchain-technology.aspx">_Singapore, 24 August 2018… The Monetary Authority of Singapore (MAS) and Singapore Exchange (SGX) today announced a…_www.mas.gov.sg</a></p>
<ol start="2">
<li><strong>Projects have recognized the need for compliance, and are creating solutions that target automated compliance and AML/KYC</strong></li>
</ol>
<p>We have touched about the need to meld real-world legal requirements into the blockchain space. There are various projects that have been doing these globally:</p>
<ol>
<li><a target="_blank" href="https://harbor.com/"><strong>Harbor</strong></a>: <em>A compliance platform and protocol to ensure tokenized securities comply with existing securities laws at issuance and on every trade, everywhere across the globe.</em></li>
<li><a target="_blank" href="https://rate3.network"><strong>Rate3 Network</strong></a>: <em>A protocol that handles asset-tokenization and identity management across both Ethereum and Stellar blockchains.</em></li>
<li><a target="_blank" href="https://polymath.network/"><strong>Polymath:</strong></a> <em>A security token platform on which regulatory-compliant tokens can be built</em></li>
</ol>
<p>I do notice more blockchain projects building tokenization solutions targeted at different asset classes, different ways of modeling structured finance through issuing both debt and equity tokens, for instance. More importantly, these solutions know that working directly with regulatory authorities, collaborating with central banks and other projects will help to improve the overall ecosystem.</p>
<p>Ensuring the legally-compliant design of the whole system is key.</p>
<p><strong>3. “Paths of least resistance” will help everyone relate existing real examples to upcoming tokenization projects</strong></p>
<p>Real estate have always been quoted as an example for tokenization projects. This is due to the structure of real estate investment trusts (REITs), that one could relate more easily to tokenized structures.</p>
<p>Tokenized real estate is <em>not</em> REITs, but there are various principles we can use to help us understand, relate and think better: property rights, economics for REITs for instance.</p>
<p><em>Not everything will be tokenized, but those that can be will be.</em></p>
<p><em>Disclosure: I work at <a target="_blank" href="https://www.rate3.network/">Rate3 Network</a>, a dual-protocol that handles asset-tokenization and identity management across both Ethereum and Stellar blockchains.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Every blockchain developer should know these Web3 and Metamask use cases ]]>
                </title>
                <description>
                    <![CDATA[ By Igor Yalovoy Update On November 2nd MetaMask and other dapp browsers will stop exposing user accounts by default. This will make some code from this paper to break. I will publish updated version with web3 1.0 and new MetaMask interface. Metamask ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/every-blockchain-developer-should-know-these-web3-and-metamask-use-cases-7f93c1f139b1/</link>
                <guid isPermaLink="false">66c349eaa1d481faeda49b2b</guid>
                
                    <category>
                        <![CDATA[ Blockchain ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web3 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 15 Oct 2018 19:00:24 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*JVmq6javfae3gzTA.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Igor Yalovoy</p>
<h3 id="heading-update">Update</h3>
<p>On <a target="_blank" href="https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8">November 2nd</a> MetaMask and other dapp browsers will stop exposing user accounts by default. This will make some code from this paper to break. I will publish updated version with web3 1.0 and new MetaMask interface.</p>
<p><a target="_blank" href="https://ylv.io/10-web3-metamask-use-cases-ever-blockchain-developer-needs/Metamask.io">Metamask</a> is the de facto standard for dApps on the web. It injects a Web3 instance into a window object making it available for JavaScript code.</p>
<p>We are going to use Web3 0.20 version, not Web3 1.0. The code for Web3 1.0 would be different.</p>
<p>Every dApp has its mission, but the way they interact with Metamask is similar. In this article, we’ll cover the ten most common practices to handle Web3/Metamask interactions.</p>
<h3 id="heading-1-detect-metamask-and-instantiate-web3">#1. Detect Metamask and instantiate Web3</h3>
<p>According to <a target="_blank" href="https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#partly_sunny-web3---ethereum-browser-environment-check">docs</a>, here’s the best way to do it.</p>
<p>What is going on here? First, we check if Web3 was injected. If it is injected we create a new instance using the injected provider. Why is that? Because we want to use our library version, not the one injected by Metamask.</p>
<p>If Web3 is not present, we try to connect to a localhost provider, like <a target="_blank" href="https://truffleframework.com/ganache">ganache</a>.</p>
<h3 id="heading-2-check-if-metamask-is-locked">#2. Check if Metamask is locked</h3>
<p>Metamask can be installed but locked. In order to interact with a user account and send transactions, the user has to unlock Metamask.</p>
<h3 id="heading-3-check-the-current-network">#3. Check the current network</h3>
<p>There are many test networks beyond the main network. Typically your contract is deployed to a certain network. You want to be sure that the user runs Metamask on the same network.</p>
<h3 id="heading-4-get-the-current-account">#4. Get the current account</h3>
<p>A user may have multiple accounts at Metamask, but they expect the dApp to interact with the current one.</p>
<p>You should always grab the account from the Web3 instance. Do not keep and reuse it, because the user may change their account at any time.</p>
<h3 id="heading-5-get-the-balance-on-the-current-account">#5. Get the balance on the current account</h3>
<p>Here we use the function <code>getAccount</code> from #4 and call <code>getBalance</code>. Easy.</p>
<h3 id="heading-6-detect-that-the-current-account-has-changed">#6. Detect that the current account has changed</h3>
<p>A user may change their account at any time. You dApp should be ready for that and react properly.</p>
<h3 id="heading-7-detect-whether-metamask-is-lockedunlocked">#7. Detect whether Metamask is locked/unlocked</h3>
<p>Similar to #6. A user may lock/unlock anytime. Your dApp should handle it correctly.</p>
<h3 id="heading-8-handle-cancelconfirm">#8. Handle cancel/confirm</h3>
<p>Once a user interacts with your dApp, you have to send a transaction using the Web3 API. A user may press the cancel or confirm button on the Metamask popup. This may lead to UI inconsistency if not handled correctly.</p>
<p>In order to return instantly with the transaction hash, call <code>contract.methodName.sendTransaction</code>.</p>
<h3 id="heading-9-get-the-transaction-receipt">#9. Get the transaction receipt</h3>
<p>Once your dApp transaction is mined, a transaction receipt becomes available. Yet there is no event/notification, so we have to implement a poll mechanism.</p>
<h3 id="heading-10-listen-for-web3-events">#10. Listen for Web3 events</h3>
<p>Solidity events are great. They allow switching from ugly polling to just a push mechanism, assuming your contract implements all necessary events. You can completely avoid polling and just react to events. Event callback <a target="_blank" href="https://github.com/ethereum/wiki/wiki/JavaScript-API#callback-return">returns</a> a lot of data, but we are mostly interested in <code>args</code>.</p>
<h3 id="heading-summary">Summary</h3>
<p>Whatever your dApp is about, it still has to perform common tasks, such as detecting Web3, getting the account state and balance, recognizing the current network, and handling transactions and events. We’ve gone over how it can be done using ten code snippets.</p>
<h3 id="heading-ps">P.S.</h3>
<p>A lot of examples here use methods which might throw an error because of Metamask’s state or some variables being undefined at the moment of a call. You should wrap them in <code>try/catch</code> in a production environment.<br> Async/await has been used here for simplicity. It can be replaced with Promise then/catch.</p>
<h3 id="heading-social">Social</h3>
<ul>
<li>Connect with me on <a target="_blank" href="https://www.linkedin.com/in/ylv-io/">LinkedIn</a>.</li>
<li>Follow me on <a target="_blank" href="https://twitter.com/ylv_io">twitter</a>.</li>
</ul>
<h3 id="heading-want-more">Want More?</h3>
<p><a target="_blank" href="https://hackernoon.com/how-to-create-and-deploy-your-own-eos-token-1f4c9cc0eca1"><strong>How to Create and Deploy Your Own EOS Token</strong></a><br><a target="_blank" href="https://hackernoon.com/how-to-create-and-deploy-your-own-eos-token-1f4c9cc0eca1">_We are going to figure out what is EOS token and how you can create and deploy one yourself._hackernoon.com</a><a target="_blank" href="https://hackernoon.com/how-much-does-it-costs-to-run-dapp-in-2018-87ee11fe1d5d"><strong>How Much Does It Cost to Run DApp in 2018</strong></a><br><a target="_blank" href="https://hackernoon.com/how-much-does-it-costs-to-run-dapp-in-2018-87ee11fe1d5d">_You think your AWS or Digital Ocean bill for your website is killing you?_hackernoon.com</a><a target="_blank" href="https://medium.com/coinmonks/difference-between-ethereum-and-eos-tokens-f2399051c0b6"><strong>Difference Between Ethereum and EOS Tokens</strong></a><br><a target="_blank" href="https://medium.com/coinmonks/difference-between-ethereum-and-eos-tokens-f2399051c0b6">_Ethereum has ERC-20 token and EOS has EOSIO.Token. They serve the same purpose, but are they the same?_medium.com</a></p>
<p><em>Originally published at <a target="_blank" href="https://ylv.io/10-web3-metamask-use-cases-ever-blockchain-developer-needs/">ylv.io</a> on October 15, 2018.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to implement Dependency Injection in your app with Dagger 2 ]]>
                </title>
                <description>
                    <![CDATA[ By Andrius Baruckis Kriptofolio app series - Part 4 Dependency injection will significantly improve your code. It makes your code more modular, flexible and testable. Actually its name sounds more complicated than the idea which stands behind it. In ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/kriptofolio-app-series-part-4/</link>
                <guid isPermaLink="false">66d45ddca3a4f04fb2dd2e35</guid>
                
                    <category>
                        <![CDATA[ Android ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Kotlin ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 07 Oct 2018 09:35:06 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*CVSY-XyHRtZZJd2lDV-ZZw.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Andrius Baruckis</p>
<h4 id="heading-kriptofolio-app-series-part-4">Kriptofolio app series - Part 4</h4>
<p>Dependency injection will significantly improve your code. It makes your code more modular, flexible and testable. Actually its name sounds more complicated than the idea which stands behind it.</p>
<p>In this part of the series we are going to learn about dependency injection. We will then implement it in “Kriptofolio” (previously “My Crypto Coins”) app. We are going to use Dagger 2. Dagger 2 is the most popular open-source dependency injection framework for Android. This is a valuable skill to have for creating modern apps, even thought the learning curve is hard enough.</p>
<h3 id="heading-series-content">Series content</h3>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series">Introduction: A roadmap to build a modern Android app in 2018–2019</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series-part-1">Part 1: An introduction to the SOLID principles</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series-part-2">Part 2: How to start building your Android app: creating Mockups, UI, and XML layouts</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series-part-3">Part 3: All about that Architecture: exploring different architecture patterns and how to use them in your app</a></li>
<li>Part 4: How to implement Dependency Injection in your app with Dagger 2 (you’re here)</li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/kriptofolio-app-series-part-5">Part 5: Handle RESTful Web Services using Retrofit, OkHttp, Gson, Glide and Coroutines</a></li>
</ul>
<h3 id="heading-what-is-dependency-injection">What is Dependency Injection?</h3>
<p>To explain dependency injection first we have to understand what dependency means in programming. A dependency is when one of the objects depends on the concrete implementation of another object. You can identify a dependency in your code whenever you instantiate an object within another. Let’s take a look at a practical example.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyAppClass</span></span>() {

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> library: MyLibrary = MyLibrary(<span class="hljs-literal">true</span>)
    ...
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyLibrary</span></span>(<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> useSpecialFeature: <span class="hljs-built_in">Boolean</span>) {

    ...
}
</code></pre>
<p>As you see from this example your class <code>MyAppClass</code> will depend directly on concrete configuration and implementation of your library class <code>MyLibrary</code>. What if you would like one day to use a third-party library instead? What if you would like to have another class where you would like to use exactly the same library configuration? Every time you will have to search through your code, find exact place and change it. It’s just a few examples.</p>
<p>The idea is that this tight coupling between the components of the application will make your development work harder as your project grows. To avoid any problems, let’s use dependency injection for loosening the coupling described.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyAppClass</span></span>(<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> library: MyLibrary) {

    ...
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyLibrary</span></span>(<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> useSpecialFeature: <span class="hljs-built_in">Boolean</span>) {

    ...
}
</code></pre>
<p>That’s it, that’s a very primitive dependency injection example. Instead of creating and configuring a new <code>MyLibrary</code> class object inside your class <code>MyAppClass</code>, you just pass or inject it into the constructor. So <code>MyAppClass</code> can be totally irresponsible for <code>MyLibrary</code>.</p>
<h3 id="heading-what-is-dagger-2">What is Dagger 2?</h3>
<p>Dagger is a fully static, compile-time, open-source dependency injection framework for both Java and Android. In this article I will be talking about its second version which Google maintains. Square created its earlier version.</p>
<p>Dagger 2 is considered to be one of the most efficient dependency injection frameworks built to date. Actually if you compare Dagger 1, Dagger 2 and Dagger 2.10 you would discover each implementation is different. You need to relearn it each time as there were significant changes done by the authors. When writing this article I am using Dagger 2.16 version and we are going to focus only on it.</p>
<p>As you now understand about dependency injection, our classes should not create or have dependencies. Instead they need to get everything from outside. So when using Dagger 2, this framework will provide all the dependencies needed.</p>
<p>It does this by generating a lot of boilerplate code for us. That generated code will be fully traceable and will mimic the code which a user may write by hand. Dagger 2 is written in Java and the code generated by its annotation processor will be Java code too.</p>
<p>However it works with Kotlin without any problems or modifications. Remember that Kotlin is fully interoperable with Java. If compared to similar frameworks, Dagger 2 is a less dynamic one. It works at compile time rather than at run-time with reflection. There is no reflection usage at all. All that means is that this framework will be harder to set up and to learn. It will provide performance boost with compile-time safety.</p>
<h3 id="heading-manual-dependency-injection-without-tools">Manual Dependency Injection without tools</h3>
<p>You may have noticed in the My Crypto Coins app <a target="_blank" href="https://github.com/baruckis/Kriptofolio/tree/Part-3">source code from the previous part</a> that there is a piece of code for injecting objects without using any dependency injection tools. It works fine, and this solution would be good enough for such a small app like this. Take a look at the utilities package:</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * Static methods used to inject classes needed for various Activities and Fragments.
 */</span>
<span class="hljs-keyword">object</span> InjectorUtils {

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getCryptocurrencyRepository</span><span class="hljs-params">(context: <span class="hljs-type">Context</span>)</span></span>: CryptocurrencyRepository {
        <span class="hljs-keyword">return</span> CryptocurrencyRepository.getInstance(
                AppDatabase.getInstance(context).cryptocurrencyDao())
    }

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">provideMainViewModelFactory</span><span class="hljs-params">(
            application: <span class="hljs-type">Application</span>
    )</span></span>: MainViewModelFactory {
        <span class="hljs-keyword">val</span> repository = getCryptocurrencyRepository(application)
        <span class="hljs-keyword">return</span> MainViewModelFactory(application, repository)
    }

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">provideAddSearchViewModelFactory</span><span class="hljs-params">(
            context: <span class="hljs-type">Context</span>
    )</span></span>: AddSearchViewModelFactory {
        <span class="hljs-keyword">val</span> repository = getCryptocurrencyRepository(context)
        <span class="hljs-keyword">return</span> AddSearchViewModelFactory(repository)
    }
}
</code></pre>
<p>As you see this class will do all the work. It will create ViewModel factories for activities or fragments that require them.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * Factory for creating a [MainViewModel] with a constructor that takes a
 * [CryptocurrencyRepository].
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainViewModelFactory</span></span>(<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> application: Application, <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> repository: CryptocurrencyRepository) : ViewModelProvider.NewInstanceFactory() {

    <span class="hljs-meta">@Suppress(<span class="hljs-meta-string">"UNCHECKED_CAST"</span>)</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-type">&lt;T : ViewModel?&gt;</span> <span class="hljs-title">create</span><span class="hljs-params">(modelClass: <span class="hljs-type">Class</span>&lt;<span class="hljs-type">T</span>&gt;)</span></span>: T {
        <span class="hljs-keyword">return</span> MainViewModel(application, repository) <span class="hljs-keyword">as</span> T
    }

}
</code></pre>
<p>Then you use <code>InjectorUtils</code> class like this where you need to get a specific ViewModel factory:</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * A placeholder fragment containing a simple view.
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainListFragment</span> : <span class="hljs-type">Fragment</span></span>() {

    ...

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> viewModel: MainViewModel

    ...

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onActivityCreated</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {

        <span class="hljs-keyword">super</span>.onActivityCreated(savedInstanceState)

        setupList()
        ...
    }

    ...

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">subscribeUi</span><span class="hljs-params">(activity: <span class="hljs-type">FragmentActivity</span>)</span></span> {

        <span class="hljs-comment">// This is the old way how we were injecting code before using Dagger.</span>
        <span class="hljs-keyword">val</span> factory = InjectorUtils.provideMainViewModelFactory(activity.application)

        <span class="hljs-comment">// Obtain ViewModel from ViewModelProviders, using parent activity as LifecycleOwner.</span>
        viewModel = ViewModelProviders.of(activity, factory).<span class="hljs-keyword">get</span>(MainViewModel::<span class="hljs-keyword">class</span>.java)

        ...
    }

}
</code></pre>
<p>As you see our <code>MainListFragment</code> class don’t even know about <code>CryptocurrencyRepository</code> or <code>AppDatabase</code>. It gets a successfully constructed factory from InjectorUtils class. Actually this is one simple way to do it. We are going to get rid of it and learn how to setup Dagger 2 tool for advanced dependency injection. If this app would expand in functionality and code, I don’t doubt we would start seeing benefits really fast of using a professional dependency injection framework over a manual solution.</p>
<p>So let’s delete <code>InjectorUtils</code> class right now and learn how to setup Dagger 2 in My Crypto Coins app source code.</p>
<h3 id="heading-dependency-injection-for-mvvm-with-kotlin">Dependency Injection for MVVM with Kotlin</h3>
<h4 id="heading-how-to-setup-dagger-2-with-viewmodels-activities-and-fragments">How to setup Dagger 2 with ViewModels, Activities and Fragments</h4>
<p>Now we’ll go through the Dagger 2 step by step setup on the My Crypto Coins app project.</p>
<p><strong>To begin, you should enable Kotlin’s own <a target="_blank" href="https://kotlinlang.org/docs/reference/kapt.html">Annotation Processing Tool</a> (kapt). Then add special Dagger 2 dependencies.</strong></p>
<p>You can do this by adding these lines to your gradle file:</p>
<pre><code class="lang-gradle">apply plugin: 'kotlin-kapt' // For annotation processing

...

implementation "com.google.dagger:dagger:$versions.dagger"
implementation "com.google.dagger:dagger-android:$versions.dagger"
implementation "com.google.dagger:dagger-android-support:$versions.dagger"
kapt "com.google.dagger:dagger-compiler:$versions.dagger"
kapt "com.google.dagger:dagger-android-processor:$versions.dagger"
</code></pre>
<p>Kapt plugin will enable the compiler to generate stub classes required for interoperability between Java and Kotlin. For convenience we will define the concrete Dagger 2 version in a separate gradle file, as we do that with all our dependencies.</p>
<pre><code class="lang-gradle">def versions = [:]

versions.dagger = "2.16"

ext.versions = versions
</code></pre>
<p>To find the latest version available check the releases at <a target="_blank" href="https://github.com/google/dagger">Dagger 2's official repository on Github</a>.</p>
<p><strong>Now, create your application <code>App</code> class.</strong></p>
<p>Skip this if you already have this class set. After you’ve done that, we will leave it as it is for a while, but come back later.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> : <span class="hljs-type">Application</span></span>() {

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">super</span>.onCreate()
    }

}
</code></pre>
<p>For My Crypto Coins app, we already have created the application class earlier.</p>
<p><strong>Next, update your manifest file to enable your <code>App</code> class.</strong></p>
<p>Skip this if you have already done that before.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">manifest</span> <span class="hljs-attr">xmlns:android</span>=<span class="hljs-string">"http://schemas.android.com/apk/res/android"</span>
    <span class="hljs-attr">package</span>=<span class="hljs-string">"com.baruckis.mycryptocoins"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">application</span>
        <span class="hljs-attr">android:name</span>=<span class="hljs-string">".App"</span>
        <span class="hljs-attr">android:allowBackup</span>=<span class="hljs-string">"true"</span>
        <span class="hljs-attr">android:icon</span>=<span class="hljs-string">"@mipmap/ic_launcher"</span>
        <span class="hljs-attr">android:label</span>=<span class="hljs-string">"@string/app_name"</span>
        <span class="hljs-attr">...</span></span>
</code></pre>
<p>For My Crypto Coins app, we’ve also already set the <code>App</code> class in the manifest earlier.</p>
<p><strong>Now let’s create a new package called <code>dependencyinjection</code>.</strong></p>
<p>Here we are going to keep all the files related to Dagger implementation.</p>
<p><strong>Create <code>AppModule</code> class module which will provide dependencies all over your application.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * AppModule will provide app-wide dependencies for a part of the application.
 * It should initialize objects used across our application, such as Room database, Retrofit, Shared Preference, etc.
 */</span>
<span class="hljs-meta">@Module(includes = [ViewModelsModule::class])</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppModule</span></span>() {

    <span class="hljs-meta">@Singleton</span> <span class="hljs-comment">// Annotation informs Dagger compiler that the instance should be created only once in the entire lifecycle of the application.</span>
    <span class="hljs-meta">@Provides</span> <span class="hljs-comment">// Annotation informs Dagger compiler that this method is the constructor for the Context return type.</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">provideContext</span><span class="hljs-params">(app: <span class="hljs-type">App</span>)</span></span>: Context = app <span class="hljs-comment">// Using provide as a prefix is a common convention but not a requirement.</span>

    <span class="hljs-meta">@Singleton</span>
    <span class="hljs-meta">@Provides</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">provideCryptocurrencyRepository</span><span class="hljs-params">(context: <span class="hljs-type">Context</span>)</span></span>: CryptocurrencyRepository {
        <span class="hljs-keyword">return</span> CryptocurrencyRepository.getInstance(AppDatabase.getInstance(context).cryptocurrencyDao())
    }
}
</code></pre>
<p>As you see, to create a Dagger module we need to annotate it with the special <code>@Module</code> annotation. Projects usually have multiple Dagger modules. It is typical for one of them to provide app-wide dependencies. This <code>AppModule</code> will be used to initialize objects used across our application, such as Room database, Retrofit, Shared Preference, etc.</p>
<p>As an example, we could discuss a very common scenario for AppModule to provide a Context object in case we need it to get access to it anywhere in our app. Let’s analyze the code to see how to do that.</p>
<p>We need to use a special Dagger annotation <code>@Provides</code>. It tells Dagger that the method provides a specific type of dependency, in our case, a Context object. So when somewhere in the app we request to inject a Context, AppModule is the place where Dagger finds it. And it does not matter the names of our methods, as Dagger cares only about the return type. It is only common practice to name the method with provide prefix, but it can be anything you want.</p>
<p>The <code>@Singleton</code> annotation which you see applied to the same method is not part of the Dagger annotations. It is contained inside the javax package. This annotation tells Dagger that there should only be a single instance of that dependency.</p>
<p>You don’t need to write the boilerplate code to check if another instance of the object is already available. When generating the code Dagger will handle all that logic for you because of this annotation. Notice that our AppModule includes another module ViewModelsModule. Let’s create it now.</p>
<p><strong>Create a <code>ViewModelsModule</code> class module. This module will be responsible for providing ViewModels all over your application.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * Will be responsible for providing ViewModels.
 */</span>
<span class="hljs-meta">@Module</span>
<span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ViewModelsModule</span> </span>{

    <span class="hljs-comment">// We'd like to take this implementation of the ViewModel class and make it available in an injectable map with MainViewModel::class as a key to that map.</span>
    <span class="hljs-meta">@Binds</span>
    <span class="hljs-meta">@IntoMap</span>
    <span class="hljs-meta">@ViewModelKey(MainViewModel::class)</span> <span class="hljs-comment">// We use a restriction on multibound map defined with @ViewModelKey annotation, and if don't need any, we should use @ClassKey annotation provided by Dagger.</span>
    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">bindMainViewModel</span><span class="hljs-params">(mainViewModel: <span class="hljs-type">MainViewModel</span>)</span></span>: ViewModel

    <span class="hljs-meta">@Binds</span>
    <span class="hljs-meta">@IntoMap</span>
    <span class="hljs-meta">@ViewModelKey(AddSearchViewModel::class)</span>
    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">bindAddSearchViewModel</span><span class="hljs-params">(addSearchViewModel: <span class="hljs-type">AddSearchViewModel</span>)</span></span>: ViewModel

    <span class="hljs-meta">@Binds</span>
    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">bindViewModelFactory</span><span class="hljs-params">(factory: <span class="hljs-type">ViewModelFactory</span>)</span></span>: ViewModelProvider.Factory
}
</code></pre>
<p>This module uses Dagger 2 feature map multi bindings. Using it, we contribute objects of our choosing into a map that becomes injectable anywhere in our app. Using the combination of Dagger annotations <code>@Binds</code>, <code>@IntoMap</code> and our custom annotation <code>@ViewModelKey</code>(this one we are going to create), we create an entry inside our map with key <code>MainViewModel::class</code> and value <code>MainViewModel</code> instance. We bind specific factory with the help of some common <code>ViewModelFactory</code> class. We need to create this class.</p>
<p><strong>Create a custom annotation class <code>ViewModelKey</code>.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * An annotation class which tells dagger that it can be used to determine keys in multi bound maps.
 */</span>
<span class="hljs-meta">@MustBeDocumented</span>
<span class="hljs-meta">@Target(
        AnnotationTarget.FUNCTION,
        AnnotationTarget.PROPERTY_GETTER,
        AnnotationTarget.PROPERTY_SETTER
)</span>
<span class="hljs-meta">@Retention(AnnotationRetention.RUNTIME)</span>
<span class="hljs-meta">@MapKey</span>
<span class="hljs-keyword">annotation</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ViewModelKey</span></span>(<span class="hljs-keyword">val</span> value: KClass&lt;<span class="hljs-keyword">out</span> ViewModel&gt;) <span class="hljs-comment">// We might use only those classes which inherit from ViewModel.</span>
</code></pre>
<p>This class is used for binding ViewModels in the <code>ViewModelsModule</code>. The specific annotation <code>@ViewModelKey</code> represents the key of our map. Our key can be only a class that inherits from <code>ViewModel</code>.</p>
<p><strong>Create the <code>ViewModelFactory</code> class.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * Factory to auto-generate a Class to Provider Map.
 * We use Provider&lt;T&gt; to create an injectable object at a later time.
 */</span>
<span class="hljs-meta">@Suppress(<span class="hljs-meta-string">"UNCHECKED_CAST"</span>)</span>
<span class="hljs-meta">@Singleton</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ViewModelFactory</span> <span class="hljs-meta">@Inject</span> <span class="hljs-keyword">constructor</span></span>(<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> viewModelsMap: Map&lt;Class&lt;<span class="hljs-keyword">out</span> ViewModel&gt;,
        <span class="hljs-meta">@JvmSuppressWildcards</span> Provider&lt;ViewModel&gt;&gt;) : ViewModelProvider.Factory {

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-type">&lt;T : ViewModel&gt;</span> <span class="hljs-title">create</span><span class="hljs-params">(modelClass: <span class="hljs-type">Class</span>&lt;<span class="hljs-type">T</span>&gt;)</span></span>: T {
        <span class="hljs-keyword">var</span> creator: Provider&lt;<span class="hljs-keyword">out</span> ViewModel&gt;? = viewModelsMap[modelClass]
        <span class="hljs-keyword">if</span> (creator == <span class="hljs-literal">null</span>) {
            <span class="hljs-keyword">for</span> (entry <span class="hljs-keyword">in</span> viewModelsMap.entries) {
                <span class="hljs-keyword">if</span> (modelClass.isAssignableFrom(entry.key)) {
                    creator = entry.value
                    <span class="hljs-keyword">break</span>
                }
            }
        }
        <span class="hljs-keyword">if</span> (creator == <span class="hljs-literal">null</span>) {
            <span class="hljs-keyword">throw</span> IllegalArgumentException(<span class="hljs-string">"Unknown model class <span class="hljs-variable">$modelClass</span>"</span>)
        }

        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">return</span> creator.<span class="hljs-keyword">get</span>() <span class="hljs-keyword">as</span> T
        } <span class="hljs-keyword">catch</span> (e: Exception) {
            <span class="hljs-keyword">throw</span> RuntimeException(e)
        }
    }
}
</code></pre>
<p>This <code>ViewModelFactory</code> is a utility class which helps you dynamically create ViewModels. Here you provide the generated map as an argument. The <code>create()</code> method will be able to pick the right instance from the map.</p>
<p><strong>Create the <code>ActivityBuildersModule</code> class module.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * All activities intended to use Dagger <span class="hljs-doctag">@Inject</span> should be listed here.
 */</span>
<span class="hljs-meta">@Module</span>
<span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ActivityBuildersModule</span> </span>{

    <span class="hljs-meta">@ContributesAndroidInjector(modules = [MainListFragmetBuildersModule::class])</span> <span class="hljs-comment">// Where to apply the injection.</span>
    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">contributeMainActivity</span><span class="hljs-params">()</span></span>: MainActivity

    <span class="hljs-meta">@ContributesAndroidInjector</span>
    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">contributeAddSearchActivity</span><span class="hljs-params">()</span></span>: AddSearchActivity
}
</code></pre>
<p>This module is responsible for constructing all your activities. It will generate <code>AndroidInjector</code> for all Activities defined in this class. Then objects can be injected into activities using <code>AndroidInjection.inject(this)</code> in the <code>onCreate</code> function from the activity lifecycle. Notice that this module also uses another separate module responsible for fragments. We will create this module next.</p>
<p><strong>Create the <code>MainListFragmetBuildersModule</code> class module.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * All fragments related to MainActivity intended to use Dagger <span class="hljs-doctag">@Inject</span> should be listed here.
 */</span>
<span class="hljs-meta">@Module</span>
<span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainListFragmetBuildersModule</span> </span>{

    <span class="hljs-meta">@ContributesAndroidInjector()</span> <span class="hljs-comment">// Attaches fragment to Dagger graph.</span>
    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">contributeMainListFragment</span><span class="hljs-params">()</span></span>: MainListFragment
}
</code></pre>
<p>This module will build all your fragments related to <code>MainActivity</code>. It will generate <code>AndroidInjector</code> for all Fragments defined in this class. Objects can be injected into Fragments using <code>AndroidSupportInjection.inject(this)</code> in the <code>onAttach</code> function from the fragment lifecycle.</p>
<p><strong>Create the <code>AppComponent</code> class component.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * Singleton component interface for the app. It ties all the modules together.
 * The component is used to connect objects to their dependencies.
 * Dagger will auto-generate DaggerAppComponent which is used for initialization at Application.
 */</span>
<span class="hljs-meta">@Singleton</span>
<span class="hljs-meta">@Component(
        modules = [
            // AndroidSupportInjectionModule is a class of Dagger and we don<span class="hljs-meta-string">'t need to create it.
            // If you want to use injection in fragment then you should use AndroidSupportInjectionModule.class else use AndroidInjectionModule.
            AndroidSupportInjectionModule::class,
            AppModule::class,
            ActivityBuildersModule::class
        ]
)
interface AppComponent {

    @Component.Builder // Used for instantiation of a component.
    interface Builder {

        @BindsInstance // Bind our application instance to our Dagger graph.
        fun application(application: App): Builder

        fun build(): AppComponent
    }

    // The application which is allowed to request the dependencies declared by the modules
    // (by means of the @Inject annotation) should be declared here with individual inject() methods.
    fun inject(app: App)
}</span></span>
</code></pre>
<p>Component is a very important class. It will enable all the above to start working together. It does this by connecting objects to their dependencies. Dagger will use this interface to generate the code necessary to perform the dependency injection.</p>
<p>To create a component class you will need to use Dagger annotation <code>@Component</code>. It takes a list of modules as an input. Another annotation <code>@Component.Builder</code> allows us to bind some instance to component.</p>
<p><strong>Then generate a graph object.</strong></p>
<p>At this moment you have all your modules and your component setup. You can generate your graph object by selecting Build -&gt; Make Module inside your Android Studio IDE. We will need this generation for future steps.</p>
<p><strong>Now create an <code>Injectable</code> interface.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * It is just a plain empty marker interface, which tells to automatically inject activities or fragments if they implement it.
 */</span>
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Injectable</span></span>
</code></pre>
<p>This will also be needed for future steps. <code>Injectable</code> interface should be implemented by activities or fragments which we want to be injectable automatically.</p>
<p><strong>Create a new helper class named <code>AppInjector</code>.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * It is simple helper class to avoid calling inject method on each activity or fragment.
 */</span>
<span class="hljs-keyword">object</span> AppInjector {
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">init</span><span class="hljs-params">(app: <span class="hljs-type">App</span>)</span></span> {
        <span class="hljs-comment">// Here we initialize Dagger. DaggerAppComponent is auto-generated from AppComponent.</span>
        DaggerAppComponent.builder().application(app).build().inject(app)

        app.registerActivityLifecycleCallbacks(<span class="hljs-keyword">object</span> : Application.ActivityLifecycleCallbacks {
            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onActivityPaused</span><span class="hljs-params">(activity: <span class="hljs-type">Activity</span>)</span></span> {

            }

            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onActivityResumed</span><span class="hljs-params">(activity: <span class="hljs-type">Activity</span>)</span></span> {

            }

            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onActivityStarted</span><span class="hljs-params">(activity: <span class="hljs-type">Activity</span>)</span></span> {

            }

            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onActivityDestroyed</span><span class="hljs-params">(activity: <span class="hljs-type">Activity</span>)</span></span> {

            }

            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onActivitySaveInstanceState</span><span class="hljs-params">(activity: <span class="hljs-type">Activity</span>, outState: <span class="hljs-type">Bundle</span>?)</span></span> {

            }

            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onActivityStopped</span><span class="hljs-params">(activity: <span class="hljs-type">Activity</span>)</span></span> {

            }

            <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onActivityCreated</span><span class="hljs-params">(activity: <span class="hljs-type">Activity</span>, savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
                handleActivity(activity)
            }
        })
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">handleActivity</span><span class="hljs-params">(activity: <span class="hljs-type">Activity</span>)</span></span> {
        <span class="hljs-keyword">if</span> (activity <span class="hljs-keyword">is</span> HasSupportFragmentInjector || activity <span class="hljs-keyword">is</span> Injectable) {
            <span class="hljs-comment">// Calling inject() method will cause Dagger to locate the singletons in the dependency graph to try to find a matching return type.</span>
            <span class="hljs-comment">// If it finds one, it assigns the references to the respective fields.</span>
            AndroidInjection.inject(activity)
        }

        <span class="hljs-keyword">if</span> (activity <span class="hljs-keyword">is</span> FragmentActivity) {
            activity.supportFragmentManager.registerFragmentLifecycleCallbacks(<span class="hljs-keyword">object</span> : FragmentManager.FragmentLifecycleCallbacks() {
                <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onFragmentCreated</span><span class="hljs-params">(fragmentManager: <span class="hljs-type">FragmentManager</span>, fragment: <span class="hljs-type">Fragment</span>, savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
                    <span class="hljs-keyword">if</span> (fragment <span class="hljs-keyword">is</span> Injectable) {
                        AndroidSupportInjection.inject(fragment)
                    }
                }
            }, <span class="hljs-literal">true</span>)
        }
    }

}
</code></pre>
<p>It is just a simple helper class to avoid calling the inject method on each activity or fragment.</p>
<p><strong>Next, setup the <code>App</code> class which we already created before.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> : <span class="hljs-type">Application</span></span>(), HasActivityInjector {

    <span class="hljs-meta">@Inject</span> <span class="hljs-comment">// It implements Dagger machinery of finding appropriate injector factory for a type.</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> dispatchingAndroidInjector: DispatchingAndroidInjector&lt;Activity&gt;

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">super</span>.onCreate()

        <span class="hljs-comment">// Initialize in order to automatically inject activities and fragments if they implement Injectable interface.</span>
        AppInjector.<span class="hljs-keyword">init</span>(<span class="hljs-keyword">this</span>)

        ...
    }


    <span class="hljs-comment">// This is required by HasActivityInjector interface to setup Dagger for Activity.</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">activityInjector</span><span class="hljs-params">()</span></span>: AndroidInjector&lt;Activity&gt; = dispatchingAndroidInjector
}
</code></pre>
<p>Because the application has activities, we need to implement the <code>HasActivityInjector</code> interface. If you see an error called out by Android Studio on <code>DaggerAppComponent</code>, it is because you have not generated a new file, as was pointed out in the previous step.</p>
<p><strong>So, setup <code>MainActivity</code> to inject the main ViewModel factory and add a support for fragment injections.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// To support injecting fragments which belongs to this activity we need to implement HasSupportFragmentInjector.</span>
<span class="hljs-comment">// We would not need to implement it, if our activity did not contain any fragments or the fragments did not need to inject anything.</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> : <span class="hljs-type">AppCompatActivity</span></span>(), HasSupportFragmentInjector {

    <span class="hljs-meta">@Inject</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> dispatchingAndroidInjector: DispatchingAndroidInjector&lt;Fragment&gt;

    <span class="hljs-meta">@Inject</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> viewModelFactory: ViewModelProvider.Factory
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> mainViewModel: MainViewModel


    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)

        <span class="hljs-comment">// Obtain ViewModel from ViewModelProviders, using this activity as LifecycleOwner.</span>
        mainViewModel = ViewModelProviders.of(<span class="hljs-keyword">this</span>, viewModelFactory).<span class="hljs-keyword">get</span>(MainViewModel::<span class="hljs-keyword">class</span>.java)

        ...
    }

    ...

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">supportFragmentInjector</span><span class="hljs-params">()</span></span>: AndroidInjector&lt;Fragment&gt; = dispatchingAndroidInjector

    ...
}
</code></pre>
<p>Because our activities have child fragments we need to implement <code>HasSupportFragmentInjector</code> interface. We also need this because we plan to make injections into our fragments. Our activity should not know about how it is injected. We use the <code>AndroidInjection.inject(this)</code> code line inside overriding <code>onCreate()</code> method.</p>
<p>Calling <code>inject()</code> method will cause Dagger 2 to locate the singletons in the dependency graph to try to find a matching return type. However we don’t need to write any code here because it’s done for us by previously created <code>AppInjector</code> helper class which we initialized inside our application class.</p>
<p><strong>Then, setup <code>MainListFragment</code> to inject the main ViewModel factory.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-comment">/**
 * A placeholder fragment containing a simple view.
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainListFragment</span> : <span class="hljs-type">Fragment</span></span>(), Injectable {

    ...

    <span class="hljs-meta">@Inject</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> viewModelFactory: ViewModelProvider.Factory
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> viewModel: MainViewModel

    ...

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onActivityCreated</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
        <span class="hljs-keyword">super</span>.onActivityCreated(savedInstanceState)

        ...
        subscribeUi(activity!!)
    }

    ...

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">subscribeUi</span><span class="hljs-params">(activity: <span class="hljs-type">FragmentActivity</span>)</span></span> {

        <span class="hljs-comment">// Obtain ViewModel from ViewModelProviders, using parent activity as LifecycleOwner.</span>
        viewModel = ViewModelProviders.of(activity, viewModelFactory).<span class="hljs-keyword">get</span>(MainViewModel::<span class="hljs-keyword">class</span>.java)

        ...

    }

}
</code></pre>
<p>Similar to activities, if we want our fragment to be injectable, then into its <code>onAttach</code> method we should write the code <code>AndroidSupportInjection.inject(this)</code>. But again this is a job done by the <code>AppInjector</code> helper, so we can skip that. Just notice that we need to add the <code>Injectable</code> interface which we created earlier for the helper to work.</p>
<p>Congratulations, we’ve implemented Dagger 2 in the My Crypto Coins app project. Of course this article is a quick guide to deploy Dagger 2 in your app straight away, but not deep coverage of it. I recommend that you continue researching this topic if you feel lost on the basics.</p>
<h3 id="heading-repository">Repository</h3>
<p>Check out the source code of the updated “Kriptofolio” (previously “My Crypto Coins”) app on GitHub.</p>
<h4 id="heading-view-source-on-githubhttpsgithubcombaruckiskriptofoliotreepart-4"><a target="_blank" href="https://github.com/baruckis/Kriptofolio/tree/Part-4">View Source On GitHub</a></h4>
<hr>
<p><strong><em>Ačiū! Thanks for reading! I originally published this post for my personal blog <a target="_blank" href="https://www.baruckis.com/android/kriptofolio-app-series-part-4/">www.baruckis.com</a> on October 7, 2018.</em></strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Another big problem with token models: “Medium of Exchange” tokens and the velocity problem ]]>
                </title>
                <description>
                    <![CDATA[ By Jose Maria Macedo As an analyst at Amazix, I spend a large portion of my time reading through hundreds of projects’ whitepapers and analyzing their token economic models to discern whether or not they’re adequately capturing the value created by t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/single-biggest-problem-with-token-models-part-2-52c0eca2115c/</link>
                <guid isPermaLink="false">66c35ef1c337fbd10a4b5966</guid>
                
                    <category>
                        <![CDATA[ Blockchain ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cryptocurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Investment ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ token economy ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 22 Sep 2018 14:07:33 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*dOLz3DK9K1LUHuFK.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Jose Maria Macedo</p>
<p>As an analyst at <a target="_blank" href="https://www.amazix.com/">Amazix</a>, I spend a large portion of my time reading through hundreds of projects’ whitepapers and analyzing their token economic models to discern whether or not they’re adequately capturing the value created by the project.</p>
<p>This is extremely important because the value captured by a token is essentially its utility or intrinsic value which is also what ensures that the token’s price grows alongside adoption/success of the underlying project. A token lacking utility will see its price supported only by speculation and is very likely to fail in the long-run.</p>
<p>For more on this, see my <a target="_blank" href="https://medium.com/@zemacedo/token-valuation-the-misunderstood-importance-of-token-economics-or-why-xrp-is-worthless-6b1b9ce5605f">earlier blog</a>, in which I discussed the importance of token economic models in ensuring a token’s long-term value.</p>
<p>In <a target="_blank" href="https://medium.freecodecamp.org/the-single-biggest-problem-with-token-models-part-i-8f9bcb3bab50">part 1 of this series</a>, I covered the problem of misaligned incentives caused by projects which have both equity and tokens, suggesting there’s an inverse relationship between the value of a project’s equity and the value of its token in that they are effectively competing to capture the value created by the project. I also suggested some potential solutions to this issue.</p>
<p>In this blog, I’ll discuss the second most common problem we see with token economic models: the velocity problem facing “Medium of Exchange” tokens. I’ll begin by giving a brief background of what token economics is before describing what the velocity problem is, why it matters and some of the solutions we recommend to our clients.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/AaXmsMRKJbeixIkkpXWJtu1QQMyDyfTlVVBr" alt="Image" width="640" height="425" loading="lazy"></p>
<h3 id="heading-what-is-a-token-economic-model-and-why-does-it-matter">What is a token economic model and why does it matter?</h3>
<p>If you’re a seasoned crypto investor or understand what a token economic model is, feel free to skip this part.</p>
<p>Before we start talking about token economic models, it may be wise to start at the very beginning with what is a token and what makes up its value.</p>
<p>A token is a crypto-economic unit of account that represents or interacts with an underlying value-generating asset. A token’s value is made up of its intrinsic value, the percentage of the token’s value that derives from demand for the underlying asset, and its speculative value, the percentage of the value of the tokens that derives from demand due to an expectation of future price increases. While speculation is nice, it is hard to control/predict and puts projects at the mercy of short-term-oriented investors, like our friend below:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/3y3eqaNZaPfZ67xy-gMHyX-xdx8tCn3HCUK6" alt="Image" width="259" height="194" loading="lazy"></p>
<p>Rather than focus on speculative value, we recommend investors focus on intrinsic value. A token’s intrinsic value is dependent on two factors: the value created by the underlying asset <em>and</em> the percentage of this value which is captured by the token.</p>
<p>The token economic model is what determines the latter — how much of the value created by the platform is captured by the token. As such, it’s one of the primary determinants of a project’s utility value and long-term success.</p>
<h3 id="heading-medium-of-exchange-tokens-and-the-velocity-problem">Medium of Exchange tokens and the velocity problem</h3>
<p>A pure Medium of Exchange token is a token whose sole or at least primary use is as payment for some utility on the project’s platform or protocol. There are various incarnations of this, from marketplaces such as <a target="_blank" href="https://signals.network/">Signals Network</a> where the token is the sole currency used to buy services on the platform, to SaaS type projects like <a target="_blank" href="http://bitstation.co/">BitStation</a> where customers can only access the platform’s utility by paying the company a fee in the native token.</p>
<p>The general problem with MoE tokens is that they suffer from extremely high velocity. This has been well documented by many, including <a target="_blank" href="https://vitalik.ca/general/2017/10/17/moe.html">Vitalik</a>, <a target="_blank" href="https://medium.com/newtown-partners/velocity-of-tokens-26b313303b77">James Kilroe</a> and <a target="_blank" href="https://www.coindesk.com/blockchain-token-velocity-problem/">Kyle Samani</a>.</p>
<p>Basically, given the MoE token’s only use is payment for a service on the platform, there’s no incentive actually to hold tokens and incur price risk vs FIAT.</p>
<p>Buyers of the platform’s utility will simply acquire tokens for the purposes of a specific transaction (holding it for as little time as possible). On the other hand, sellers of the platform’s utility (whether this be users on a marketplace as in the case of Signals or the company behind the project in the case of Bitstation) will instantly sell the tokens they receive for FIAT rather than incur price risk vs FIAT.</p>
<p>This will result in high velocity for the token, as the increase in demand driven by buyers acquiring tokens will always be quickly matched by a corresponding increase in supply from sellers converting these tokens to FIAT.</p>
<p>Effectively, high velocity acts as an increase in circulating supply and is thus inversely proportional to the value of the token (although a certain base level velocity is necessary for the token to have any value, <a target="_blank" href="https://medium.com/newtown-partners/velocity-of-tokens-26b313303b77">as pointed out by James Kilroe</a>). We can see how this works using the <a target="_blank" href="https://www.investopedia.com/terms/e/equation_of_exchange.asp">Equation of Exchange</a>, which has famously been adapted to crypto by both Chris Burniske and Vitalik.</p>
<p>To use Burniske’s definition:</p>
<p>MV=PQ</p>
<p>Where:<br><em>M</em>= size of the asset base<br><em>V</em>= velocity of the asset (the number of times that an average coin changes hands every day)<br><em>P</em>= price of the digital resource being provisioned. This is not the price of the cryptocurrency but rather of the resource being provisioned by the network (i.e. price in $ per GB of storage in the case of Filecoin)<br><em>Q</em>= quantity of the digital resource being provisioned (GBs of storage provided)</p>
<p>As Burniske tells us, in order to value the coin, we solve for M, where:</p>
<p>M = PQ/V.</p>
<p>M is the size of the monetary base necessary to support a cryptoeconomy of size PQ, at velocity V. In order to find the token price, we simply divide M by the total token supply. As we can see, the higher the velocity the lower the coin’s value.</p>
<p>Or, if we prefer to use Vitalik’s definition:</p>
<p>Vitalik takes MV=PT and in order to simplify the analysis of cryptocurrencies recasts it as MC=TH, where:</p>
<p><em>M</em>= total money supply (or total number of coins)<br><em>C</em>= price of the cryptocurrency (or <em>1/P</em>, with <em>P</em> being price level)<br><em>T</em>= transaction volume (the economic value of transactions per time)<br><em>H= 1/V</em> (the average time that a user holds a coin before using it to make a transaction)</p>
<p>Therefore, the left part of the equation (MC) is simply the market cap (total supply*price) whereas the right side is the economic value transacted per time period (T) multiplied by the average time a user holds a coin (H).</p>
<p>To solve for the token price, one must therefore solve for C:</p>
<p><em>C=TH/M</em></p>
<p>Once again, we can see that the higher the velocity (or the lower the holding time H), the lower the token price.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/pdcCegPgrx4ceZkSDwRkENIKHTs956dP9L2B" alt="Image" width="320" height="180" loading="lazy">
<em>Vitalik impress</em></p>
<p>In both Burniske and Vitalik’s definitions, it is apparent that the velocity of the coin is inversely proportional to the value of the token, That is, the longer people hold the token, the higher the price of each token. As James Kilroy tells us:</p>
<blockquote>
<p><em>“This is intuitive, because if the transactional activity of an economy is $100 billion (for the year) and coins circulate 10 times each over the course of the year, then the collective value of the coins is $10 billion. If they circulate 100 times, then the collective coins are worth $1 billion. Thus, understanding and calculating the velocity in any token economy is extremely important.”</em></p>
</blockquote>
<p>To see the drastic effects that velocity can have on a token’s value capture and market cap, see the following analysis <a target="_blank" href="https://medium.com/@john_pfeffer/hi-johnny-8411ec5d266">of the effects of velocity on Ethereum’s market cap by John Pfeffer:</a></p>
<blockquote>
<p><em>“In a protocol-land where protocol usage is managed by capital-efficiency optimising intelligent bots (which seems likely), let’s assume for simplicity the absolute floor on 1/V is the block time of the chain in question. Let’s then take ETH with a 2.5 minute block time as an example (highly theoretical, just to make a simple maths point). This implies each token could be used (assuming fixed block times, which in fact will likely shorten) 210,240 times a year. Buterin, Choi, etc. talk about, say, 10% of ETH being staked (let’s assume staked tokens never move at all). That would bring V down to 189,216 per year. Assume 50%, then V=105,120. Multiply this last number by $50b of network value (i.e., ETH just maintains its current value, and you’d need $5.25 quadrillion of economic activity denominated in ETH (i.e., excluding any ERC20/ ERC721-denominated economic activity), that is to say, 65x the current global GDP of $80 trillion. These numbers are all just varying shades of silly. That’s the point. As long as some of your tokens are circulating at a high V, your overall V is high.”</em></p>
</blockquote>
<h3 id="heading-solutions-to-the-velocity-problem"><strong>Solutions to the velocity problem</strong></h3>
<p>The most commonly used solutions to this problem all involve designing token economic models that provide incentives for people to hold the token — basically turning it into an asset (or “Store of Value”) rather than a currency. This can be done in several ways:</p>
<h4 id="heading-1-ensure-token-model-has-a-sink-in-it">(1) Ensure token model has a “sink” in it</h4>
<p>This one was initially suggested by Vitalik and has been widely adopted since. Basically, it involves designing token models with “buy-and-burn” mechanisms in which the project charges transaction fees and then uses some or all of the cash flows generated by its platform to purchase its own tokens and destroy them. The decrease in supply raises the value of all remaining tokens by the percentage of total supply destroyed. Effectively, the project is distributing its cash flows to its token-holders, very similar to how equity distributes cashflows to its stockholders through a dividend.</p>
<p>An example of this is Iconomi, a digital asset management platform which <a target="_blank" href="https://iconomi.zendesk.com/hc/en-us/articles/360001428854-Repayment-Programme-Buybacks-Token-Burn">burns preset percentages of all fees collected</a> and also produces quarterly reports outlining the number of tokens burned (crypto quarterly earnings reports).</p>
<p>Since, as we previously mentioned, velocity acts as an increase in circulating supply which reduces the value captured by the token, a buy-and-burn mechanism has the opposite effect of ensuring each additional transaction (i.e. increase in velocity) on the platform reduces the total supply of tokens, thus counteracting the increase in velocity with a deflationary force.</p>
<p>This should also reduce velocity by giving people a reason to hold the token, namely the expectation that it will be more valuable in the future due to the deflationary force created by the token burn.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/4xvIyYR8SJlQ7BkY8LMyp81y935fNtYHlvK-" alt="Image" width="600" height="255" loading="lazy">
<em>The Joker reducing $ velocity</em></p>
<h4 id="heading-2-implement-a-profit-share">(2) Implement a “profit-share”</h4>
<p>This one was initially <a target="_blank" href="https://multicoin.capital/2017/12/08/understanding-token-velocity/">suggested by Kyle Samani of Multicoin</a>. It is very similar in spirit to the “buy-and-burn” in that it is providing the token with a yield and turning it into an asset that generates cash flows.</p>
<p>An example of this is Augur which pays REP holders for performing work for the network. REP tokens are like taxi medallions: you must pay for the right to work for the network. Specifically, REP holders must report event outcomes to resolve prediction markets. Other examples of “profit-share” tokens include <a target="_blank" href="https://foam.space/">FOAM</a> , <a target="_blank" href="https://sharpe.capital/">Sharpe Capital</a> and also Ethereum once it has switched to Proof of Stake.</p>
<p>Once again, a profit-share reduces token velocity by forcing people to hold the token in order to have the right to generate cash flows by providing work to the network.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/vrdFC-TozgbVmvYVmqlkK3yPMTW2A3YrMJHo" alt="Image" width="518" height="369" loading="lazy"></p>
<h4 id="heading-3-encourage-users-to-lock-up-tokens">(3) Encourage users to lock up tokens</h4>
<p>This can be done through mechanisms such as <a target="_blank" href="https://github.com/ethereum/wiki/wiki/Proof-of-Stake-FAQ">Proof-of-Stake</a> which encourage users to lock up a certain amount of tokens, verify transactions and receive a yield in return (this also has the added benefit of acting as a profit-share). DASH, NEO and Navcoin are all examples of coins that have implemented proof of stake models.</p>
<p>Users can also be encouraged to lock up tokens through clever gamification — providing users with rewards (financial or otherwise) for locking up tokens. For instance, Alluma, a crypto exchange targeting Asian markets, offers different membership levels and fee discounts based on users staking different amounts of tokens:</p>
<ul>
<li>Gold memberships offer 35% discounts in exchange for staking 2500 LUMA for 30 days, and</li>
<li>Platinum memberships offer 50% discounts in exchange for staking 10,000 LUMA for 90 days (<a target="_blank" href="https://cdn2.hubspot.net/hubfs/4077694/whitepaper%20languages/Alluma%20Whitepaper.pdf?__hssc=147911272.3.1531961915300&amp;__hstc=147911272.bf36623eb62b5916dee4146a67129a0e.1531961915299.1531961915299.1531961915299.1&amp;__hsfp=2747456470&amp;hsCtaTracking=8aed7630-08c6-4c61-8bd1-6db116fa6876%7C50cad1a6-1dbf-4b3e-9f82-a8dd851584c5">source: page 28 of Alluma whitepaper</a>).</li>
</ul>
<p>For another example, we can look at YouNow, a live streaming app which allows users to tip content creators in its native token PROPS.</p>
<p>While content creators could immediately convert PROPS to FIAT, they are incentivized to hold onto it as their content is ranked higher by YouNow’s algorithm based on how many tokens they hold. Since discoverability leads directly to more tips, YouNow is effectively turning PROPS into an asset by ensuring users who hold it are able to generate cash flows.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/HHs-7B9WUn3SVSULp62cIeO8FbpXYO8kvSFk" alt="Image" width="500" height="281" loading="lazy">
<em>Donald Duck’s masternode</em></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Token economic model design is an extremely important and underrated area for both investors and founders of cryptocurrency projects to think about. A project with a weak token economic model may see its token price fail, even as the project itself succeeds, simply because the token is not capturing any of the value created by the project.</p>
<p>Velocity is one of the biggest problems with current token economic models and many established projects such as <a target="_blank" href="https://www.newtownpartners.com/how-civics-updated-token-model-decentralizes-trust/">Civic</a>, <a target="_blank" href="https://www.coindesk.com/300-million-lockup-storj-clarifies-token-economics-surprise-reveal/,">Storj</a> and Po.et have recently revamped their token models to address this issue. If you believe your project may also suffer from high velocity and are interested in having your token economics audited or discussing this further, feel free to get in touch with me through here or on <a target="_blank" href="https://twitter.com/zemariamacedo">Twitter.</a></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
