<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ciaran Mcveigh on Medium]]></title>
        <description><![CDATA[Stories by Ciaran Mcveigh on Medium]]></description>
        <link>https://medium.com/@ciaranmcveigh5?source=rss-640f647802c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_p2yp_UexRhbktpMoNcaig.jpeg</url>
            <title>Stories by Ciaran Mcveigh on Medium</title>
            <link>https://medium.com/@ciaranmcveigh5?source=rss-640f647802c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:27:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ciaranmcveigh5/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[DAO Treasuries: A Balancing Act]]></title>
            <link>https://ciaranmcveigh5.medium.com/dao-treasuries-a-balancing-act-64f6963ba707?source=rss-640f647802c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/64f6963ba707</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[dao]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Ciaran Mcveigh]]></dc:creator>
            <pubDate>Sun, 19 Dec 2021 09:12:09 GMT</pubDate>
            <atom:updated>2021-12-19T11:42:19.283Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a treasury to survive a crypto winter</h4><p>DAO Treasuries are lying to you. The billions of dollars locked up in their treasuries aren’t real. Capital allocation in a DAO treasury is a delicate balancing act, get it wrong and you might not survive the winter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5i74z2S01ixP83PC.jpg" /></figure><h4>Messari 2022 Report</h4><p>I recently read the DAO chapter from Messari’s <a href="https://messari.io/pdf/messari-report-crypto-theses-for-2022.pdf">2022 Crypto Theses Report</a> (Page 154) and was surprised to see just how many DAO’s have almost 100% of their treasury allocated to their native token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*V_FdYdUMtoV-Jrwv89ciyg.png" /><figcaption><a href="https://messari.io/pdf/messari-report-crypto-theses-for-2022.pdf">https://messari.io/pdf/messari-report-crypto-theses-for-2022.pdf</a></figcaption></figure><h4>A Trip Down Memory Lane</h4><p>It’s 2017 and the ICO boom is in full swing, projects were raking in millions of dollars worth of ETH and in many cases keeping it in ETH.</p><p>Crypto winter hit and the ETH price collapsed.</p><p>Project treasuries that were still denominated in ETH saw their runways shrink from 2 years to 6 months.</p><p>Many of these projects died while liquidating their ETH at the market bottom to pay staff.</p><h4>DAO Treasury Allocation</h4><p>While being exposed to one asset shows the purest form of faith in your token, it isn’t the smartest move for longevity and protecting against unforeseen future events. <a href="https://twitter.com/twobitidiot">Ryan Selkis</a> puts it best in his <a href="https://messari.io/pdf/messari-report-crypto-theses-for-2022.pdf">Messari Report</a>.</p><blockquote>Black Swan events leave protocol treasuries at the mercy of the market and that’s before you consider the idiosyncratic risk of each specific asset: smart contract failures, hacks, oracle deficiencies, and coding errors can tank a token’s price</blockquote><p>DAO treasuries made up of only their native token also says nothing about its real purchasing power. <a href="https://twitter.com/hasufl">Hasu</a> illustrates this point in his <a href="https://uncommoncore.co/a-new-mental-model-for-defi-treasuries/">Mental Models for Defi Treasuries</a>.</p><blockquote>Imagine that Uniswap tried to sell as little as 2% of its treasury. When executing this trade via 1inch, which routes the order to many on- and off-chain markets, the price impact on UNI would be almost 80%.</blockquote><p>So what should DAO’s do, let’s draw from methodologies already used within crypto &amp; TradFi to try and create a framework.</p><h3>Treasury Categories</h3><p>Caveat, the best approach would be to employ a professional financial manager to reduce treasury risk while maximising long-term token holder value. However, for now the nature of DAO governance, underlying smart contracts and lack of tooling make this extremely hard to implement.</p><p>Instead will look at a broad stroke structure of what a treasury could look like. We’ll start by looking at potential treasury categories, % split of assets have been included but have been arbitrarily picked and would likely be decided via a governance vote.</p><p>I’m going to use Aave as an example.</p><h4>Native Protocol Token: AAVE — 40%</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/0*KrMNC9CoA1IKu7nk.png" /></figure><p>A protocol should definitely hold its native protocol token and in most cases will be the largest holding of the DAO.</p><p>It signals the team/DAO has skin in the game of how the protocol performs. It is the easiest token for the DAO to acquire &amp; the hardest to exchange without impacting price.</p><p>It can be deployed to provide liquidity depth on AMM’s while earning fees. Buy backs can be conducted if LPing results in loss of the native token (impermanent loss).</p><h4>Stable Coins: USDC, DAI etc. — 35%</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/0*2BowZvLlWyRbKkIK.png" /></figure><p>A protocol should also have stables in their treasury and in most cases it should be the second largest holding.</p><p>Stables provide a buffer if a crypto winter comes, protecting against having to liquidate crypto assets at market bottoms, it can be used for grants, team payments etc.</p><p>Having a variety of stables makes sense for the same idiosyncratic risks mentioned above.</p><h4>L1/L2 Tokens: ETH, MATIC, AVAX — 20%</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/0*nXb7OxzPPBtmBqxv.png" /></figure><p>The DAO should own L1/L2 tokens of the networks its protocol is deployed on. Their combined total should equate to the third largest holding of the DAO.</p><p>Take Aave for example, they are currently deployed on Ethereum, Polygon &amp; Avalanche. As a result the DAO should own some ETH, MATIC &amp; AVAX and their ratios should be determined by their TVL on each network.</p><p>This helps diversify the DAO treasury, support the network (relative to the amount of usage on that network) and moves capital into more stable assets (This isn’t guaranteed but we would expect ETH to have smaller drawdown than AAVE in a bear market).</p><p>These Assets could be used for LPing with the protocols native token or could be staked to help support the networks, both would earn fees for the treasury.</p><h4>Strategic Partners: MKR — 5%</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/0*O5KDBWzfjwdhzuZU.png" /></figure><p>A small allocation could optionally be used with strategic partners. For example <a href="https://medium.com/intotheblock/makerdao-partnership-with-aave-redefines-the-mechanics-of-stablecoin-protocols-77d5ac8e7ad9">Aave have recently partnered with MakerDAO</a>.</p><p>Aave may be interested in acquiring MKR tokens primarily to have a voice in governance decisions with their strategic partner.</p><p>This again helps diversify the DAO treasury. The tokens could also be put to work in DeFi protocols while retaining the ability to vote on governance proposals with <a href="https://medium.com/element-finance/element-governance-a-technical-architecture-overview-2d0f72bd278a">element finance’s voting vaults</a>.</p><h3>The Path to Treasury Diversity</h3><p>Obviously a DAO that is currently 100% exposed to their native token needs to be extremely careful when liquidating /moving assets. Communication to the community about what is being done and governance voting on the categories / % splits are essential.</p><p>Large selling would likely see the native token price crash, if a DAO is to restructure its treasury it must do so very slowly. This could be implemented at the smart contract level over a set period of time/blocks. This could be percentage based or in absolute $ terms using an oracle.</p><p>Gradually the treasury would transform into the desired split.</p><p>DAO governance votes would control how often the rebalance occurs &amp; the maximum amount of assets that can be transformed. Governance will also decide which assets are included and their % splits.</p><h3>Conclusion</h3><p>It will ultimately be DAO members who decide what is done with the treasury.</p><p>Above are some ideas on how a treasury can be diversified to a variety of assets. There are still many questions to answer on how something like this would be implemented and the risks involved. Constant sell pressure, AMM slippage etc.</p><p>In the future large DAO’s will employ real financial managers to help protocols diversify intelligently and ensure they are well capitalised under all sorts of market environments.</p><p>For smaller DAO’s this won’t be possible so hopefully we as a community can come together and find the correct balance for DAO treasuries to protect both the token holders and the protocol itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64f6963ba707" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum’s EIP 1559]]></title>
            <link>https://ciaranmcveigh5.medium.com/ethereums-eip-1559-cd452d059988?source=rss-640f647802c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd452d059988</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[eip-1559]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Ciaran Mcveigh]]></dc:creator>
            <pubDate>Mon, 28 Jun 2021 07:50:40 GMT</pubDate>
            <atom:updated>2021-06-28T07:50:40.790Z</atom:updated>
            <content:encoded><![CDATA[<h4>Is Ethereum going deflationary after this latest monetary change</h4><p>EIP-1559 has got a lot of hype around it. The bulls are saying this is going to drive the price of Ethereum upwards as ETH turns deflationary but what exactly is it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjBxG_XTkaCea3EzS7ri4w.jpeg" /><figcaption>Ethereum</figcaption></figure><h4>Ethereum Improvement Proposal</h4><p>First, let give a brief explanation of what an EIP is. It stands for “Ethereum Improvement Proposal” and is a method by which anyone in the community can suggest improvements to the network.</p><p>EIP’s are voted on and vigorously peer-reviewed resulting in a Darwinian survival of the fittest. Only the EIP’s that can stand up to technical scrutiny and ones the community collectively want to implement will survive.</p><p>See <a href="https://github.com/ethereum/EIPs/tree/master/EIPS">here</a> for a list of EIPs that have made the cut since Ethereum started.</p><h3>Ethereum Transactions Fees - Status Quo</h3><p>EIP-1559 is centred on changing the Ethereum transaction fee structure. For us to understand these changes we need to understand the current state of play for the transaction fee market.</p><h4>Gas Limit &amp; Gas Price</h4><p>When you make a transaction you may have seen 2 terms used, the gas limit and the gas price. All transactions break down to specific instructions (OPCODES) that miners execute. Each of these instructions has a gas cost.</p><p>See <a href="https://github.com/crytic/evm-opcodes">here</a> for a list of these instructions (OPCODES) and their associated cost.</p><p>So how does gas limit and gas price relate to these?</p><p>Gas price is the amount you’re willing to pay per gas, the higher this number typically the faster your transaction will get into a block as miners will pick transactions with the highest gas fees. Think of the gas price per gallon at the gas station.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vfC97KdE8ZcBohEXTdQN4g.jpeg" /><figcaption>Ethereum gas can be compared to car gasoline to aid in understanding it as a concept</figcaption></figure><p>Gas limit is a protection against malicious or broken contracts, the gas limit sets a hard cap on the amount of gas you’re willing to spend on the transaction. Imagine at the gas station you could put a limit on the number of gallons from the pump and it wouldn’t let you go beyond that number to make sure you don’t overspend.</p><p>Let’s say there’s a contract that you assumed used 20 gas actually used 200,000 this would end up costing you orders of magnitude more. In this case, you could set a gas limit of 30 which would only allow your account to pay for a maximum of 30 gas. This prevents the contract call from draining your account due to the gas fees.</p><h4><strong>First Price Auction</strong></h4><p>So how do I decide on what gas price I should use?</p><p>Currently, Ethereum uses a “First Price Auction” method. This is where the price you bid is the price you pay. Let’s say a block can hold 5 transactions and the first 4 bidded 10 Gwei and you bidded 100 Gwei. You would pay 100 Gwei per gas even though you could have paid 10 Gwei and still been included in the block. An overspend of 90 Gwei per gas is not an efficient system for the end-user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPTwa20HQLoR9Rda0x0lPw.png" /><figcaption>First price auction is the current method for getting a transaction included in a block</figcaption></figure><p>Wallets will normally decide the gas price for you and let you know roughly the expected cost in dollar terms. They predict the gas cost based on previous blocks however past performance isn’t always indicative of future price and this is evidenced by the variance we see in gas prices paid in a given block.</p><p>And where do all these fees go? They go to the miners who secure the network.</p><h4><strong>Block Gas Limit</strong></h4><p>The last thing to note is the block gas limit. This is different from the transaction gas limit we mentioned above which is set by the user. This number is coded into the network and is the limit of gas that can be used per block.</p><p>The reason there is competition for transactions to get into a block is that there is a finite amount of space available per block. Currently, this sits at 12.5 million gas per block.</p><h3>Ethereum Transaction Fees - Post EIP-1559</h3><p>EIP-1559 looks to change the way the transaction fees work by having a compulsory “base fee” and an optional “priority fee”.</p><p>The base fee will be algorithmically calculated and will be fixed-per-block so all transactions in a block will pay the same base fee. This base fee will be burned. The priority fee will be determined by the user and will act as a tip to miners to incentivise them to prioritise your transaction in the block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*K7tGzGvHvX14B9Nw80sZsQ.png" /><figcaption>Fee structure after EIP-1559 implementation</figcaption></figure><p>Another change EIP-1559 implements is a dynamic block gas limit. Instead of blocks being fixed at 12.5 million gas the blocks will now target 12.5 million gas and be able to increase up to 25 million gas during periods of high load.</p><p>This dynamic block gas limit is linked to the algorithm that determines the base fee. The miner will choose the block gas limit based on demand, if that block limit is above the target limit of 12.5 million gas the base fee will be increased to suppress demand as gas prices increase. Similarly, the base fee will be decreased when the block gas limit drops below 12.5 million to increase demand.</p><p>The solidity code below shows the code that will be executed when the block gas limit is above 12.5 million gas, (see <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md">here</a> for full code snippet)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3be98e588e73669c723850dcd69c6fca/href">https://medium.com/media/3be98e588e73669c723850dcd69c6fca/href</a></iframe><p>Let’s run through this, we can see from line 8 the new base fee is being set by adding together the parent_base_fee_per_gas and the <strong>base_fee_per_gas_delta</strong>.</p><p>From line 7 we can see that the <strong>base_fee_per_gas_delta</strong> is influenced by the <strong>gas_used_delta</strong>. The higher the gas_used_delta the higher the base_fee_per_gas_delta.</p><p>From line 6 we can see that the <strong>gas_used_delta</strong> is calculated by looking at the parent_gas_used and the parent_gas_target. We know that the parent target is always 12,500,000 gas so the more we are over that number the higher the gas_used_delta will be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7iGQunrONqIIPmvgaoP34A.jpeg" /><figcaption>The algorithm determines the base fee rather than the user</figcaption></figure><p>This means the higher the parent block gas limit the higher the gas_used_delta which means the higher the base_fee_per_gas_delta which means the higher the new base fee will be.</p><p>This increase in base fee will continue until the block gas limit returns to its target of 12.5 million gas. This can be viewed as similar to the difficulty target that is adjusted as more hash rate comes on the network for proof of work mining.</p><p>In mining, there is a target block time and difficulty is adjusted to achieve that block time. Here there is a target block limit and the base fee is adjusted to achieve that block limit.</p><p>This predictability through the algorithm is great for wallets that can now accurately predict what the next blocks base fee will be instead of guessing based on current market conditions.</p><h4>Where do the fees go?</h4><p>Another change is where the fees go. Previously all fees went to the miners, EIP-1559 states that the optional priority fee will still go to the miners however the required base fee will instead be burnt.</p><p>Gas is paid in Gwei which is a denomination of Ether. Burning the base fee means removing it from circulation forever. This means for each block a certain amount of ETH is removed from the total supply.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FCZBM8aUid3p0A%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Frap-money-burn-CZBM8aUid3p0A&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2FCZBM8aUid3p0A%2Fgiphy.gif%3Fcid%3D790b76115924cd708cf6279c0a1423d571b5ce525e55dd64%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="342" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b5057157ac07f04c745e205a2aed925/href">https://medium.com/media/7b5057157ac07f04c745e205a2aed925/href</a></iframe><p>What does this mean for Ethereum, well the first thing to note is that each block still adds an amount of ETH back into the total supply in the form of a block reward for miners, this currently sits a 2 ETH per block.</p><p>So while Ethereum will likely continue to issue more ETH than it burns, its issuance rate will decrease. This in turn will reduce some of the sell-side pressure coming from miners. Less supply on the sell-side of a market generally means prices go up.</p><p>Miners aren’t particularly happy with this development in Ethereum as ETH that used to go to them in the form of transaction fees is instead being burned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*_NZMiRXVqx2qZgUr0QDORw.jpeg" /><figcaption>The Miner aren’t too happy with these new proposals</figcaption></figure><p>Historically transaction fees haven’t made up a huge percentage of miners profits &lt;5% however recently we’ve seen fees make up over 50% as the network has become congested and gas bidding wars have emerged.</p><p>The priority fee will still go to miners however this part of the fee is optional. It is likely this will be a small portion of the overall fee but we’ll have to wait and see how the ecosystem reacts to these new parameters.</p><p>Miners may not be happy but EIP-1559 is charging ahead. It’s set to be released on Mainnet with the “London Hard Fork” sometime in July 2021.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd452d059988" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cryptocurrencies & The Sharpe Ratio]]></title>
            <link>https://medium.com/coinmonks/cryptocurrencies-the-sharpe-ratio-8b662aa42af9?source=rss-640f647802c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b662aa42af9</guid>
            <category><![CDATA[sharpe-ratio]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Ciaran Mcveigh]]></dc:creator>
            <pubDate>Sun, 20 Jun 2021 20:22:59 GMT</pubDate>
            <atom:updated>2021-07-04T16:33:15.629Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding risk in a volatile market</h4><p>FOMOing in (Fear Of Missing Out) at the top, FUD (Fear Uncertainty Doubt) leading to weak hand selling at the bottom, these are decision driven by our emotions. The Sharpe Ratio looks at the data and tells us what our emotions can’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7s0V3E8weget4WrTBZPqmA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nick604?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nick Chong</a> on <a href="https://unsplash.com/s/photos/stock-market?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Risk and return, these two features are found in every market.</p><p>Return is a concept we’re all familiar with, I buy Bitcoin at $100 and I sell it a year later at $130, which represents a yearly return of 30%.</p><p>But what about risk, how do we define risk,</p><blockquote>Financial risk is the chance that an outcome or investment’s actual gains will differ from an expected outcome or return</blockquote><p>That quote may not make sense now but by the end of the article it will do.</p><p>We typically look at the financial world only in terms of returns and we allow our emotions to drive how we perceive risk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ar4A9sBDzqb1H3itf0qFlg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bubo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lubo Minar</a> on <a href="https://unsplash.com/s/photos/risk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We need to quantify risk and look at not just our returns but our risk-adjusted returns. Risk-adjusted returns looks at your risk and expected returns and provides you with a return per unit of risk.</p><p>The Sharpe Ratio is one of the industry-leading tools for looking at risk-adjusted returns and it&#39;s what we’ll be covering in the rest of this article.</p><p>First, we’ll need to start with the foundation upon everything else is built, the data.</p><h4><strong>The Data</strong></h4><p>Quantifying risk and return starts with the data. Historical price data is what we will be using. Note we’ll be using a very small sample size, when doing this for real it’s important to have large datasets to have confidence in what our calculations are telling us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpyrgqwMjfclV2oN1U2VIA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Luke Chesser</a> on <a href="https://unsplash.com/s/photos/analytics?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>For our example, we’re going to use real daily price data for Bitcoin (BTC), Ethereum (ETH) and Cardano (ADA) from 01/01/2021 to 10/01/2021. We’re going to grab this data from the <a href="https://coinpaprika.com/">CoinPaprika</a> API.</p><p>Try pasting some of the links below into your browser, they should return price datasets back to you.</p><pre># BTC<a href="https://api.coinpaprika.com/v1/coins/btc-bitcoin/ohlcv/historical?start=2021-01-01&amp;end=2021-01-10"><br>https://api.coinpaprika.com/v1/coins/btc-bitcoin/ohlcv/historical?start=2021-01-01&amp;end=2021-01-10</a></pre><pre># ETH<br><a href="https://api.coinpaprika.com/v1/coins/eth-ethereum/ohlcv/historical?start=2021-01-01&amp;end=2021-01-10">https://api.coinpaprika.com/v1/coins/eth-ethereum/ohlcv/historical?start=2021-01-01&amp;end=2021-01-10</a></pre><pre># ADA<br><a href="https://api.coinpaprika.com/v1/coins/ada-cardano/ohlcv/historical?start=2021-01-01&amp;end=2021-01-10">https://api.coinpaprika.com/v1/coins/ada-cardano/ohlcv/historical?start=2021-01-01&amp;end=2021-01-10</a></pre><p>This data comes in the form,</p><pre># BTC Price Data 2021-01-01</pre><pre>{<br>    &quot;time_open&quot;: &quot;2021-01-01T00:00:00Z&quot;,<br>    &quot;time_close&quot;: &quot;2021-01-01T23:59:59Z&quot;,<br>    &quot;open&quot;: 28966.95587637,<br>    &quot;high&quot;: 29568.27873174,<br>    &quot;low&quot;: 28812.98178846,<br>    &quot;close&quot;: 29344.67383113,<br>    &quot;volume&quot;: 29395282202,<br>    &quot;market_cap&quot;: 538407186724<br> }</pre><p>There are a lot of fields here, some are self-explanatory, for open, high, low, close these relate to chart candlesticks. I&#39;m sure you’ve seen these on Coinbase or Binance. Below is a diagram showing you how these terms relate to the candlesticks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*jsBdWvOn1jdZGziXg3YxkA.png" /><figcaption>Chart candlesticks and the terms used to describe them</figcaption></figure><p>We’ll only be looking at the close price of a given day and ignoring all the other price information to drive our calculations of risk and return. Now we have the data we can look at the formulas driving our calculations.</p><p>All the calculations below have be completed on this google sheet, <a href="https://docs.google.com/spreadsheets/d/1BzGxVHy50DMgkjDwSlnH2QhGK_Ga6_gE0kbs_sJLdXo/edit?usp=sharing">https://docs.google.com/spreadsheets/d/1BzGxVHy50DMgkjDwSlnH2QhGK_Ga6_gE0kbs_sJLdXo/edit?usp=sharing</a>.</p><h4>Expected Return Formula</h4><p>First, let’s look at BTC data in isolation and examine how we quantify expected return and risk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*OEr1X195hOG3A2mrAVdxTQ.png" /><figcaption>Our BTC data and the calculated daily return</figcaption></figure><p>Above we’ve loaded the data we grabbed from the CoinPaprika API into google sheets. We have the date, the price and the % return BTC.</p><p>Percentage return BTC is a daily return and is calculated by doing,</p><pre>(Todays_Price / Yesterdays_Price) - 1 </pre><p>Give it a go using some of the numbers above, note you’ll have to multiply the result by 100 to get it in a percentage format.</p><p>We can see when the price goes up we have a positive return and when the price goes down we have a negative return.</p><p>To get our <strong>expected return</strong> based we get an average of all our daily expected returns. When we calculate this it comes out to 3.18%. In our example, this indicates we can expect Bitcoin to increase by 3.18% per day based on our previous data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QvhoVcOU-OPz3UVtijsmkw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jievani?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jievani Weerasinghe</a> on <a href="https://unsplash.com/s/photos/bitcoin-market?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Risk</h4><p>Risk is calculated using the standard deviation of our daily return figures. Let’s start with a definition of standard deviation.</p><blockquote>A standard deviation is a statistic that measures the dispersion of a dataset relative to its mean.</blockquote><p>This effectively means standard deviation tells us about asset volatility, I’ll give you an example to hopefully help clarify.</p><p>Imagine we have 2 assets Asset A and Asset B, we have the following pieces of information on these assets,</p><ul><li>Asset A has an expected daily return of 7%</li><li>Asset B has an expected daily return of 4%</li><li>Asset A has a standard deviation (volatility) of 10%</li><li>Asset B has a standard deviation (volatility) of 1%</li></ul><p>If we look at Asset A, the standard deviation of 10% means that on a given day the asset could fluctuate from the average (expected daily return 7%) by plus/minus 10% which gives us a range of -3% to 17%.</p><p>Asset B on the other hand has a standard deviation of 1% and an expected daily return of 4% giving us a range of 3%-5%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sfKqs2vqDR39yT9EEoCEA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@etiennemartin?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Etienne Martin</a> on <a href="https://unsplash.com/s/photos/bank-of-england?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A fund manager would look at these 2 ranges and acknowledge that while Asset A provides a greater expected return it also represents a greater risk.</p><p>The lower bound of the range for Asset A is -3% while for Asset B it&#39;s 3%. In the case that we hit that lower bound Asset B will perform better than Asset A.</p><p><em>In reality, the ranges discussed above have a 68% chance of occurring which represents 1 standard deviation. Digging into this is outside the scope of this article but have a look </em><a href="https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule"><em>here</em></a><em> to find out more.</em></p><p>So how do we calculate the standard deviation?</p><h4>Risk Formula aka Standard Deviation</h4><p>Standard deviation looks at the values and their deviations from the mean of the sample set. This helps us see if the results are tightly clustered together which would represent low volatility and a low standard deviation or spread apart resulting in high volatility and a high standard deviation.</p><p>This volatility represents asset risk as it means the asset can have large fluctuations in price up or down.</p><p>The equation for population standard deviation is as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*jYqkNvFd6gnSFQwAJ3p1gA.png" /><figcaption>Standard Deviation Equation</figcaption></figure><p>Where,</p><p>σ = Standard Deviation<br><em>xi </em>= Data point value<br>μ = Mean of the data points<br>N = Number of data points</p><p>For Bitcoin this works out to 4.76%, see cell B18 for the result. Cell B18 uses the built-in function STDEV.P, I’ve completed the long hand version in cell B19. If you’d like more information on the standard deviation equation see <a href="https://www.khanacademy.org/math/statistics-probability/summarizing-quantitative-data/variance-standard-deviation-sample/a/population-and-sample-standard-deviation-review#:~:text=Standard%20deviation%20measures%20the%20spread,data%20point%20and%20the%20mean.&amp;text=If%20the%20data%20is%20being,number%20of%20data%20points%2C%20N.">here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0kowbmFNVZAI%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl0kowbmFNVZAI%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl0kowbmFNVZAI%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/616f56f532f6ccc9603c1d076061b691/href">https://medium.com/media/616f56f532f6ccc9603c1d076061b691/href</a></iframe><h4>Sharpe Ratio</h4><p>Now we have the components needed for calculating our Sharpe Ratio. The Sharpe Ratio measures the risk to reward of a portfolio/asset. It does this by looking at the excess return of the portfolio and dividing it by the volatility of the portfolio.</p><pre>                (excess return of the portfolio)<br>Sharpe Ratio = ----------------------------------<br>                  (volatility of the portfolio)</pre><p>The notation for this is as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*xUiDhmNFlQ8ndcsax42jCg.png" /><figcaption>Sharpe Ratio Equation</figcaption></figure><p>Where,</p><p>S = Sharpe Ratio<br>Rp = Expected return <br>Rf = Risk-free return<br>σp = Standard deviation</p><p>We’ve looked at expected return and standard deviation but we haven’t yet defined “risk-free return”. Risk-free return is the return we could get if we allocated our money to an asset with 0 risk.</p><p>In reality nothing has 0 risk but in finance government bonds are considered risk free and as a result, are typically used as the yardstick for what is the current risk free rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*xsvVIWe_2Wn9EAw6vXJeNg.jpeg" /><figcaption>Government bond from 1976 at 8% interest</figcaption></figure><p>Government bonds are effectively a loan to the government where they will pay you a certain interest rate for the duration of the loan and pay you back the principal at the end of the loan.</p><p>For us to work out the “excess return of the portfolio” we have to subtract the risk-free return from our expected return as this is the rate we could have got without taking on any risk.</p><p>In our example, we’ll assume a risk-free return of 1%, see <a href="https://www.bloomberg.com/markets/rates-bonds/government-bonds/us">here</a> for some real examples of the yields on US Treasury Bonds.</p><h4>Bitcoin’s Sharpe Ratio</h4><p>Using the figures calculated above we now have,</p><pre>Sharpe Ratio = (Rp - Rf) / σp</pre><pre>Sharpe Ratio = (3.18 - 1) / 4.76 = 0.458</pre><p>The higher the Sharpe Ratio the higher the reward per unit of risk that you are taking on. Having calculated Bitcoins Sharpe Ratio we could then go on to calculate other crypto assets to see how they compare.</p><p>I have done this for Ethereum and Cardano over the same time period. For expected return and standard deviation see cells C16, D16, C18, D18.</p><p><strong>Ethereum</strong></p><p>Expected Return = 6.58%<br>Standard Deviation = 8.06%<br>Sharpe Ratio = 0.692</p><p><strong>Cardano</strong></p><p>Expected Return = 6.95%<br>Standard Deviation =11.07%<br>Sharpe Ratio = 0.537</p><p>This means that Ethereum over that time period offered the largest reward per unit of risk as its Sharpe Ratio of 0.692 is higher than Cardano’s 0.537 and Bitcoin’s 0.458.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPUSr4llHeDhv1RkaGSUTQ.jpeg" /><figcaption>Ethereum — Photo by <a href="https://unsplash.com/@zoltantasi?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Zoltan Tasi</a> on <a href="https://unsplash.com/s/photos/ethereum?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Note the sample size for this example is 10 days so these results hold no real value, you would need to use the complete historical price data sets to have confidence in the results</em></p><h4>Portfolios</h4><p>We’ve calculated which asset gives us the best return per unit of risk. The question now turns to what happens when we mix and match these assets. Are we able to get a higher Sharpe Ratio?</p><p>The short answer is yes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*bK6Asmy_g6qq6aIivXUK4w.jpeg" /><figcaption>Optimising our portfolio can increase our risk-adjusted returns</figcaption></figure><p>For us to be able to work out our Sharpe Ratio for a portfolio containing multiple assets there are few additional steps we need to do.</p><h4>Correlation Between Assets</h4><p>First, we need to work out the correlation between the assets in our portfolio. Effectively this is asking when BTC/ETH/ADA goes up/down in price what do the other assets do.</p><p>Correlation varies between -1 and 1 where 1 shows a strong positive correlation ie. if BTC goes up in price so does ETH.</p><p>-1 shows a strong negative correlation ie. if BTC goes up in price ETH price goes down.</p><p>0 shows no correlation ie if BTC goes up in price it has no effect on ETH price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saINN7ypT9DGvMJu_XSu0w.png" /><figcaption>Example of correlation in graph format</figcaption></figure><p>Correlations are calculated between 2 assets, to cover all combinations of the 3 assets we need to calculate,</p><p>BTC/ETH<br>BTC/ADA<br>ETH/ADA</p><p>The correlation equation to do this is below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*rd2X_yY6L4AWzPeldEV10g.png" /><figcaption>Pearson Correlation Equation</figcaption></figure><p>Where,</p><p><em>xi = Asset A return on day i<br></em>x̄ = Asset A mean return over the time period<br><em>yi = Asset B return on day i<br></em>ȳ = Asset B mean return over the time period</p><p>This results in,</p><p>BTC/ETH correlation = 0.176<br>BTC/ADA correlation = 0.277<br>ETH/ADA correlation = 0.605</p><p>These correlations are needed to calculate our portfolio risk. See cells B24, C24, D24 which use the built-in function CORREL and cells B25, C25, D25 which uses the long hand formula.</p><h4>Portfolio Risk</h4><p>The portfolio risk is still represented by the volatility of the portfolio using standard deviation however the equation is slightly changed to take into consideration the various assets and their correlations.</p><p>The portfolio standard deviation is calculated using,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAElv3ceYEKa4nV0G4g_PA.png" /></figure><p>Where,</p><p><em>w = </em>Weight of the asset in the portfolio<em><br></em>σ = Standard deviation of the asset<br>c = Correlation between 2 assets</p><p>The subscripts indicate which asset is associated with which symbol. See cell B28 for an example of this calculation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-L0upbqq2BNbo8CBIOkaNg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tamara_photography?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tamara Gak</a> on <a href="https://unsplash.com/s/photos/risk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Portfolio Return</h4><p>The portfolio return is easily calculated by taking the expected return of an asset and multiplying it by its weighting in the portfolio.</p><p>As an example, let&#39;s say we held 50% BTC, 30% ETH and 20% ADA. From above the expected returns for the assets are 3.18%, 6.58%, 6.95% respectively. Therefore,</p><p>Expected Portfolio Return = (0.5 * 3.18) + (0.3 * 6.58) + (0.2 * 6.95) <br>Expected Portfolio Return = 4.95%</p><p>See cell B27 for an example of this calculation.</p><h4>Weighting of Assets</h4><p>The weighting of the assets affects both the risk and return. By varying the weighting we can explore how the risk and return change. We can then work out which portfolio gives us the best risk-adjusted return.</p><p>Below is a small simulation of testing various weightings, in reality a computer would run these calculations and test every possible portfolio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*p_5ikLi44yH-LqsjaUeD_w.png" /><figcaption>Calculations of the Sharpe Ratio as we vary portfolio weighting</figcaption></figure><p>Rp = Portfolio expected return<br>SD = Portfolio standard deviation (risk)</p><p>We can see that we start with a portfolio of 100% BTC. In steps, we then change the portfolio by decrementing BTC by 10% and increasing ETH and ADA by 6% and 4% respectively.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FFox4oWLsNMKD3QubO3%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FFox4oWLsNMKD3QubO3%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FFox4oWLsNMKD3QubO3%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/dadd53b6647f70fde10e517b34875dae/href">https://medium.com/media/dadd53b6647f70fde10e517b34875dae/href</a></iframe><p>As we include more ETH and ADA into our portfolio our return goes up (Rp) but so does our risk (SD). These figures enable us to calculate our Sharpe Ratio for each portfolio.</p><p>An allocation of 50% BTC, 30% ETH, 20% ADA gives us our highest Sharpe Ratio of 0.749. This means this portfolio gives us our greatest return per unit of risk.</p><p>If we compare this to our individual Sharpe Ratios calculated above we also beat all of those. The ETH Sharpe Ratio was the highest at 0.692 showing that diversification can increase your risk-adjusted return.</p><p>In reality, there are multiple portfolio’s with a higher Sharpe Ratio than 0.749. One example is 45% BTC, 45% ETH, 10% ADA which has a Sharpe Ratio of 0.774. In the real world, we would check all possibilities to make sure we had the best possible weighting.</p><h4>Conclusion</h4><p>You now have the tools to look at assets and portfolios and view them through the lens of both risk and return. The data drives our decisions rather than our emotions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FDnMMGxEvniha7CvASq%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FGetPartiful-to-the-moon-gme-stock-DnMMGxEvniha7CvASq&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2FDnMMGxEvniha7CvASq%2Fgiphy.gif%3Fcid%3D790b7611e059c3cdb088253a3f6943b2067135e2494f756f%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="457" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf01ecbd6dff2f3a4f4ae0bca4a7448a/href">https://medium.com/media/cf01ecbd6dff2f3a4f4ae0bca4a7448a/href</a></iframe><p>The calculations above give us insights based on historical price data. The larger the dataset the more confidence we have in our results, this means running these simulations on relatively new coins is probably unwise. Cryptocurrencies with multiple years worth of price data are best suited for these methods.</p><p>The Sharpe Ratio is one of many tools used to look at risk, it’s now in your toolbox but be careful not to treat it as a hammer in a world full of nails.</p><blockquote>None of the above is financial advise it’s purpose is purely educational</blockquote><h4>Also Read</h4><ul><li><a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">10 Best FREE Crypto Trading Bots in 2023</a></li><li><a href="https://medium.com/coinmonks/best-crypto-signals-telegram-5785cdbc4b2b">5 Best Crypto Telegram Channels 2024 (Trading Signals)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b662aa42af9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/cryptocurrencies-the-sharpe-ratio-8b662aa42af9">Cryptocurrencies &amp; The Sharpe Ratio</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wrapped Bitcoin - The Bridge to Decentralised Finance]]></title>
            <link>https://medium.com/coinmonks/wrapped-bitcoin-the-bridge-to-decentralised-finance-e5b293742d77?source=rss-640f647802c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5b293742d77</guid>
            <category><![CDATA[decentralized-finance]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Ciaran Mcveigh]]></dc:creator>
            <pubDate>Fri, 04 Jun 2021 07:23:43 GMT</pubDate>
            <atom:updated>2021-06-08T07:05:37.778Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why Wrapped Bitcoin is so important and how it works</h4><p>If I told you you could earn ~10% APY on your Bitcoin holdings you might ask me where? A better question is how?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*H9n0HOeAhHyzJAzZnpu0Rw.png" /><figcaption>“Compound interest is the 8th wonder of the world” — Albert Einstein</figcaption></figure><p>The first part of that answer is understanding Wrapped Bitcoin, what it is, why we need it and the technology that&#39;s being used to make it happen.</p><p>In this article, I’ll address these topics and highlight how Bitcoin was brought into the Ethereum ecosystem and granted access to the insane yields we see in decentralised finance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*tlNBkTptHd7PdlA7SfOxkQ.png" /><figcaption>Wrapped Bitcoin aka WBTC</figcaption></figure><h3>What is Wrapped Bitcoin?</h3><p>You may have heard of stable coins, these are cryptocurrencies that are pegged to a fiat currency. They represent a non-native asset on that blockchain (In this article we are specifically looking at the Ethereum blockchain) and their job is to accurately reflect the price of the asset backing them.</p><p>Wrapped assets do the same thing, they reflect the price of the asset backing them, because of this we could just as easily call these stable coins wrapped fiat coins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6xV6yrjwDBfC_4SK3Y1CA.png" /><figcaption>Various stable coins that are pegged to the dollar</figcaption></figure><p>There are 2 ways these coins maintain a peg to the off-chain asset, algorithmically using a smart contract or via a centralised reserve. If we take 2 examples for USD stable coins, Coinbase’s USDC and MakerDAO’s DAI we can compare the methods they use to maintain the peg.</p><p><strong>MakerDAO, DAI, Algorithmic<br></strong>Ethereum smart contracts are created where demand and supply are controlled in order to keep the price of the token in line with a fiat currency.</p><p><strong>Coinbase, USDC, Centralised Reserve<br></strong>Coinbase holds a reserve of USD which it has received in return for minting new USDC tokens, this ensures a 1 to 1 ratio of USDC to USD is maintained. Coinbase is audited regularly by a third party and has to provide proof of reserves. Centralised Reserves will also often publically publish evidence of proof of reserves.</p><h3>WBTC</h3><p>Wrapped Bitcoin is a project jointly initiated by Kyber, Ren, and BitGo, designed to make Bitcoin compatible with the Ethereum chain. We can see from the above that wrapped bitcoin WBTC has a lot in common with stable coins, it is an on-chain representation of a non-native Ethereum asset. Just like stable coins, its role is to accurately reflect the price of the asset backing it, Bitcoin.</p><p>It maintains its peg using the“Centralised Reserve” method with some additional safeguards intended to reduce the level of trust users need to have with that centralised entity. Before we get into the details of how this works let’s first address the question of why we need it.</p><h3>Why we need WBTC?</h3><ol><li>It enables Bitcoin as an asset to interact with Decentralised applications (Dapp’s) the majority of which reside on the Ethereum network</li><li>Increased speed of transaction, Ethereum blocks are created every ~15 seconds while Bitcoin blocks are created every ~ 10 minutes</li><li>Bringing Bitcoins liquidity into the Ethereum Dapp ecosystem</li><li>Improving interoperability between cryptocurrencies and being able to leverage smart contracts for future ideas</li></ol><p>Let&#39;s run through each one of these briefly;</p><h4>Dapps &amp; DeFi</h4><p>First, Bitcoins ability to interact with Dapps. This opens lots of opportunities in the Decentralised Finance (DeFi) space. Loaning your BTC on a DeFi platform enables you to earn a yield on your BTC which previously had been a non-yielding asset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqmmiyGmnZBxuC3ZRgNk8Q.png" /><figcaption>Two DeFi platforms APY compared: badger.finance &amp; beefy.finance</figcaption></figure><p>Moving your BTC to a Decentralised Exchange (DEX) enables to you swap BTC for currencies that aren’t listed on the centralised exchanges.</p><p>New ICO’s can accept both ETH and WBTC as payment enabling users to use BTC as an investment in an ICO. This list will only continue to grow as the Ethereum ecosystem becomes more mature.</p><h4>Transaction Speed</h4><p>Second, increased speed of transaction, this is less impactful than others on the list but does provide benefits to users. Say you have some BTC in cold storage and something is going on in the market that makes you want to sell.</p><p>You need to transfer that BTC to an exchange quickly. Typically for BTC the exchange will wait for 6 block confirmations before giving you access to you’re funds. In Bitcoin, ~10 mins blocks mean you’ll have to wait an hour to get access to your BTC on the exchange.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*Y3dQTRSnHNHREtkgLBNtNw.png" /><figcaption>Speed can be the difference between profit and loss in the market</figcaption></figure><p>In contrast for WBTC which is on the Ethereum network requires 12 block confirmations however each block is only ~15 seconds. Instead of waiting an hour you only have to wait 3 minutes.</p><p>We know how much can happen in the crypto markets in 57 minutes. Not having this speed advantage could correlate to lots of lost $$$.</p><h4>Liquidity in the Ethereum Ecosystem</h4><p>Bitcoin is king in the crypto markets and as a result, has the largest share of the overall market cap. Getting this liquidity onto the new and existing Dapp helps drive adoption and increases investor interest in these projects.</p><h4>Interoperability</h4><p>Interoperability between cryptocurrencies is not a zero-sum game, both networks can gain from that interoperability. Ideas that people may have had about Bitcoin but weren’t able to implement on its scripting language are now possible with WBTC.</p><p>There are clear advantages right now with WBTC and as we move forward new ideas and applications will only add to or strengthen those advantages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMMonbdbM8vWoZBF9FHd6A.jpeg" /><figcaption>Interoperability between various blockchains and assets is constantly being worked on</figcaption></figure><h3>How WBTC Works?</h3><p>WBTC consists of 3 key actors, the user, the merchant and the custodian.</p><p><strong>Custodian</strong> — The custodian holds the asset (The real Bitcoin). In the case of WBTC, this will be played by BitGo. Custodians hold the keys to mint WBTC tokens via smart contracts.</p><p><strong>Merchant </strong>— The merchants act as a middle men between the users and the custodian, they play a key role in the distribution of the wrapped token. In the case of WBTC, this will be played initially by Kyber and Republic Protocol (this has now expanded out to multiple other merchants). Each merchant holds a key to initiate minting of new wrapped tokens and burning of wrapped tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*3tyiFMon6wBe3TuGQz5aFA.png" /><figcaption>Minting process between the Custodian and Merchant</figcaption></figure><p><strong>User</strong> — The holders of the wrapped token. Users can use wrapped tokens to transfer and transact like any other ERC20 token in the Ethereum ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*zSeYJxPqKJJaoLDltNRS2Q.png" /><figcaption>Converting BTC to WBTC, interaction between Customer and Merchant</figcaption></figure><h4><strong>The Process</strong></h4><p>Custodians exchange wrapped tokens for assets with merchants. This is done through two different types of transactions; minting (creation of wrapped tokens) and burning (reducing supply of wrapped tokens).</p><p>These transactions will be available publicly and can be viewed by anyone through a block explorer. Here&#39;s an <a href="https://etherscan.io/tx/0xc7a9a50220ad581e79adfa573149cbf9b5410c927ae609537396c77e02300eec">example</a> of one of the biggest WBTC mints ever on etherscan. After the initial exchange, merchants aim to maintain a buffer of wrapped tokens so that they can exchange them with users.</p><p>The two-step minting process helps reduce the time it takes for users to get wrapped tokens, as minting and burning are more time-consuming processes.</p><h4><strong>Custodian &amp; Merchants Fees</strong></h4><p>You should be asking what’s in it for the custodians and merchants, why would they do this. Transfers of WBTC between users will have no cost apart from network fees. There are a couple of ways in which different parties in the network can earn fees:</p><ul><li>Custodian fees: This is taken by the custodian at the time when a merchant mints or burns wrapped tokens. (Varies from 0.04% - 0.1% trading fee)</li><li>Merchant fees: This is taken by the merchant who the user exchanges wrapped tokens with for the asset. (As an example Coinlist charges a flat 0.25% trading fee to wrap or unwrap WBTC)</li></ul><h4><strong>WBTC DAO</strong></h4><p>A Decentralised Autonomous Organisation is intended to enable a project to make changes in a decentralised fashion. The powers of a WBTC DAO member are listed below.</p><p>WBTC DAO member — Contract changes and addition/removal of custodians and merchants will be controlled by a multi-signature contract. Holders of the keys to the multi-sig contract will be held by institutions as part of the WBTC DAO.</p><h4><strong>Trust Model</strong></h4><p>The set-up described above requires the WBTC user to trust the centralised custodian entity. The custodian holds all the real Bitcoin, if they decided to exit scam the value of WBTC would quickly go to zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3h5siK9N1wA6lhsd-39yjw.jpeg" /><figcaption>WBTC requires a level of trust between the end-user and the Custodian</figcaption></figure><blockquote>BitGo being the only custodian does imply a significant counterparty risk to the asset directly, but we must take into account that BitGo is a crypto financial institution of significant importance for the crypto financial market.</blockquote><p>Having said this it is no different to trusting Coinbase as a custodian of you’re dollars when they mint USDC. There are a number of additional features WBTC have included to attempt to build more trust with users.</p><h4><strong>Audits</strong></h4><p>First quarterly audits will verify a 1 tot 1 match of WBTC to BTC reserves for the custodian. Proof of reserves can be shown by publishing signatures from the addresses in which bitcoin is stored in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oSRWsiyZwrXfScJQmlqAQ.jpeg" /><figcaption>Audits ensure the Custodian is in possession of the reserves they claim they are holding</figcaption></figure><p>Audits are a key part for any custodian. While they don’t protect against an exit scam they do protect against the custodian using the Bitcoin they have in custody of to try and generate more revenue ie trading BTC, loaning BTC etc. which is a risk the WBTC user hasn’t signed up for.</p><p>The private-public key set up of Bitcoin addresses enables an owner of a Bitcoin address to provide cryptographic proof of ownership without revealing their private keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*6OcK9SMgxf5Knr94qfiqDw.jpeg" /><figcaption>Bitcoin’s public-private key cryptography enables owners of BTC to prove they own the funds of an address</figcaption></figure><p>This is how BitGo would prove to the auditor they own the addresses they provide. See the dashboard of Bitcoin addresses owned by BitGo and the amount of BTC they hold <a href="https://wbtc.network/dashboard/audit">here</a>.</p><p>Recently BitGo the custodian for WBTC has partnered up with chainlink to create a <a href="https://www.bitgo.com/newsroom/press-releases/bitgo-adopts-chainlink-enable-on-chain-auditing-for-wbtc">chainlink oracle</a> for these proof of reserves. This enables DeFi projects to call a smart contract to verify the reserves every time new WBTC is minted or burned. Instead of having to trust a third-party audit every 3 months, they are now able to verify this themselves on demand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rr3N0ygbyx44laMfHpPSGA.png" /><figcaption>BitGo (Custodian) and Chainlink (oracle provider) have recently collaborated on a proof of reserves oracles</figcaption></figure><h4><strong>Minting</strong></h4><p>Custodians will not be able to mint tokens on their own, they require the initiation of a merchant in order to do so. Hence the creation of new tokens involves both the custodian and the merchant.</p><p>This prevents the custodian from arbitrarily minting new WBTC, the risk would be that they could mint new WBTC for Bitcoins that don’t exist. Additionally, the minting contract only allows the WBTC to be sent to an approved merchant. While this doesn’t completely protect the user against bad actors it does mean you would need 2 bad actors coordinating together, custodian and merchant rather than 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*LQ8w90t63f5pjemEyHX8Jg.jpeg" /><figcaption>Minting is how WBTC are created and brought into the Ethereum ecosystem</figcaption></figure><h4><strong>Transparency</strong></h4><p>WBTC have been very transparent with how the token functions and have provided key details on the following;</p><ul><li>Actors involved at the custodian and merchant level</li><li>List of custodian BTC addresses</li><li>Total value of custodian BTC addresses VS Total value of minted WBTC</li><li>Merchant and Custodian Ethereum addresses</li><li>Open-sourced contract code</li><li>Status of mints and burns, as these are Ethereum smart contracts they can easily be viewed</li></ul><h3>Conclusion</h3><p>Wrapped Bitcoin is a great tool that will help accelerate the adoption of Decentralised Finance and other Ethereum Decentralised Applications. It cannot be seen as a decentralised implementation as there is still counterparty risk. The implementation requires users to trust BitGo as the custodian of their real Bitcoin.</p><p>Despite this, there has been great adoption of the token with approximately 1% of all circulating BTC now wrapped as WBTC. This represents over $7 billion dollars worth of value. As new useful applications appear on the Ethereum network I can only see this percentage increasing as users look for ways to make their Bitcoin capital work harder for them.</p><blockquote>Join <a href="https://t.me/joinchat/Trz8jaxd6xEsBI4p">Coinmonks Telegram group</a> and learn about crypto trading and investing</blockquote><h4>Also, Read</h4><ul><li><a href="https://medium.com/coinmonks/youhodler-vs-coinloan-vs-hodlnaut-b1050acde55a">YouHodler vs CoinLoan vs Hodlnaut</a> | <a href="https://blog.coincodecap.com/cryptohopper-vs-haasbot">Cryptohopper vs HaasBot</a></li><li><a href="https://blog.coincodecap.com/binance-vs-kraken">Binance vs Kraken</a> | <a href="https://blog.coincodecap.com/pionex-dca-bot">Dollar-Cost Averaging Trading Bot</a></li><li><a href="https://medium.com/coinmonks/buy-bitcoin-in-india-feb50ddfef94">How to buy Bitcoin in India?</a> | <a href="https://medium.com/coinmonks/wazirx-review-5c811b074f5b">WazirX Review</a> | <a href="https://blog.coincodecap.com/bitmex-review">BitMEX Review</a></li><li><a href="https://blog.coincodecap.com/bitcoin-taproot">Bitcoin Taproot</a> | <a href="https://blog.coincodecap.com/bitso-review">Bitso Review</a> | <a href="https://medium.com/coinmonks/bitcoin-credit-card-bc8ab6f377c6">Top 6 Bitcoin Credit Card</a></li><li><a href="https://blog.coincodecap.com/gemini-vs-coinbase">Gemini vs Coinbase</a> | <a href="https://blog.coincodecap.com/kraken-vs-coinbase">Coinbase vs Kraken</a> | <a href="https://blog.coincodecap.com/coinspot-vs-coinjar">CoinJar vs CoinSpot</a></li><li><a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Bitcoin exchange in India</a> | <a href="https://medium.com/coinmonks/bitcoin-savings-account-e65b13f92451">Bitcoin Savings Account</a> | <a href="https://medium.com/coinmonks/paxful-review-4daf2354ab70">Paxful Review</a></li><li><a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a> | <a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://blog.coincodecap.com/best-crypto-trading-bots">Crypto Trading Bot</a></li><li><a href="https://medium.com/coinmonks/binance-fees-8588ec17965">Binance Fees</a> | <a href="https://medium.com/coinmonks/botcrypto-review-2021-build-your-own-trading-bot-coincodecap-6b8332d736c7">Botcrypto Review</a> | <a href="https://blog.coincodecap.com/crypto-com-alternatives">Crypto.com Alternatives</a></li><li><a href="https://medium.com/coinmonks/mxc-exchange-review-3af0ec1cba8c">MXC Exchange Review</a> | <a href="https://blog.coincodecap.com/pionex-vs-binance">Pionex vs Binance</a> | <a href="https://blog.coincodecap.com/pionex-arbitrage-bot">Pionex Arbitrage Bot</a></li><li><a href="https://medium.com/coinmonks/my-experience-with-crypto-copy-trading-d6feb2ce3ac5">My Experience with Crypto Copy Trading</a> | <a href="https://medium.com/coinmonks/coinbase-review-6ef4e0f56064">Coinbase Review</a></li><li><a href="https://medium.com/coinmonks/cryptocurrency-savings-accounts-be3bc0feffbf">Cryptocurrency Savings Accounts</a> | <a href="https://blog.coincodecap.com/staking-crypto">Staking Crypto</a> | <a href="https://blog.coincodecap.com/cex-io-review">CEX.IO Review</a></li><li><a href="https://medium.com/coinmonks/bitcoin-margin-trading-exchange-bcbfcbf7b8e3">Best Bitcoin Margin Trading</a>| <a href="https://blog.coincodecap.com/bityard-margin-trading">Bityard Margin Trading</a></li><li><a href="https://medium.com/coinmonks/crypto-margin-trading-exchanges-428b1f7ad108">Crypto Margin Trading Exchanges</a> | <a href="https://medium.com/coinmonks/earn-bitcoin-6e8bd3c592d9">Earn Bitcoin</a> | <a href="https://blog.coincodecap.com/mudrex-invest-review-the-best-way-to-invest-in-crypto">Mudrex Invest</a></li><li><a href="https://blog.coincodecap.com/blockfi-credit-card">BlockFi Credit Card</a> | <a href="https://blog.coincodecap.com/buy-bitcoin-binance">How to buy Bitcoin on Binance</a> | <a href="https://blog.coincodecap.com/grid-trading">Grid Trading Bots</a></li><li><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">Crypto Copy Trading Platforms</a> | <a href="https://blog.coincodecap.com/blockfi-alternatives">Top 5 BlockFi Alternatives</a></li><li><a href="https://medium.com/coinmonks/coinloan-review-18128b9badc4">CoinLoan Review</a> | <a href="https://medium.com/coinmonks/crypto-com-review-f143dca1f74c">Crypto.com Review</a> | <a href="https://medium.com/coinmonks/huobi-margin-trading-b3b06cdc1519">Huobi Margin Trading</a></li><li><a href="https://blog.coincodecap.com/blockchain-courses">Top paid cryptocurrency and blockchain courses</a> | <a href="https://medium.com/coinmonks/binance-review-ee10d3bf3b6e">Binance Review</a></li><li><a href="https://blog.coincodecap.com/use-bitmex-in-usa">How to use BitMEX in the USA?</a> | <a href="https://blog.coincodecap.com/bitmex-review">BitMEX Review</a> | <a href="https://blog.coincodecap.com/binance-vs-bittrex">Binance vs Bittrex</a></li><li><a href="https://blog.coincodecap.com/free-crypto-signals">Best Free Crypto Signals</a> | <a href="https://medium.com/coinmonks/yobit-review-175464162c62">YoBit Review</a> | <a href="https://medium.com/coinmonks/bitbns-review-38256a07e161">Bitbns Review</a></li><li><a href="https://blog.coincodecap.com/coinbase-staking">Coinbase Staking</a> | <a href="https://medium.com/coinmonks/hotbit-review-cd5bec41dafb">Hotbit Review</a> | <a href="https://blog.coincodecap.com/kucoin-review">KuCoin Review</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5b293742d77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/wrapped-bitcoin-the-bridge-to-decentralised-finance-e5b293742d77">Wrapped Bitcoin - The Bridge to Decentralised Finance</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be Less Wrong: A Mental Model]]></title>
            <link>https://blog.devgenius.io/be-less-wrong-a-mental-model-7fa5c0330faa?source=rss-640f647802c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fa5c0330faa</guid>
            <category><![CDATA[thinking]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[mental-models]]></category>
            <category><![CDATA[elon-musk]]></category>
            <dc:creator><![CDATA[Ciaran Mcveigh]]></dc:creator>
            <pubDate>Wed, 15 Jul 2020 06:55:44 GMT</pubDate>
            <atom:updated>2020-07-20T07:44:14.796Z</atom:updated>
            <content:encoded><![CDATA[<h4>Elon Musk’s thought-provoking advice on approaching problems</h4><p>What are the odds that your solution to a particular problem is the perfect solution?</p><p>That you are 100% right.</p><p>And I’m not talking 2+2 Math problems but real-world problems with many variables and many degrees of freedom.</p><p>Logically it’s 0.</p><p>If there are an infinite number of ways to approach the problem, then the odds you picked the winning lottery ticket are infinitesimally small. They tend to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZKMQpV6BhOPFlUNFLdjCgw.jpeg" /></figure><p>So we have established that your solution is somewhat wrong. Given this information what should we do?</p><blockquote>Question everything (including the problem statement itself).</blockquote><p>If we take the view that everything in our system is somewhat wrong and our job is to make it less wrong it opens up some interesting debates.</p><p>These include questioning our constraints and the problem statement itself.</p><p>Our constraints are sometimes self-imposed and sometimes come from external sources (ie our boss). In either situation, the constraints themselves will be somewhat wrong as well. Question them and understand why they are there.</p><p>With regards to the question remember, “A question well stated is half solved”. We often solve the wrong problem.</p><p>A good approach to get to the root of a problem is the 5 whys. Try asking this simple question, why?, 5 times in a row, you’ll be amazed at how much new information comes out of it.</p><p>When everything in the system is wrong there are no sacred cows, everything can be improved or discarded. We often optimise a part/process that either doesn’t add real value or doesn’t need to exist.</p><p>Next time you have to solve a problem, think about being less wrong. Try to get to the root cause of the issue. Don’t be afraid to challenge firmly held beliefs and constantly ask questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uU_i_f3qglKim8ECNbxptQ.jpeg" /><figcaption>SpaceX landing both boosters from a Falcon Heavy launch, each booster is the height of a 14-story building</figcaption></figure><p>Being “Less Wrong” has enabled Elon Musk to build Tesla when nobody said it was economically feasible and create rockets that land themselves when many were saying it wasn’t physically possible.</p><p>The “Be less wrong” line comes from an interview Elon Musk gave to the “Everyday Astronaut” in 2019. Check it out <a href="https://www.youtube.com/watch?v=cIQ36Kt7UVg&amp;t=306s">here</a>, 1:52 - 6:22.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fa5c0330faa" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/be-less-wrong-a-mental-model-7fa5c0330faa">Be Less Wrong: A Mental Model</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DeFi: A Beginners Guide]]></title>
            <link>https://medium.com/coinmonks/defi-a-beginners-guide-604874f76e37?source=rss-640f647802c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/604874f76e37</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Ciaran Mcveigh]]></dc:creator>
            <pubDate>Fri, 10 Jul 2020 18:13:37 GMT</pubDate>
            <atom:updated>2020-08-15T14:28:10.139Z</atom:updated>
            <content:encoded><![CDATA[<h4>Just what the Hell is Decentralised Finance?</h4><p>Decentralised Finance the current darling of the cryptocurrency space. A suite of tools and protocols that are looking to bring financial products “on-chain”. DeFi is quickly gaining traction but just what the hell is it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pv2AJGKWmqbFC9NjAWXuCg.jpeg" /></figure><p>There are various aspects to DeFi, decentralised exchanges, derivatives, stable coins, wrapped assets etc. but to understand DeFi you need to understand the current King of the space. Lending protocols are the dominant player in this arena.</p><p><a href="https://blog.coincodecap.com/the-ultimate-guide-to-defi-decentralized-finance">DeFi</a> has already picked up a head of steam, at the time of writing, DeFi products have a total of $2.16 billion locked up in them. Of that roughly $1.7 billion resides in “Lending Protocols”. Let’s find out why.</p><h3>Lending Protocols</h3><h4>Origins in Traditional Finance</h4><p>Lending protocols take a few very simple concepts from traditional finance, such as lending and borrowing, and implement them on-chain via smart contracts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sfKqs2vqDR39yT9EEoCEA.jpeg" /></figure><p>Let’s look at a traditional finance lending example, you deposit some money in your bank account, you can access it at any time and a benefit of depositing that money is that you receive interest.</p><p>The reason you earn interest is that the bank uses the money you deposited to issue low-risk loans such as mortgages. These loans typically have a higher interest rate than the one you are getting for depositing your money. This difference is one of the ways banks make a profit.</p><p>Now you may ask if my money is loaned out via a mortgage how can I withdraw my money at any time? You can do this because your deposit along with every other person’s deposit is pooled together as a liquidity pool.</p><p>Conceptually everything comes out and goes into this pool, the funds for the loans, withdrawals from your account, deposits into your account, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3u9E-NVOIyadCmWVnJbkqg.jpeg" /><figcaption>Think of each deposit as a droplet of water, these droplets in aggerate can create a “liquidity” pool</figcaption></figure><p>The bank does some calculations and there are some regulations in place to ensure that there should always be money in the pool for people to withdraw. Despite this, things can go wrong.</p><p>The model works because it assumes everyone won’t want to withdraw all their funds at the same time. This can and has happened and is known as a “bank run”.</p><p>For example in the 2008 financial crisis, people began to get nervous that the banks would fail so they began to withdraw their funds. This, in turn, increased the bank’s chances of failure as they now have less liquidity in their pool.</p><p>Information spreads that people are withdrawing their funds from the bank and so others also withdraw their funds. This creates a negative feedback loop and becomes a self-fulling prophecy when the bank eventually fails.</p><p>Now you have an understanding of the traditional finance model, let’s take a look at the new shiny decentralised world and their methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1WcfW1kbQpfJMGEf7ECJQ.jpeg" /></figure><h4>DeFi Lending Protocols, What do they Solve?</h4><p>Lending protocols are by far the biggest market currently in DeFi and it’s not surprising since they solve a major issue with holding cryptocurrencies. Ideally, people want to hold assets that appreciate and provide a yield. Yield examples would be dividends in stock and shares, bond interest rates, bank interest rates etc.</p><p>Before DeFi cryptocurrencies typically didn’t offer yield opportunities (except for staking). Cryptocurrencies had a negative yield because of the risks associated with holding it. If held on an exchange your funds could be hacked/stolen, on a hardware wallet the device could be lost and if you die without telling others those funds are lost forever.</p><p>We accepted these risks because the upside in terms of asset appreciation was so large that the yield didn’t matter. <a href="https://coincodecap.com/category/lend-and-borrow">Lending protocols</a> in DeFi now offer us a way to earn a yield on cryptocurrencies without giving up custody of our assets. They do this via smart contracts on the Ethereum blockchain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1X0-98EiQNkwBJj2vnTTqQ.jpeg" /></figure><p>The smart contract represents a place where assets can be pooled together, much like the way deposits are pooled together in a bank. With this pool of liquidity, loans can be made.</p><h4>The Lending Mechanics</h4><p>Earlier I referenced low-risk loans such as mortgages, one of the reasons mortgages are low risk is because there is a down payment of normally 10% the value of the house and because the house can be used as collateral if you default.</p><p>If you stop paying your mortgage the bank will repossess your house sell it to cover the loan. This idea of collateral is also used in DeFi, the borrower needs to put up some form of collateral so the debt can be repaid if they default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXS3qDTOwe176bRpAD-ObQ.jpeg" /></figure><p>This collateral generally takes the form of other cryptocurrencies and needs to be over collateralised. A 150% collateralisation rate means I need to put up $150 worth of collateral for a $100 loan. The reason for this over collateralisation is due to the volatility of cryptocurrency assets in general.</p><p>It’s not unusual to see +/- 50% move in an assets price over the course of a day. As a result, the protocol needs to protect itself by ensuring that even in the event of a steep decline in price the loan can be covered by selling the collateral.</p><p>One of the other ways the protocols further protect themselves from these steep declines is by using liquidation thresholds. A liquidation threshold is generally a ratio of the collateral value to the loan value.</p><p>The example above has a 1.5 ratio with $150 collateral for a $100 loan. The Protocol may say that you cannot drop below a 1.3 ratio. If your collateral, let’s say Bitcoin, drops by 15% in the price, then the dollar value will have been reduced to $127.50. The 1.3 ratio threshold requires a dollar value of at least $130 so in this case, you would be liquidated.</p><p>Liquidation involves the smart contract selling your Bitcoin on the open market and terminating your loan. You get to keep the $100 you loaned out but you lose your Bitcoin, which, at the time of sale was worth $127.50.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRMPny9g9mP9ADSvaYzung.jpeg" /></figure><p>Now that we’ve covered the collateral lets look at the interest rates on these loans. The rates are generally variable, that means they can go up and down during the duration of the loan. From a borrowers perspective, this is far from ideal.</p><p>The variable rate means they can’t plan for the future, they can’t know the exact amount of interest they’re going to have to pay at the end of the loan period. They need to constantly keep up to date with how the rate is changing.</p><p>The rates change constantly depending on the number of deposits into a pool and loans out of it. Generally, a mathematical formula is used to calculate the interest rate. It uses the deposits in and loans out to derive a utilization of the pool which in turn helps calculate the interest rate.</p><p>As an example, a pool with 100 Bitcoins in it and 80 Bitcoins loaned out would represent a utilization rate of 80%. Typically the interest rates are in the 5–15% range but can go as high as 60% and as low as 0.5%.</p><h4>Use Cases</h4><p>You may be wondering who would take the risk of liquidation along with the variable interest rates that can go as high as 60% to get a loan which they could get themselves by selling part of their collateral. A great question, let’s have a look at 2 of the main use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skINHS-mNCH55sOiu8KBPA.jpeg" /></figure><p>The first use case for a borrower is someone who wants to short a cryptocurrency. When you short an asset you’re betting that the price of that asset is going to go down.</p><p>They could put up a dollar-pegged stable coin as collateral for a loan of Ethereum, immediately sell that Ethereum, wait for the price to go down, buy it back, repay the loan and take profit on the difference between the interest paid and the money made selling the Ethereum high and buying back low. Needless to say, if Ethereum increases in price you’re in trouble.</p><p>Another possible use case is for people who are crypto rich but dollar (fiat) poor. Imagine you hold $1500 worth of Bitcoin and you believe it’s going to go up in price over the next couple months. You’ve also just had something break on your car and need to get it fixed, it will cost $1000.</p><p>You could sell you’re Bitcoin but you don’t want too because you believe the price is going to go up. Instead, you decide to take a DeFi loan out against your Bitcoin. You receive $1000 stable coin loan at 12% APR which can be converted to real dollars. You use this to get your car fixed and pay back the loan over the next 2 months from your paycheck.</p><p>With the interest, you’ve had to pay back $1020, but Bitcoin went up 20% in the last 2 months so your Bitcoin is now worth $1800. You leave happy knowing your instincts were right (This time).</p><p>Both examples may seem risky and they are but people are willing to take these risks. Both stories can end in tears if the price of your collateral or shorted asset goes the opposite direction you thought it would.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baxcUSIKVOwWsTLc4e07yQ.jpeg" /></figure><h4>Conclusion</h4><p>DeFi is in its infancy, it’s still growing but has already shown that it can genuinely add value to people in the crypto community. We have looked at the origins in traditional finance and seen the mechanics used to implement these concepts in smart contracts. We have an understanding of some of the risks involved and have seen some potential use cases. DeFi is charging forward with new protocols and innovations, only time will tell if these protocols will be blockchains breakout products. Let’s wait and see.</p><blockquote><a href="https://coincodecap.com/?utm_source=coinmonks">Get Best Software Deals Directly In Your Inbox</a></blockquote><figure><a href="https://coincodecap.com/?utm_source=coinmonks"><img alt="" src="https://cdn-images-1.medium.com/max/584/0*OJ-qb5G6i863msBB.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=604874f76e37" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/defi-a-beginners-guide-604874f76e37">DeFi: A Beginners Guide</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Math Behind The Magic — Defi Yield]]></title>
            <link>https://ciaranmcveigh5.medium.com/math-behind-the-magic-defi-yield-c1db2f0d216c?source=rss-640f647802c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1db2f0d216c</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[aave]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Ciaran Mcveigh]]></dc:creator>
            <pubDate>Thu, 25 Jun 2020 12:06:03 GMT</pubDate>
            <atom:updated>2020-06-25T12:06:03.392Z</atom:updated>
            <content:encoded><![CDATA[<h3>Math Behind The Magic — Defi Yield</h3><h4>Breaking down the mechanics behind Aave’s yield</h4><p>Defi: the land of opportunity. A place where you can earn up to 8–10% interest on your crypto without handing over custody of your private keys, it sounds like magic doesn’t it? I can assure you it’s not.</p><p>This article will examine the mechanics of those magical 8–10% yields and provide you with a better understanding of how they are derived. Today we’ll take a look at the Aave Defi protocol, a crypto lending platform that has taken the crypto world by storm since launching in January 2020 and now has over $144 million worth of crypto deposited with them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZlvLRDVs4YtMtAtxk4cIg.jpeg" /><figcaption>Aave a Defi Protocol</figcaption></figure><p>A quick primer on Aave and what they do. Let’s imagine you own some crypto, maybe you currently have it on an exchange or a hardware wallet. Your crypto is an asset, Aave enables it to become an interest-bearing asset. With Aave, you can earn interest on your crypto by depositing your cryptocurrencies into an Aave “reserve pool”. These are pools of liquidity in the form of smart contracts that Aave uses to finance loans.</p><p>These smart contracts mean that you aren’t entrusting Aave with your crypto but are instead entrusting the code that they have written. You receive tokens representing the crypto that was deposited. These tokens work like bonds with a programmatic guarantee of consistent interest payments and return of the principal amount upon redemption.</p><p>By depositing along with others into a pool depositors create liquidity so that others can borrow from that pool. The one requirement of people borrowing from these pools is that they must provide collateral. The collateral is in the form of other cryptocurrencies and needs to be over collateralized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0n5wbNLvvuXjjU_eHok8XQ.jpeg" /></figure><p>This means that borrowers need to provide more collateral than the loan amount. This ensures that the loaned “USD (Dollar) value” can be recovered in the event of volatile crypto markets. If the collateral no longer represents the required value relative to the USD value of the loan, the borrower’s collateral can be liquidated i.e. sold on the open market to repay the outstanding loan.</p><p>As an example, let’s say I have some Ether ($200) and want to borrow some Dai (a USD pegged stable coin). If the collateralisation ratio was 200% I could put up my $200 worth of Ether as collateral and in return borrow $100 worth of Dai. I have to pay the accumulated interest on the loan and the borrowed Dai to get my Ether back.</p><p>You can borrow at a stable interest rate or a variable interest rate in the same way you can have a fixed or variable rate mortgage. The stable rate will generally work out more costly than the variable rate but provides certainty and hedges against volatility risk.</p><p>So we have depositors who pool their crypto together and borrowers who take out loans from that pool on either a variable or stable rate. For us to understand how the yield rate (savings/deposit rate) is calculated we first need to understand some key pieces of data. These include the total amount borrowed, the utilization rate of the pool and the borrowing rates, both variable and stable.</p><p>For the total borrowed from a reserve pool, we can use this simple calculation:</p><pre>AmountBorrowedWithStableRate + AmountBorrowedWithVariableRate</pre><p>Each crypto has its own pool. Let&#39;s use the Dai reserve pool as an example. The total borrowed figure can be compared to the overall liquidity of the pool to determine the utilization rate. The utilization rate represents how much of a pool has been loaned out. For example, if I have a pool with $100 of Dai and $80 of those Dai have been borrowed that represents a utilisation rate of 80%.</p><p>To determine how much depositors (liquidity providers) should be compensated (the saving rate) we need to see how much those borrowers are currently paying us in interest.</p><p>For variable rate borrowers, this is an easy calculation we take the amount borrowed on the variable rate and multiply it by the variable interest rate to get a “weighted variable rate” or a snapshot of expected returns for the year from variable-rate borrowers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*1VjwWoiR_RvudKcKcf7GOQ.jpeg" /><figcaption>Dai a stable coin pegged to the US Dollar</figcaption></figure><p>Let’s use our example above, since Dai is pegged to USD I will represent everything in dollars (reminder: $1 = 1 Dai). Above we have $100 in the pool with $80 borrowed, let’s say that $50 are variable rate borrows and the remaining $30 are stable rate borrows. The current variable interest rate will be 4% APR (Annual Percentage Rate) and the stable rate will be 8% APR. So to calculate our “weighted variable rate” we do:</p><pre>VariableBorrowed * CurrentVariableRate = WeightedVaraibleRate <br>$50 * 4% = $2<br>50 * 0.04 = 2</pre><p>Next, we need to work out our “weighted stable rate”, this calculation is a little more complicated as borrowers may have taken out their loans at different times and as a result, received different interest rates. Again this happens every day with house mortgages, the rate you’ll be offered today will be different to the rate you were offered one year ago.</p><p>Given we could have multiple stable rates we need to take an average to get a single figure that represents how much we’ll receive in interest per year. Using our example we have $30 in stable-rate loans, let’s say $20 worth was taken out today at the 8% APR quoted above and the other $10 was taken out 2 months ago when the stable rate was 2% APR. To calculate the average we need to combine these 2 numbers. We need to take into consideration how much is borrowed at each rate to get a representative result. We have $30 in stable-rate loans, therefore the $20 at 8% represents 66.66% of the total stable rate loans and the $10 at 2% represents 33.33%. See the calculation below to get the “Average Stable Rate”.</p><pre>Average Stable Rate</pre><pre>(8% * 66.66%) + (2% * 33.33%) = 6%</pre><pre>OR</pre><pre>((8% * $20) + (2% * $10)) / $30 = 6%</pre><p>With this single figure of 6% to represent the rate of all stable loans we can use the same logic that was used with the variable rate loans to calculate the “weighted stable rate”.</p><pre>StableBorrowed * AverageStableRate = WeightedStableRate <br>$30 * 6% = $1.80<br>50 * 0.04 = 1.80</pre><p>Now we have all the pieces required to calculate our “savings rate”, the savings rate calculation uses the weighted rates along with the total amount borrowed and the utilisation of the pool. The first part is as follows:</p><pre>(WeightedVariableRate + WeightedStableRate) / TotalBorrowed</pre><p>This calculation referred to as the “overall borrow rate”, it essentially represents a “Return on Investment” (ROI) figure, ROI is calculated using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*IBW46_1VeUbryMXo5Nc9JA.png" /><figcaption>Source, <a href="https://www.investopedia.com/articles/basics/10/guide-to-calculating-roi.asp">https://www.investopedia.com/articles/basics/10/guide-to-calculating-roi.asp</a></figcaption></figure><p>Our “weighted stable rate” and “weighted variable rate” represent our net return i.e. what you have leftover once you have subtracted the initial investment. So if we lend out $80 for a year and get back $83.80 then we have received a net $3.80 in interest after we have subtracted the original loan amount of $80. Therefore in that scenario $3.80 represents our net return on investment.</p><p>They use that figure against the “cost of investment” or in our case the total amount borrowed out, $80. The multiplication of 100% is just to get it from decimal format ie 0.04 into a readable percentage ie 4%.</p><p>Let’s plug in our numbers and see what we get:</p><pre>(WeightedVariableRate + WeightedStableRate) / TotalBorrowed<br>(2 + 1.80) / 80 = 0.0475 = 4.75%</pre><p>Thus the overall borrow rate is 4.75%. However, there is one last calculation to get our savings rate. We need to multiply the overall borrow rate by the utilization rate (how much of the pool is borrowed). In this scenario, the utilization rate is 80% or 0.8 since we have a pool of $100 and $80 is borrowed.</p><pre>0.0475 * 0.8 = 0.038 = 3.8%</pre><p>We can therefore conclude that a depositor would get an interest rate of 3.8% for any deposits in the Dai pool. It’s worth noting that the saving rate is variable too as the inputs to the calculations are constantly changing. As an example, if I deposit $10 the utilization rate will now be 80/110 = 72.73% (changed from 80%) since the pool size has gone from $100 to $110. This, in turn, will change our savings rate. Having said this please note that normally the deposited amount relative to the pool will be small enough to not have a huge impact.</p><p>So now you know how the savings rate is calculated, let’s see it in action using real data from the Aave website and its API endpoint. Here’s a screenshot of the Aave website, specifically of the rates offered for Dai.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0b4LYaJbOwVffqAWAtjnSQ.png" /><figcaption>Source, <a href="https://aave.com/">https://aave.com/</a></figcaption></figure><p>Let’s see what we can extract from this:</p><pre>TotalBorrowed = $3,100,000<br>Utilisation = $3,100,000 / $4,400,000 = 0.7045 = 70.45%<br>VaraiableRate = 6.48%<br>StableRate = 8.19%</pre><pre>SavingRate = 4.60% (This is what we want to calculate)</pre><p>We have some useful data but we’re still missing some key items like how much of the total borrowed is stable and how much is variable. To get this we can use the API. For those who don’t know what an API is, just think of it as a place where you can request additional data. You can request data through <a href="https://thegraph.com/explorer/subgraph/aave/protocol-multy-raw">“the graph” </a>API for Aave. Below is the JSON response I received for the Dai Pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*iTqFF80dvb7jd60Fd5iveA.png" /><figcaption>Source, <a href="https://thegraph.com/explorer/subgraph/aave/protocol-multy-raw">https://thegraph.com/explorer/subgraph/aave/protocol-multy-raw</a></figcaption></figure><p>A lot of the fields in the JSON Response should look familiar, totalBorrowsStable, totalBorrowsVariable, utilizationRate etc. The numbers may look strange, this is because Aave uses something called “Ray Math”. The simplest way to describe this is that you make the numbers very big for the math part to reduce rounding errors and then convert it back to decimal for the users to see on the website. Read more about it <a href="https://medium.com/dapphub/introducing-ds-math-an-innovative-safe-math-library-d58bc88313da">here</a>. Below I’ve extracted the relevant fields we require and converted the numbers to decimal for us to complete our example. This conversion is simply dividing the number by 1000000000000000000000000000 (1e27) or by 1000000000000000000 (1e18) depending on the field.</p><pre>{<br>  &quot;name&quot;: &quot;Dai Stablecoin&quot;,<br>  &quot;totalBorrowsStable&quot;: &quot;191727&quot;,<br>  &quot;totalBorrowsVariable&quot;: &quot;2886067&quot;,<br>  &quot;variableBorrowRate&quot;: &quot;0.0648&quot;, (~6.48%)<br>  &quot;stableBorrowRate&quot;: &quot;0.0819&quot;, (~8.19%)<br>  &quot;averageStableBorrowRate&quot;: &quot;0&quot;,<br>  &quot;utilizationRate&quot;: &quot;0.7040&quot;, (~70.4%)<br>  &quot;totalLiquidity&quot;: &quot;4371729&quot;,<br>  <br>  &quot;liquidityRate&quot; : &quot;0.0460&quot; (~4.6%) (What we want to calculate)<br>}</pre><p>Let’s see if our new data from the API matches what we saw on the website. We just need to do one quick calculation first, totalBorrowStable plus totalBorrowVariable will give us our total borrowed in this case its,</p><pre>totalBorrowed = totalBorrowsStable + totalBorrowsVariable<br>totalBorrowed = $191,727 + $2,886,067 = $3,077,794</pre><p>So now let’s compare,</p><pre>WEBSITE                          |                              API</pre><pre>variableBorrowRate = 6.48%       |        variableBorrowRate = 6.48%<br>stableBorrowRate = 8.19%         |          stableBorrowRate = 8.19%<br>totalBorrowed = $3,100,000       |        totalBorrowed = $3,077,794<br>totalLiquidity = $4,400,000      |       totalLiquidity = $4,371,729</pre><p>We can see there are some slight discrepancies in our data however these are only due to rounding issues. The numbers we have are close enough for us to feel confident that the API data is reflective of what we see as a user on the website.</p><p>We have one final item to address before we do the calculation. From the API you may have noticed we get the field,</p><pre>&quot;averageStableBorrowRate&quot;: &quot;0&quot;</pre><p>This makes no sense, we have $191,727 borrowed on the stable rate and its currently at 8.19% so how can the “average stable borrow rate” be 0. It can’t and it isn’t. I’ve spoken to the Aave team and discovered this is a temporary issue with retrieving that specific piece of data from “the graph” API. The team are working on resolving it at some point in the future. If you want to get the “average stable borrow rate” you can by requesting the data directly from the blockchain using a web3 client. To keep things simple for this article, I won’t go into the details of how this is done but have retrieved the value which you can see below:</p><pre>&quot;averageStableBorrowRate&quot;: &quot;74317207158561776311730176&quot;</pre><pre>Which when converted to decimal equates to,</pre><pre>&quot;averageStableBorrowRate&quot;: &quot;0.0743&quot; (~7.43%)</pre><p>We can see a slight difference between this value 7.43% and our current stable rate, 8.19%. This is expected as we have combined all the stable rate loans together. Let’s do the math.</p><p>First, we need to calculate our weighted variable and stable rates,</p><pre>VariableBorrowed * CurrentVariableRate = WeightedVaraibleRate <br>$2,886,067 * 6.48% = $187,017<br>2886067 * 0.0648 = 187017</pre><pre>StableBorrowed * CurrentStableRate = WeightedStableRate <br>$191,727 * 7.43% = $14,245<br>191727 * 0.0743 = 14245</pre><p>Now we can use these values to get our “overall borrow rate”,</p><pre>(WeightedVariableRate + WeightedStableRate) / TotalBorrowed<br>($187,017 + $14,245) / $3,077,794 = 0.0654 (~6.54%)<br>(187017 + 14245) / 3077794 = 0.0654</pre><p>Then we use this value multiplied by the utilisation rate to get our savings rate,</p><pre>overallBorrowRate * utilizationRate = savingsRate<br>6.54% * 70.4% = 4.60%<br>0.0654 * 0.704 = 0.0460</pre><p>Finally, we have a savings rate, when we compare it to both the API and the website it matches! All three showed a “savings rate” of ~4.60%, congratulations you made it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2B1VruHNyAIsOsMOWREQw.jpeg" /></figure><p>Hopefully, this article has helped you gain a better understanding of the underlying math in Defi, you should now have a solid grasp of how the Aave saving rate is calculated and have seen it demonstrated against a real-world example. You now know the math behind the magic!</p><p>For those versed in javascript feel free to have a look at this code snippet <a href="https://jsfiddle.net/nabvdjzq/">https://jsfiddle.net/nabvdjzq/</a> which runs through the calculation above.</p><p>As always any feedback is welcome and please let me know if I’ve made any mistakes. Stay tuned for part 2 where I will break down the mechanics of calculating the Aave borrow rates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1db2f0d216c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang, What the Hell is a Pointer?]]></title>
            <link>https://ciaranmcveigh5.medium.com/golang-what-the-hell-is-a-pointer-e8d3a2524a5c?source=rss-640f647802c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8d3a2524a5c</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Ciaran Mcveigh]]></dc:creator>
            <pubDate>Wed, 30 Oct 2019 22:16:50 GMT</pubDate>
            <atom:updated>2019-10-30T22:16:50.255Z</atom:updated>
            <content:encoded><![CDATA[<h4>Demystifying the Golang Pointer Once and for All</h4><p>So what is a pointer in Golang? It’s a common question to those new to Go and one that should be explained fully to give the reader a solid foundation upon which they can build their understanding of the Go language. To understand the Go pointer we first must start with a quick overview of how computer memory works and how its related to your Golang programs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*mFf8Qzah4FMmG0p1kwGGRA.jpeg" /></figure><h4>A Brief Introduction To Computer Memory</h4><p>Computer memory, RAM, can be thought of as a series of boxes which each have an associated address and value. The boxes are labelled with a unique number, which increments sequentially; this is the address of the cell, its memory location. Each cell holds a single value. The diagram below may help crystallise this idea in your head. Note the empty cells represent cells where no value has been allocated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*Ob7UYZd4KOf2FmC6tRFWEg.png" /><figcaption>A representation of RAM</figcaption></figure><p>The above diagram shows four memory addresses 0000 to 0003 three of which have been filled with a value. You can imagine these values being a username (Jimmy) at 0003, a password at 0001 and an account balance at 0002. If you know the memory address of a cell, you can go to that cell and read its contents or you can place a value in that cell; replacing anything that was in there previously. With access to these values our programs can then manipulate them to achieve some desired result.</p><h4>Computer Memory in Golang</h4><p>So how does this relate to Golang pointers, take a look at the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c451a0192a19ef9dea579254a7ccbdd/href">https://medium.com/media/8c451a0192a19ef9dea579254a7ccbdd/href</a></iframe><p>A very simple Golang program that creates a variable called “age” and assigns it a value of 3. We then do two simple print statements one on “age” which represents the value of the variable “age” and one on “&amp;age” which represents the memory address of the variable age. You can run the code here <a href="https://play.golang.org/p/3C6FO9sZdTC">https://play.golang.org/p/ubkMp5bmjMQ</a>. The output I get is,</p><pre>age Value: 3<br>age Memory Address: 0x414020</pre><p>Now while I represented memory address values as decimal numbers here it is represented as a hexadecimal number. Don’t be confused its still just a number, 0x414020 in hexadecimal is actually equal to 4276256 in decimal. Read more about hexadecimal numbers <a href="https://medium.com/blockchaintechnologies/base-systems-and-ascii-8e7d33db5860">here</a>. So this is how our RAM looks when running this code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*esEJEeOodAiDpnwnYqEYYg.png" /><figcaption>A Representation of RAM for our Simple Go Program</figcaption></figure><p>Here we can see that the memory address 0x414020 holds a value of 3. It is also clear that each memory address is unique, if we look at the last number in the addresses they go 0, 1, 2, 3. Finally we can see that within our program “age” points to the associated value while “&amp;age” points to the memory address where that associated value is stored.</p><h4>Golang Operators</h4><p>Ok now we’re starting to get a rough picture of how values are stored in memory in our Golang program. Above we saw the use the &amp;age, this is an operator in Golang. We have the ampersand operator &amp;age and the star operator *age. The &amp; operator gives us the memory address of the variable it is used with while the * operator when used with a memory address will return the value at that memory address. Again a simple example may help clarify.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4806afcbe932f6b95c8f9f151c073a63/href">https://medium.com/media/4806afcbe932f6b95c8f9f151c073a63/href</a></iframe><p>The code above should look very familiar, all we’ve really added is one new value starOperatorAge and some additional print statements that print out the value of each variable and its type. Run it for yourself here <a href="https://play.golang.org/p/eC8d6yc2s7x">https://play.golang.org/p/eC8d6yc2s7x</a>. The output is shown below.</p><pre>age Value: 3<br>age Type: int<br><br>age Memory Address: 0x414020<br>ampersandOperatorAge Type: *int<br><br>age Value at Memory Address: 3<br>starOperatorAge Type: int</pre><p>Looking at the output the values make sense based on what we know about operators but what about the types. Age is of type int as is starOperatorAge but ampersandOperatorAge is of some strange type *int. *int means of type “integer <strong>POINTER</strong>” ie a memory address with an int stored as its value. If it were *string it would mean of type “string <strong>POINTER” </strong>ie a memory address with an string stored as its value. So in Golang when you hear someone talk about a pointer the first key point is to understand is that a pointer is simply the memory address of where some value is stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*MsLcEgkebIznvDgC7gH_mQ.png" /></figure><p>Ok so we finally know what a pointer is but hold on, this is also the point where people can get very confused. Why? Because * means two different things depending on the context. When * is used within a type declaration as I have show with *int it means a pointer to some type (in this case an integer), however when * is used as an operator as I showed with *ampersandOperatorAge it is used on memory addresses (which we just found out are referred to as pointers in Golang) to get the value at that address. Im going to write this out again to really hammer home this point.</p><pre>Star (*) Type Declaration Context ie *int</pre><pre>- Means a pointer to some type (memory address with value of type X)</pre><pre>--------------------------------------------------------------------</pre><pre>Star (*) Operator Context ie *ampersandOperatorAge</pre><pre>- Means get the value at some memory address</pre><p>Now we understand the types an important note to make is that the * operator can only be used on memory addresses AKA pointers AKA variables of *someType. This means if I were to try to add the line starOperatorAge := *age I would get an error as the * operator can not be used on a variable of type int. Hopefully you are starting to see the pieces fit together.</p><p>We’re almost done, we should now have a good grasp of what a Golang pointer is and how it relates to a variables value and its memory address. In Part 2 (coming soon) we will explore why pointers are needed in Goalng as well as their common uses and gotchas.</p><p>Hopefully this has helped you gain a better understanding of pointers in Go. As always any feedback is welcome and please let me know if I’ve made any mistakes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8d3a2524a5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding HTTP Requests & Responses in Golang]]></title>
            <link>https://ciaranmcveigh5.medium.com/understanding-http-requests-responses-in-golang-a13e5e92bc4f?source=rss-640f647802c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a13e5e92bc4f</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Ciaran Mcveigh]]></dc:creator>
            <pubDate>Sun, 13 Oct 2019 20:25:52 GMT</pubDate>
            <atom:updated>2019-10-19T14:56:07.540Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to communicate with API endpoints</h4><p>HTTP requests are a fundamental part of almost any application, it allows us to retrieve and submit data from endpoints which we can then manipulate. In Golang a simple HTTP GET request can be “not so simple” to newcomers. This article will look to build your understanding of the HTTP request and response in Golang and enable you to confidently make HTTP requests in your Golang application, let’s begin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*06A5r9G6LQApjya2LCo2JA.png" /></figure><h4>A Quick Overview of a Response</h4><p>Before we start lets quickly go over what a response consists of, for now will just look at a GET request. We’re going to use httpbin.org which is a great resource for playing about with and testing HTTP requests and responses.</p><p>Lets run a curl request to the /get endpoint and inspect the output</p><pre>curl -v https://httpbin.org/get</pre><p>Below is a shortened version of what is returned, I’ve omitted the parts that won’t be explained today but feel free to investigate them yourself ;</p><pre>&lt; HTTP/1.1 200 OK<br>&lt; Access-Control-Allow-Credentials: true<br>&lt; Access-Control-Allow-Origin: *<br>&lt; Content-Type: application/json<br>&lt; Date: Tue, 08 Oct 2019 21:14:39 GMT<br>&lt; Referrer-Policy: no-referrer-when-downgrade<br>&lt; Server: nginx<br>&lt; X-Content-Type-Options: nosniff<br>&lt; X-Frame-Options: DENY<br>&lt; X-XSS-Protection: 1; mode=block<br>&lt; Content-Length: 200<br>&lt; Connection: keep-alive<br>&lt;</pre><pre>{<br>    &quot;args&quot;: {},<br>    &quot;headers&quot;: {<br>        &quot;Accept&quot;: &quot;*/*&quot;,<br>        &quot;Host&quot;: &quot;httpbin.org&quot;,<br>        &quot;User-Agent&quot;: &quot;curl/7.54.0&quot;<br>    },<br>    &quot;origin&quot;: &quot;87.0.213.186, 87.0.213.186&quot;,<br>    &quot;url&quot;: &quot;https://httpbin.org/get&quot;<br>}</pre><p>In the above response there is a status code, a collection of headers and a response body. The status code is represented by,</p><pre>&lt; HTTP/1.1 200 OK</pre><p>The status code is the specifically the “200” in the above. The status code tells us the status of our request, ie whether it failed or was successful, a 200 means our request was successful. The HTTP/1.1 is just the version of HTTP that was used for the request and the OK is the corresponding message for a 200 status code. See <a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes">here</a> for a full list of status codes.</p><p>The headers are a list of key value pairs and are represented by,</p><pre>&lt; Access-Control-Allow-Credentials: true<br>&lt; Access-Control-Allow-Origin: *<br>&lt; Content-Type: application/json<br>&lt; Date: Tue, 08 Oct 2019 21:14:39 GMT<br>&lt; Referrer-Policy: no-referrer-when-downgrade<br>&lt; Server: nginx<br>&lt; X-Content-Type-Options: nosniff<br>&lt; X-Frame-Options: DENY<br>&lt; X-XSS-Protection: 1; mode=block<br>&lt; Content-Length: 200<br>&lt; Connection: keep-alive</pre><p>Each line represents a key value pair and enables the client and the server pass additional information with an HTTP request or response. For example “Content-Type: application/json” lets us know what format we can expect the body to be in so we can parse it accordingly.</p><p>Finally we have the response body, this is the data we want to retrieve from the endpoint and is represented by,</p><pre>{<br>    &quot;args&quot;: {},<br>    &quot;headers&quot;: {<br>        &quot;Accept&quot;: &quot;*/*&quot;,<br>        &quot;Host&quot;: &quot;httpbin.org&quot;,<br>        &quot;User-Agent&quot;: &quot;curl/7.54.0&quot;<br>    },<br>    &quot;origin&quot;: &quot;87.0.213.186, 87.0.213.186&quot;,<br>    &quot;url&quot;: &quot;https://httpbin.org/get&quot;<br>}</pre><p>Once we have this data we can load it into variables within our program and manipulate it to serve our purpose.</p><h4>A Simple GET Request</h4><p>In most programming languages, grabbing some data from an endpoint and loading it into a variable via a simple HTTP GET request requires very little work. Lets use python as an example and take a look at a snippet of code for a simple http get request to an api endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8323b4974dfaae51cde0ad310c860d15/href">https://medium.com/media/8323b4974dfaae51cde0ad310c860d15/href</a></iframe><p>In this example we import requests, we then make our HTTP GET request to the “https://httpbin.org/get” api endpoint using requests.get(&quot;https://httpbin.org/get&quot;) and set the result in the variable “response”. We can then access the status code returned using response.status_code, the headers can be accessed using response.headers and finally the body in JSON format loaded into a python dictionary using response.json(), we can get the raw body in string form using response.text. Finally we print out the variables to the console for us to inspect.</p><p>Golang is much the same however when you first start it can appear much more complicated. Hopefully you’ll see by the end of this article that Golang follows roughly the same process with a few nuances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*PKPCEDxgBcus8PAxTnzjTw.jpeg" /></figure><h4>A Simple (Not so Simple) GET Request in Golang</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c18de670e7282baded1ee34874e58387/href">https://medium.com/media/c18de670e7282baded1ee34874e58387/href</a></iframe><p>A lot of the above code is essentially the same as the python code. The import of net/http mirrors the import of requests and the setting of the resp variable to be equal to http.Get() again is extremely similar to request.get(). To understand how HTTP requests and responses work in Golang we must first understand the http.Get() method and its return types.</p><p>Golang is a statically typed language so understanding the return types is essential. We can find out return types and the implementation of that type by looking at the documentation. Being able to read documentation is a great skill to have and fortunately Golang provides some of the best docs out there. Follow along and you’ll realise reading the documentation isn’t as hard as you thought it would be.</p><p>First lets look at the return type of http.Get(). To find this we just need to navigate to the net/http package and method Get() in the documentation. (See here for the doc <a href="https://golang.org/pkg/net/http/#Get">https://golang.org/pkg/net/http/#Get</a>)</p><pre>func Get(url <a href="https://golang.org/pkg/builtin/#string">string</a>) (resp *<a href="https://golang.org/pkg/net/http/#Response">Response</a>, err <a href="https://golang.org/pkg/builtin/#error">error</a>)</pre><p>Here we can see that the method signature for “Get” returns 2 items, a pointer to a Response type (*Response) and an error type. The Get method takes in a single string variable called url.</p><p>Quick detour, a pointer is essentially the memory address of a variable so instead of passing around (duplicating) a huge piece of data you can simply pass around the memory address and then read the data at that memory address when you need to. This leads to performance improvements. See <a href="https://dave.cheney.net/2017/04/26/understand-go-pointers-in-less-than-800-words-or-your-money-back">here</a> for more information on pointers.</p><p>Now that we know the return variable is of type *Response lets find the docs on Response to understand what it consists of (<a href="https://golang.org/pkg/net/http/#Response">https://golang.org/pkg/net/http/#Response</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZ6K9hmm2NIKn9hVwx_TpQ.png" /></figure><h4>The Response Struct, The Key Sections</h4><p>The Response struct just like python has fields like Headers, Body and StatusCode. Their types however is where the confusion can begin. For now I’m going to simplify the Response struct to just the 3 items below so we can get a grasp of how these key pieces work.</p><pre>type Response struct {<br>    StatusCode <a href="https://golang.org/pkg/builtin/#int">int</a><br>    Header     <a href="https://golang.org/pkg/net/http/#Header">Header</a><br>    Body       <a href="https://golang.org/pkg/io/">io</a>.<a href="https://golang.org/pkg/io/#ReadCloser">ReadCloser</a><br>}</pre><p><strong>StatusCode Field </strong>-<strong> </strong>is the simplest, it returns a int just like in python no additional work is required.</p><p><strong>Header Field</strong> - is slightly more complicated, it is of type Header which means we need to jump a little further down the rabbit hole to understand what a Header type is. Again the docs come to the rescue here (<a href="https://golang.org/pkg/net/http/#Header">https://golang.org/pkg/net/http/#Header</a>).</p><pre>type Header map[<a href="https://golang.org/pkg/builtin/#string">string</a>][]<a href="https://golang.org/pkg/builtin/#string">string</a></pre><p>We can see Header is ultimately a map[string][]string. This is a dictionary or hash map where the keys are strings and the contents are arrays of strings, heres an example to clarify.</p><pre>{<br>    &quot;key1&quot;:[&quot;value1.1&quot;, &quot;value1.2&quot;, &quot;value1.3&quot;],<br>    &quot;key2&quot;:[&quot;value2.1&quot;, &quot;value2.2&quot;, &quot;value2.3&quot;]<br>}</pre><p><strong>Body Field</strong> - this is where I personally was very confused initially. In python you call request.json() and it takes the body and loads it into a dictionary ready for you to use within your code. Golang requires a few additional steps to get to this stage.</p><p>In Go you get back an object of type io.ReadCloser. So what the hell is an io.ReadCloser. An io.ReadCloser is an interface that implements the Reader and Closer interfaces which in turn implement a Read function and a Close function. Still confused? Don’t worry I was too.</p><p>Let’s explain the component parts first. A Reader is simply an object that has data inside of it which you can read out of it and an Closer is something that provides a generic way to close streams.</p><p>So our resp.Body is an object that has a some data inside of it which we can read out and has a function that allows us to close the stream. Docs here <a href="https://golang.org/pkg/io/#Reader">https://golang.org/pkg/io/#Reader</a>, <a href="https://golang.org/pkg/io/#Closer">https://golang.org/pkg/io/#Closer</a>.</p><pre>type Reader interface {<br>    Read(p []<a href="https://golang.org/pkg/builtin/#byte">byte</a>) (n <a href="https://golang.org/pkg/builtin/#int">int</a>, err <a href="https://golang.org/pkg/builtin/#error">error</a>)<br>}</pre><pre>type Closer interface {<br>    Close() <a href="https://golang.org/pkg/builtin/#error">error</a><br>}</pre><p>We want the body data in a format we understand so first of all we need to read it out. We want to make sure we close this operation when we are done to prevent resource leaks (Hence why we needed the “Closer”). We do this using defer resp.Body.Close() this says close the response body at the end of the function. We can now read out the data using ioutil.ReadAll() which will read the entire contents of the Reader into memory and then returns that data as an array of bytes. To convert the array of bytes to a string we simply use string(bodyBytes). Under the hood the ioutil.ReadAll() function implements a buffer to read the data.</p><blockquote>A data buffer (or just buffer) is a region of a physical memory storage used to temporarily store data while it is being moved from one place to another</blockquote><p>We now finally have the body in a format we can understand and is equivalent to the “response.text” variable in the python code. Here is the output I got from the Golang code posted above, I’ve added additional spacing and comments to make it easier to read,</p><pre><strong>// fmt.Println(resp.StatusCode)</strong><br>200</pre><pre><strong>// fmt.Println(resp.Header)</strong><br>map[Referrer-Policy:[no-referrer-when-downgrade] Server:[nginx] X-Frame-Options:[DENY] Connection:[keep-alive] Access-Control-Allow-Origin:[*] Content-Type:[application/json] Date:[Sun, 13 Oct 2019 19:51:29 GMT] Access-Control-Allow-Credentials:[true] X-Content-Type-Options:[nosniff] X-Xss-Protection:[1; mode=block]]</pre><pre><strong>//fmt.Println(resp.Header[&quot;Content-Type&quot;])</strong><br>[application/json]</pre><pre><strong>// fmt.Println(resp.Header[&quot;Content-Type&quot;][0])</strong><br>application/json</pre><pre><strong>// fmt.Println(bodyString)</strong><br>{<br>  &quot;args&quot;: {},<br>  &quot;headers&quot;: {<br>    &quot;Accept-Encoding&quot;: &quot;gzip&quot;,<br>    &quot;Host&quot;: &quot;httpbin.org&quot;,<br>    &quot;User-Agent&quot;: &quot;Go-http-client/1.1&quot;<br>  },<br>  &quot;origin&quot;: &quot;87.0.213.186, 87.0.213.186&quot;,<br>  &quot;url&quot;: &quot;<a href="https://httpbin.org/get">https://httpbin.org/get</a>&quot;<br>}</pre><p>There are a few more steps needed to get the data into the equivalent of a python dictionary I have run through this process in another article <a href="https://medium.com/swlh/json-in-golang-an-introduction-8e889c29a83">here</a>. It provides a run down of how to convert this JSON string into a usable Golang variable. In future articles I will discuss how to set headers for your GET request and run through a HTTP POST request as well.</p><p>We are now more or less at the same point as we were in the python code we have access to the status code, the headers and the body albeit in string format. Hopefully you now have an understanding of what the main components of a HTTP response are and how to use them even if you are still a little unsure of why they are implemented in this way. We have used the docs and followed the breadcrumb trail to understand what each component is made of and how it works. This improved understanding will hopefully enable us all to write better, cleaner code.</p><p>Thanks again for reading, as always any feedback is welcome and please let me know if I’ve made any mistakes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a13e5e92bc4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JSON in Golang an Introduction]]></title>
            <link>https://medium.com/swlh/json-in-golang-an-introduction-8e889c29a83?source=rss-640f647802c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e889c29a83</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Ciaran Mcveigh]]></dc:creator>
            <pubDate>Sun, 01 Sep 2019 17:59:03 GMT</pubDate>
            <atom:updated>2020-05-16T20:42:18.072Z</atom:updated>
            <content:encoded><![CDATA[<h3>JSON in Golang an Introduction, Never be Confused Again</h3><h4>A simple explanation of how to consume and return JSON in your Golang applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30aoNxlSnaYrLhBT0O1lzw.png" /></figure><h3>Introduction</h3><p>In this article, I will show you the basics of how to parse and return JSON in Go while also providing you with an understanding of the process.</p><p>First, let’s look at how JSON is parsed in other languages specifically dynamically typed ones, I’m going to use python as an example.</p><pre>##############<br>RETURNING JSON <br>##############</pre><pre>import json<br><br># a Python object (dict):<br>p_dict = {<br>  &quot;name&quot;: &quot;John&quot;,<br>  &quot;age&quot;: 30,<br>  &quot;city&quot;: &quot;New York&quot;<br>}<br><br># convert into JSON:<br>y = json.dumps(p_dict)<br><br># the result is a JSON string:<br>print(y)</pre><pre>##############<br>CONSUMING JSON <br>##############</pre><pre>import json<br><br># some JSON:<br>j_str =  &#39;{ &quot;name&quot;:&quot;John&quot;, &quot;age&quot;:30, &quot;city&quot;:&quot;New York&quot;}&#39;<br><br># parse j_str:<br>y = json.loads(j_str)<br><br># the result is a Python dictionary:<br>print(y[&quot;age&quot;])</pre><p>The code looks relatively simple, in the case of returning JSON we have a python dictionary “p_dict” which we can convert to a JSON string using json.dumps(p_dict) . When consuming JSON, we have a JSON string “j_str” which we can convert to a python diction using json.loads(j_str) .</p><p>Now parsing a format like JSON in a <strong>statically typed</strong> language like Go presents a bit of a problem. Go is statically typed which means the type of every variable in the program needs to be known at compile time. This means that you as the programmer must specify what type each variable is. Other languages (python) offer some form of type inference, the capability of the type system to deduce the type of a variable. The main advantage of a statically typed language<strong> </strong>is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage. A simple code example may clarify.</p><pre>PYTHON</pre><pre>x = 3</pre><pre>GOLANG </pre><pre>var x int = 3 </pre><p>When parsing the JSON anything could show up in the JSON body, so how does the compiler know how to set up memory given it doesn’t know the types?</p><p>There are two answers to this. One answer when you know what your data will look like and one answer for when you don’t. We will cover the first option initially as this is the most common situation and leads to the best practices.</p><p>When the data types in the JSON is known you should parse the JSON into a struct you’ve defined. Any field which doesn’t fit in the struct will just be ignored. We’ll explore this option in both returning and consuming JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*Hup2haY1IpFdiUC2Url2gw.png" /></figure><h3>Returning JSON</h3><p>Let’s say we want to return the following JSON object.</p><pre>{<br>  &quot;key1&quot;: &quot;value 1&quot;,<br>  &quot;key2&quot;: &quot;value 2&quot;<br>}</pre><p>The code below shows how this is done, let’s talk through it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35eb3ac8d48643c5afda9433928163f8/href">https://medium.com/media/35eb3ac8d48643c5afda9433928163f8/href</a></iframe><ul><li>Lines 3–6: We import the encoding/json and fmt packages for parsing the JSON and printing the results.</li><li>Lines 8–11: The JSONResponse struct is the Go variable representation of the JSON in the same way the python dictionary was the python variable representation of the JSON.</li><li>Lines 8–11: Note in JSONResponse we only declare types no values, we also add “Go Tags” `json: &quot;key1&quot;` which let&#39;s Go know what the associated key is in the JSON object.</li><li>Lines 15–18: jsonResponse is an instantiation of the JSONResponse struct and populates the values.</li><li>Lines 20–21: We print the jsonResponse variable to the console so we can contrast it with the JSON which is later printed.</li><li>Lines 23–24: We Marshal the variable jsonResponse which is of type JSONResponse this converts it into a byte array and takes into consideration the mappings declared in the “Go Tags”. The returned byte array is stored in the byteArray variable.</li><li>Lines 26–28: We run an error check on the Marshal function and print the error if it is not nil.</li><li>Lines 30–31: We cast the byteArray to a string and print it, we can now view the difference between the printed struct and the printed JSON.</li></ul><p>Please run the code here to see the results, play with the code also it’s the best way to learn <a href="https://play.golang.org/p/gaBMvz21LiA">https://play.golang.org/p/gaBMvz21LiA</a>.</p><h4>Nested JSON</h4><p>Now let’s look at a more complex JSON object with nested items</p><pre>{<br>  &quot;key1&quot;: &quot;value 1&quot;,<br>  &quot;key2&quot;: &quot;value 2&quot;,<br>  &quot;nested&quot;: {<br>    &quot;nestkey1&quot;: &quot;nest value 1&quot;,<br>    &quot;nestkey2&quot;: &quot;nest value 2&quot;<br>  }<br>}</pre><p>The code below shows how this is done, let’s discuss what’s changed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff7fb66d7c9a151ebd3c789865935f52/href">https://medium.com/media/ff7fb66d7c9a151ebd3c789865935f52/href</a></iframe><ul><li>Line 11: Rather than declaring Nested as type string we declared Nested as type Nested which is a type we are about to create.</li><li>Line 14–17: We declared the Nested type struct which we have used in JSONResponse following the format of the JSON we want to return.</li><li>Line 21–30: We instantiate both the nested variable of type Nested and the jsonResponse variable of type JSONResponse which in turn references the nested variable we just declared.</li></ul><p>Those are the key differences between this example and the previous one. Again run the code here to test it and make some of the changes suggested in the comments <a href="https://play.golang.org/p/GcRceKe1jC-">https://play.golang.org/p/GcRceKe1jC-</a>.</p><h4>Arrays in JSON</h4><p>Finally, let’s look at returning a JSON object that contains an array.</p><pre>{<br>  &quot;key1&quot;: &quot;value 1&quot;,<br>  &quot;key2&quot;: &quot;value 2&quot;,<br>  &quot;nested&quot;: {<br>    &quot;nestkey1&quot;: &quot;nest value 1&quot;,<br>    &quot;nestkey2&quot;: &quot;nest value 2&quot;<br>  },<br>  &quot;arrayitems&quot;: [<br>    {<br>      &quot;iteminfokey1&quot;: &quot;item info 1 array index 0&quot;,<br>      &quot;iteminfokey2&quot;: &quot;item info 2 array index 0&quot;<br>    },<br>    {<br>      &quot;iteminfokey1&quot;: &quot;item info 1 array index 1&quot;,<br>      &quot;iteminfokey2&quot;: &quot;item info 2 array index 1&quot;<br>    }<br>  ]<br>}</pre><p>The code below shows how this is done, again let’s discuss what has changed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbda92f4326593a6b162f6206e1b3879/href">https://medium.com/media/fbda92f4326593a6b162f6206e1b3879/href</a></iframe><ul><li>Line 12: We add ArrayItems to our JSONResponse which is of type []ArrayItem, an array of type ArrayItem which we are about to declare below.</li><li>Line 20–23: Declare ArrayItem struct this is the definition of what each item within the array will consist of.</li><li>Line 27–36: Instantiate arrayItems of type []ArrayItem and populate the values in each index.</li><li>Line 47: Reference the arrayItems variable in the declaration of the jsonResponse.</li></ul><p>Test it out and play with the code here <a href="https://play.golang.org/p/YhqKR6lZ_ge">https://play.golang.org/p/YhqKR6lZ_ge</a>.</p><h3>Consuming JSON</h3><p>Ok now let’s look at consuming JSON from a rest API, I’m going to mock the returned JSON from the API to simplify the process. Since we have an understanding now of how Go structs relate to JSON strings we’ll jump straight in with a complicated JSON object.</p><p>This is the JSON response we are going to get from the API. I’m using the JSON returned from <a href="https://httpbin.org/get">https://httpbin.org/get</a> which is a great website for testing HTTP requests and responses. Here’s the JSON we are going to receive. (Run curl <a href="https://httpbin.org/get">https://httpbin.org/get</a> in your terminal to test)</p><pre>{<br>  &quot;args&quot;: {},<br>  &quot;headers&quot;: {<br>      &quot;Accept&quot;: &quot;*/*&quot;,<br>      &quot;Host&quot;: &quot;httpbin.org&quot;,<br>      &quot;User-Agent&quot;: &quot;curl/7.54.0&quot;<br>  },<br>  &quot;origin&quot;: &quot;83.7.252.17, 83.7.252.17&quot;,<br>  &quot;url&quot;: &quot;https://httpbin.org/get&quot;<br>}</pre><p>Note the “origin” will be different for you as your request will be coming from a different IP. The empty “args” object will contain any arguments passed in the URL. So <a href="https://httpbin.org/get?testArg=testValue&amp;x=3">https://httpbin.org/get?testArg=testValue&amp;x=3</a> would return,</p><pre>&quot;args&quot;: {<br>  &quot;testArg&quot;: &quot;testValue&quot;,<br>  &quot;x&quot;: &quot;3&quot;<br>}</pre><p>This args value is a good example of a case when we don’t know what the key name or the values intended type is going to be. To get around this we set “args” type as map[string]interface{} which is a map (a hash table) with keys of type string and values of type interface{}. An empty interface{} is a way of defining a variable in Go as “this could be anything”. At runtime, Go will then allocate the appropriate memory to fit whatever you decide to store in it.</p><p>Let’s have a look at an example of using JSON from an API in code and discuss the main sections of the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cfac449e22196d0ea2b1dcdb3cd91ba/href">https://medium.com/media/5cfac449e22196d0ea2b1dcdb3cd91ba/href</a></iframe><ul><li>Line 8–19: Declaration of Structs to match the structure of the returned JSON.</li><li>Line 22: Mocked JSON response of type string.</li><li>Line 24: Instantiate jsonResponse of type JSONResponse.</li><li>Line 25: Unmarshal data from the JSON string and into the jsonResponse variable, the Go tags `json:&quot;headers&quot;` etc. enable specific JSON key values to be loaded into the appropriate variables within the struct.</li><li>Line 25: The unmarshal function requires the JSON data to be passed in a byte array which is why we cast the JSON string to a byte array.</li><li>Line 25: The unmarshal function requires a pointer of the variable to be passed in, this is why there is an ampersand (&amp;) before jsonResponse. &amp;jsonResponse is the memory location of jsonResponse see <a href="https://dave.cheney.net/2017/04/26/understand-go-pointers-in-less-than-800-words-or-your-money-back">here</a> for more information on pointers.</li><li>Line 27–29: Error check on unmarshalling.</li><li>Line 31: Printing the jsonResponse Go variable which now contains the data that was in the JSON string.</li><li>Line 35–36: Access field with the JSONResponse struct with dot notation ie. jsonResponse.Url and jsonResponse.Headers.Host</li></ul><p>Try it out for yourself here <a href="https://play.golang.org/p/sPSfEczBiU1">https://play.golang.org/p/oqFjZii_yjA</a>.</p><h3>Parsing into an Interface</h3><p>We now know that we can parse JSON into a map[string]interface{} type if we are unsure of the value types or the key names that are going to be used in the JSON. If we look at the previous example and imagine values were passed in via the URL (<a href="https://httpbin.org/get?testArg=testValue&amp;x=3">https://httpbin.org/get?testArg=testValue&amp;x=3</a>) to result in,</p><pre>&quot;args&quot;: {<br>  &quot;testArg&quot;: &quot;testValue&quot;,<br>  &quot;x&quot;: &quot;3&quot;<br>}</pre><p>These values can be accessed simply by referencing jsonResponse.Args[&quot;testArg&quot;] and jsonResponse.Args[&quot;x&quot;]. Take a look here <a href="https://play.golang.org/p/WehVIkK8CRd">https://play.golang.org/p/WehVIkK8CRd</a>, I’ve updated the mocked JSON to include the values within the “args” object and added 2 print statements at the end to show you how to access the values.</p><p>Hopefully this has helped you gain a better understanding of how to work with JSON in Go. As always any feedback is welcome and please let me know if I’ve made any mistakes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e889c29a83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/json-in-golang-an-introduction-8e889c29a83">JSON in Golang an Introduction</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>