<?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 Forest Fang on Medium]]></title>
        <description><![CDATA[Stories by Forest Fang on Medium]]></description>
        <link>https://medium.com/@saurfang?source=rss-5d668b546d10------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MHu4hEqyGYrDQNTJ.</url>
            <title>Stories by Forest Fang on Medium</title>
            <link>https://medium.com/@saurfang?source=rss-5d668b546d10------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 18 Apr 2026 21:42:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saurfang/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[ERC809/1201: Tokenizing Non-fungible Access]]></title>
            <link>https://medium.com/coinmonks/erc809-1201-tokenizing-non-fungible-access-abdc5018c49?source=rss-5d668b546d10------2</link>
            <guid isPermaLink="false">https://medium.com/p/abdc5018c49</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[erc]]></category>
            <dc:creator><![CDATA[Forest Fang]]></dc:creator>
            <pubDate>Sun, 02 Sep 2018 10:02:39 GMT</pubDate>
            <atom:updated>2018-12-11T09:26:48.093Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9SiR2o2LXUMG9JDJ_4V1g.png" /></figure><p>NFT (<a href="https://hackernoon.com/an-overview-of-non-fungible-tokens-5f140c32a70a">Non-fungible Token</a>) has been one of the most exciting developments in the Ethereum ecosystem. The <a href="http://erc721.org/">ERC721</a> standard, in particular, gave a common language to create on-chain token that represents non-fungible assets. Some of the most popular examples include <a href="https://www.cryptokitties.co/">CryptoKitties</a>, <a href="https://decentraland.org/">Decentraland</a>, and <a href="https://www.larvalabs.com/cryptopunks">CryptoPunks</a>.</p><p>While the canonical use case of non-fungible tokens and ERC721 has been digital or digitized collectibles, we can use the same framework to tokenize ownership of other sorts such as rental rights of a non-fungible asset.</p><p>For example, <a href="https://medium.com/@booklocal/hotel-booking-and-guest-management-on-the-ethereum-blockchain-beddcfa2040">BookLocal</a> proposed <a href="https://github.com/ethereum/EIPs/issues/809">ERC809</a> as a standard for rental rights over rival non-fungible tokens. <a href="https://github.com/ethereum/EIPs/issues/1201">ERC1201</a> explores the same topic with an improved approach. In this post, I am excited to present <a href="http://meeteth.io/"><strong>MeetETH</strong></a><strong>, a proof of concept implementation </strong>of the above token standard proposals<strong> to tokenize ephemeral access rights to non-fungible tokens</strong>. I will discuss the technical challenges compared to digital collectible ERC721 tokens, and why ERC809/1201 can become fundamental building blocks for profound use cases such as traffic planning for autonomous vehicles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*DHfs-1dl95-t0oAo.jpg" /><figcaption>Tokenize ALL THE THINGS!</figcaption></figure><h3>Introducing MeetETH</h3><p><a href="http://meeteth.io">MeetETH</a> is a scheduling Dapp that allows user to create tokenized calendar bound to an Ethereum account and invite other users to create tokenized reservations on such calendars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EW4lAvgP9Tg_tmbXD2UzUw.gif" /><figcaption>Schedule Tokenized Event on a Tokenized Calendar</figcaption></figure><p>The Dapp and its smart contracts manage two set of tokens: <a href="https://github.com/saurfang/meeteth/blob/master/contracts/Calendar.sol">Calendar</a> and <a href="https://github.com/saurfang/meeteth/blob/master/contracts/Reservation.sol">Reservation</a>. Let us consider <strong>short term rental properties as a concrete example</strong> since this is what ERC809 and ERC1201 were designed to do.</p><p>A property owner or manager who wants to list an accommodation space online can create a <strong>Calendar token</strong> for each of her listing as a row of calendar dates shown below. A guest can then reserve a block of time for a specific calendar by minting a <strong>Reservation token that is associated with the particular Calendar token with a start and end date time</strong>. That is to say each Reservation token represents a block on the corresponding calendar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yw_1iAKpAvVor0LeNLm-Rw.png" /><figcaption>A Hypothetical MultiCalendar View for Rental Property Management</figcaption></figure><p>In MeetETH, <strong>both Calendar and Reservation tokens are ERC721 tokens</strong>. This means we get wallet, transfer, and trading support for free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*av9k5fi2-fjtKYo50KpLqA.gif" /><figcaption>Transfer a Reservation — No Different from Transferring a CryptoKitty</figcaption></figure><p>This also opens the door to a secondary market of rental rights that can <strong>reuse a lot of NFT infrastructure we are already building today. </strong>One might ask what if I want some form of guest verification or simply banning secondary trading altogether. This is feasible indeed <strong>because we conform to ERC721 token standard</strong> first and foremost. Exchange protocols such as 0x have already been exploring <a href="https://blog.0xproject.com/compliant-peer-to-peer-trading-4dab8e5c3162">compliant peer-to-peer trading</a>. We could <strong>deploy a permissioned Calendar token</strong> such that each Calendar owner can set their desired secondary trading/transfer restrictions. <strong>The power of composing token standards and get free interoperable infrastructure is one of the killing applications of Smart Contract.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*21Wmt6V68NwHVvW-VoBm-w.gif" /><figcaption>Cancel a Reservation = Burn the Token = Transfer to 0x000..0</figcaption></figure><h3>Why it matters</h3><p>While the interactions in MeetETH may look simple, it can be generalized to many exciting use cases. At its core, this is about <strong>reserving an ephemeral access to a </strong><a href="https://en.wikipedia.org/wiki/Rivalry_(economics)"><strong>non-rival goods</strong></a><strong>.</strong></p><p><strong>Human to Human Reservations</strong></p><p>Doctor appointments are often made weeks in advance in U.S. and people often have to choose between expensive emergency care and week long wait for an appointment. Doctor offices often spend a ten of time and resource calling patients to juggle appointments based on patient’s schedule and preferences.</p><p>A tokenized reservation would allow patients to easily swap reservation time and guardrails can be set up in smart contract to prevent squatting and scalping. Furthermore, as ERC809 inherits ERC721, the token can be traded using common protocol such as <a href="https://blog.0xproject.com/introducing-0x-protocol-v2-9f5bda04d38d">0x</a> or common exchanges such as <a href="https://opensea.io/">OpenSea</a> and <a href="https://rarebits.io/">RareBits</a> which dramatically <strong>reduces engineering work, increases liquidity, and lowers cost</strong>.</p><p>Lastly, doctors with common practice area could participate in a <a href="https://hackernoon.com/token-curated-registry-tcr-design-patterns-4de6d18efa15"><strong>TCR</strong></a> where <strong>access to healthcare can be efficiently pooled among doctors who have similar experience, reputation, and expertise</strong>.</p><p><strong>Human to Machine Reservations</strong></p><p>It is not difficult to see how such calendars can belong to other smart contracts as well. For example, one can reserve a self-driving car for a multi-day trip. One may also reserve a cloud computing resource at a pre-agreed price akin to AWS reserved instances.</p><p><strong>Machine to Machine</strong> <strong>Reservations</strong></p><p>This naturally extends to machine to machine as well. A self-driving autonomous vehicle can manage its own wallet and bids for rides. When providing the ride, it communicates with <a href="https://startupboy.com/2014/04/01/the-fifth-protocol/">traffic management smart contract</a> to bid and reserve the right of road at an intersection. When it does its route planning, it can precisely calculate the time it enters and leaves each intersection, and can further trade the right of road as traffic condition changes. The existence of such market for public goods enables price discovery and creates an incentive structure to prioritize shared resources that were traditionally difficult to value or allocate equitably. <strong>This provides a framework to represent rights of road that supports decentralized planning and real time calibration.</strong></p><h3>A Two-Tier Token Approach</h3><p>Last but not least, I would like to present MeetETH’s smart contract architecture and my proposal to improve the design of ERC809/1201 token standard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*VxLTZY4C6DqJ5YFP3XnHsQ.png" /><figcaption>ERC809 Proposal (Simplified)</figcaption></figure><p><a href="https://github.com/ethereum/EIPs/issues/809">ERC809</a> proposed to add additional functions on top of ERC721 to “allow an owner to rent access to their rival NFTs using a standard set of commands, thus allowing users to view all past and current rental agreements from a single wallet interface.”</p><p>One of the shortcomings stems from the fact the “rental rights” itself is not a token. Therefore there is no easy way to query the renter or transfer the reservation.</p><p>It is worth noting that this was a logical choice for the use case of BookLocal, a platform for rental property management. I thought it was sensible to abstract each property room as a unit of NFT but later realized that <strong>renting a NFT is often times different from owning the NFT over a period of time</strong>. Having a token that grants me access to a vacation rental property does not equal to owning a token that represents the ownership of the property: I cannot modify, sell, or destroy the place as if I am the owner however short or long my reservation may be. That is to say a NFT represents the management of renting out a property is different from another NFT represents property deeds.<strong> </strong>In other words, <strong>a physical object can have different digital NFTs for different purposes.</strong></p><p>@<a href="https://github.com/hyperfekt">hyperfekt</a> gave the brilliant suggestion that individual reservation should also be treated as NFT as well. This is what <a href="https://github.com/ethereum/EIPs/issues/1201">ERC1201</a> sets out to accomplish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MoqyDiHHsNCWnNFFHE6h3Q.png" /><figcaption>ERC1201</figcaption></figure><p>Each ERC1201 ownership token manages the reservations according to its own inventory. In addition, each reservation mints one or more reservation token(s) by unit of reserved time (e.g. day.) In other words, <strong>ERC1201 reservation token is two dimensional: NFT assets (rows) by time slots (columns.) </strong>Take rental property example above, each reservation token maps to a calendar square in the multi-calendar. A traveler who books a two nights trip will receive two ERC1201 tokens representing each night.</p><p>This is a good step forward from ERC809 but the rental tokens mostly duplicate ERC721 functions with rental prefix. This greatly hinders interoperability of this contract. <strong>The ability to display, transfer, and trade access rights (Reservation token) is much more desirable than perform these operations to the management (Calendar token). </strong>Under this approach, we would need to rebuild wallet and exchange to support ERC1201. Fortunately, we can do better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwkR_NstAhuISF36zBAgyg.png" /><figcaption>Proposed ERC809/1201 Two Tier Token Architecture</figcaption></figure><p>Since it is evident that both ownership and reservation tokens are valid NFT, MeetETH proposes a <strong>paired smart contracts architecture</strong>: <strong>ERC809 and ERC809Child, both inheriting ERC721</strong>. Furthermore, ERC809 has a contract immutable variable that points to the ERC809Child so information can be shared and synchronized.</p><p>Notice ERC809 and ERC809Child are rather simple and missing the reserve function. This is intentional. Just like ERC721 does not have mint function as part of the standard, the reserve action has a lot of variables that we cannot account for: whether user pays now or later, what auxiliary data is required at the time of reservation, whether the reservation is instantly accepted or require further approval and etc. With such amount of variance, it is difficult to design a reserve interface that is useful across implementations.</p><p>In practice, this is how MeetETH implements <a href="https://github.com/saurfang/meeteth/blob/master/contracts/Calendar.sol">Calendar.sol</a> and <a href="https://github.com/saurfang/meeteth/blob/master/contracts/Reservation.sol">Reservation.sol </a>implementing ERC809 and ERC809Child respectively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DobsqftGkHxaQcarnJ9kMA.png" /><figcaption>Proposed ERC809/1201 Two Tier Token Architecture</figcaption></figure><p>In a way the two smart contracts are rather coupled: to make a reservation, user needs to interact with Calendar smart contract because the owner of Calendar sets the availability and keep track of the sold inventory. Meanwhile, Calendar smart contract needs to mint the Reservation token by calling the Reservation contract. The same applies to cancellation. The heavy lifting, checking availability, has been implemented in the Calendar contract because we feel the complexity belongs to the owner who could setup complicated calendar rules or even use Oracles to enforce availability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*EIChvS3fDy9bajiD.jpg" /><figcaption>Everybody wins!</figcaption></figure><p>There is big upsides to this approach. We eliminated the trade off between favoring either owner and renter.</p><p><strong>Since Ownership and Reservation tokens are both ERC721, we can leverage existing infrastructures for wallet, transfer, and exchange support.</strong></p><p>When we design token standard, it is not only important to think how smart contract can empower a decentralized solution, but also how we can build on top of others’ ideas and work.</p><p><strong>Whenever we can solve problems by composing ideas and standards (e.g. </strong><a href="https://medium.com/coinmonks/introducing-crypto-composables-ee5701fde217"><strong>Token Composables</strong></a><strong>), we be rewarded with interoperable protocols and infrastructure</strong>. Software engineering has long recognized the importance of code reuse and open source. Composing token standard not only let us reuse the smart contract implementations but also strengthen the underneath economy and protocol at the same time.</p><h3>Next Steps and Acknowledgments</h3><p>Neither ERC809 and ERC1201 are close to a mature state and this post is just another possible improvement to this standard which contains great potential. I welcome thoughts and suggestions and look forward to someone building on top my idea and proposing something better. I listed a few <a href="https://github.com/saurfang/meeteth#roadmap">ideas</a> I have not yet explored and they may or may be relevant to the common standard. Last but not least, this has been a more of intellectual exploration for me, thanks to <a href="https://github.com/saurfang/consensys-academy-2018-final-project">Consensys Academy</a>, and I would love to see someone to take this standard and build real world applications.</p><p>Finally, I would like to acknowledge <a href="https://medium.com/u/b8117209847f">BookLocal</a> team for proposing the ERC809 standard and sponsoring @<a href="https://twitter.com/ethmemphis?lang=en">ETHMemphis</a>, <a href="https://medium.com/u/68a3489944ac">Zeming Yu</a> for sharing his thoughts and discussing ERC809 with me, working through and proposing ERC1201 as an enhancement, and <a href="https://medium.com/u/3199e60ae2b1">Matt Condon</a> for his <a href="https://github.com/ethereum/eips/issues/1155#issuecomment-400044803">thought provoking comment</a> in <a href="https://github.com/ethereum/eips/issues/1155">ERC1155</a> which challenged me and helped me arriving this solution. Shoutout also goes to <a href="https://medium.com/u/c0cacba41b4d">Brian Flynn</a> for his awesome NFTY newsletter that expanded my mind a lot about NFT.</p><figure><a href="http://bit.ly/2G71Sp7"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKX2mtg7p1lOs7JmosPLsA.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abdc5018c49" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/erc809-1201-tokenizing-non-fungible-access-abdc5018c49">ERC809/1201: Tokenizing Non-fungible Access</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[Solidity Import in VS Code: The Right Way]]></title>
            <link>https://medium.com/coinmonks/solidity-import-in-vs-code-the-right-way-82baa1cc5a71?source=rss-5d668b546d10------2</link>
            <guid isPermaLink="false">https://medium.com/p/82baa1cc5a71</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Forest Fang]]></dc:creator>
            <pubDate>Tue, 03 Jul 2018 03:06:10 GMT</pubDate>
            <atom:updated>2019-07-04T13:47:16.452Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Import Solidity Files in VS Code with IDE Support</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXcolG63_Wpwl5VOYt2xuQ.png" /><figcaption>Let IDE work for you.</figcaption></figure><p>For the longest time, I thought it was a lost cause making my VS Code happy with external Solidity file import (in <a href="https://truffleframework.com/docs/getting_started/packages-npm#within-your-contracts">the way</a> Truffle wants me to). I coped with the red screaming squiggly lines. I learned to ignore and 😒.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWwJYjwyKTuusJvf08loiQ.png" /><figcaption>Enough is enough.</figcaption></figure><h3>TLDR</h3><p>If you are setting up a standard truffle project via `truffle init` or `truffle unbox`, you can use the following <a href="https://code.visualstudio.com/docs/getstarted/settings">settings</a> in VS Code:</p><pre>&quot;solidity.packageDefaultDependenciesContractsDirectory&quot;: &quot;&quot;,<br>&quot;solidity.packageDefaultDependenciesDirectory&quot;: &quot;node_modules&quot;</pre><p>Import from an <a href="https://truffleframework.com/docs/getting_started/compile#importing-contracts-from-an-external-package">external package</a> as usual (after installing using npm) like so:</p><pre>import &quot;openzeppelin-solidity/contracts/math/SafeMath.sol&quot;;</pre><p>Happy Solidity hacking with error-free IDE, autocompletion, and definition lookup.</p><h3>Why (proper) Import is useful</h3><p>With the proper setup, Solidity plugin can source autocompletion from all imported files (and their children imports too.) The autocompletion is <a href="https://github.com/juanfranblanco/vscode-solidity/issues/58">not yet contextual</a> but gives some information on where the completion element is defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b3ZF74oFmfzru-ZH.png" /><figcaption>Two <strong>totalSupply()</strong> functions: one from BasicToken.sol and the other from ERC20.sol which BasicToken inherits</figcaption></figure><p>With <a href="https://github.com/juanfranblanco/vscode-solidity/pull/80#event-1711277730">latest version</a>, you can jump to definitions of external imports as well as variables and functions defined in the external packages 🎉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*CzFxt4leGLews1haRVtkbA.gif" /></figure><p>I contributed the functionality by implementing the corresponding event in LSP (<a href="https://code.visualstudio.com/docs/extensionAPI/language-support#_show-definitions-of-a-symbol">Language Server Protocol</a>) so potentially it can be used in other IDEs (Atom, Sublime, Remix) as well. <strong>There are still many features we can implement for Go to Definition and LSP in general in VSCode Solidity. Head over to </strong><a href="https://github.com/juanfranblanco/vscode-solidity/"><strong>Github</strong></a><strong> and join the #BUIDL train if you have something on your wish list.</strong></p><h3>How does Import work in Solidity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*WJU4vJLUYkvWRRl4PoqVVg.gif" /></figure><p>Read on for back stories on my resolved frustration and nasty stuff under the rug of Solidity, Truffle, and VSCode Solidity plugin.</p><p>It was an ordinary night when I got increasingly irritated 🤬 (again!) by:</p><ul><li>me not remembering contract constructor signature I was inheriting from</li><li>OpenZeppelin keeping changing contract implementation and interfaces (for good reasons)</li><li>VS code Solidity plugin not letting me jump to the file I imported</li><li>OpenZeppelin contract being c̶o̶n̶v̶o̶l̶u̶t̶e̶d̶l̶y̶ ̶n̶e̶s̶t̶e̶d̶ categorized in nested folders</li><li>and VS code not allowing search in node_modules by default.</li></ul><p>I decided to turn my endless mouse clicking and scrolling into more productive detective funzies (insert distracted programmer jokes.) Apparently, this was <a href="https://github.com/juanfranblanco/vscode-solidity/issues/70">not</a> <a href="https://github.com/juanfranblanco/vscode-solidity/issues/31">an</a> <a href="https://github.com/juanfranblanco/vscode-solidity/issues/54">uncommon</a> <a href="https://github.com/juanfranblanco/vscode-solidity/issues/78">issue</a> and (shockingly) the Solidity plugin is designed to <a href="https://github.com/juanfranblanco/vscode-solidity#solidity-support-for-visual-studio-code">work with import</a> 🤔.</p><p>The answer lies in the two settings mentioned before, <strong>packageDefaultDependenciesContractsDirectory</strong> and <strong>packageDefaultDependenciesDirectory</strong>, and the fact that Solidity has no standard on how to reference <a href="http://solidity.readthedocs.io/en/develop/layout-of-source-files.html?#importing-other-source-files">external package import</a>.</p><p>For non-local imports (the one doesn’t start with “.” and isn’t absolute path), the compiler uses its discretion on how to apply the <a href="http://solidity.readthedocs.io/en/develop/layout-of-source-files.html?#use-in-actual-compilers">remapping to resolve the import</a>:</p><blockquote>When the compiler is invoked, it is not only possible to specify how to discover the first element of a path, but it is possible to specify path prefix remappings so that e.g. github.com/ethereum/dapp-bin/library is remapped to /usr/local/dapp-bin/library and the compiler will read the files from there.</blockquote><p><strong>Truffle</strong></p><p>Truffle uses <a href="https://github.com/trufflesuite/truffle/tree/7205c9e91c8c3de4996cf9eb679446d5c0b2810e/packages/truffle-resolver">truffle-resolver</a> to resolve dependencies from <a href="https://truffleframework.com/docs/getting_started/packages-ethpm">EthPM</a> and <a href="https://truffleframework.com/docs/getting_started/packages-npm">NPM</a>. For NPM specifically, it <a href="https://github.com/trufflesuite/truffle/blob/c603524f3036f8d3d19641ca774b1133a5142a6e/packages/truffle-resolver/npm.js#L34">looks for packages</a> under <strong>node_modules</strong> and replace the prefix with the file system path only.</p><p>In addition, Truffle states a Truffle project should use <strong>/contracts</strong> to store <strong>*.sol</strong> files and <strong>/build(/contracts)</strong> for build output. However, the resolver does not enforce this project structure since not all npm Solidity packages follow this layout.</p><p>Therefore we import by package name followed with relative path from the root of the npm package. For <a href="https://github.com/OpenZeppelin/openzeppelin-solidity/tree/master/contracts">openzeppelin-solidity</a>, we use</p><pre>import &quot;<strong>openzeppelin-solidity</strong>/contracts/math/SafeMath.sol&quot;;</pre><p><strong>VSCode Solidity</strong></p><p>VSCode Solidity extension provides two settings with <a href="https://github.com/juanfranblanco/vscode-solidity/blob/9fc69464314b3f07c02aee3473464608ebba3848/package.json#L143">default values</a> to control how external dependencies are resolved:</p><ul><li><strong>solidity.packageDefaultDependenciesDirectory: </strong>node_modules</li><li><strong>solidity.packageDefaultDependenciesContractsDirectory: </strong>contracts</li></ul><p><strong>packageDefaultDependenciesDirectory </strong>adds a prefix to the package and resolves from the project root. <strong>packageDefaultDependenciesContractsDirectory </strong>specifies where to find *.sol files inside an external package.</p><pre>import &quot;package/folder1/contract.sol&quot;;</pre><p>expands to</p><pre>import &quot;{<strong>projectRoot</strong>}/{<strong>packageDefaultDependenciesDirectory</strong>}/package/{<strong>packageDefaultDependenciesContractsDirectory</strong>}/folder1/contract.sol&quot;;</pre><p>While the default value <strong>contracts</strong> may look innocent, it actually creates a duplicate in a Truffle project. The previous import would expands to</p><pre>import &quot;{<strong>projectRoot</strong>}/<strong>node_modules</strong>/openzeppelin-solidity/<strong>contracts</strong>/contracts/math/SafeMath.sol&quot;;</pre><p>Oops. Setting <strong>packageDefaultDependenciesContractsDirectory</strong> to empty would conform to Truffle standard 🧐.</p><h3>Bonus Tip🤫</h3><p>Have you been frustrated when VSCode closes every file that you opened for reference but not editing? This turns out to be a <a href="https://code.visualstudio.com/docs/getstarted/userinterface#_preview-mode">feature</a> (?!) not a bug. <strong>You can pin a file to exit preview mode by double clicking the file or tab header.</strong> You can also disable preview mode in certain condition or altogether in the setting.</p><p>I can understand how this is useful to keep my workspace clean but I found often this feature counter-productive. Would it be better if the file closes itself after some time of inactivity or tuck itself away in the tab list?</p><h3>Acknowledgment</h3><p>Last but not least I would like to acknowledge <a href="https://medium.com/u/f35d0f682616">Juan Blanco</a> authoring and <a href="https://github.com/juanfranblanco/vscode-solidity#credits">all other contributors</a> before me for the amazing VSCode Solidity plugin. Go star <a href="https://github.com/juanfranblanco/vscode-solidity">the repo</a> to show your love today!</p><figure><a href="https://cryptofi.co"><img alt="" src="https://cdn-images-1.medium.com/max/407/1*HrFLDXz92JavTZXjhmvU7g.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82baa1cc5a71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/solidity-import-in-vs-code-the-right-way-82baa1cc5a71">Solidity Import in VS Code: The Right Way</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[Let’s Play — Capture the Ether : Lotteries (Part II)]]></title>
            <link>https://medium.com/@saurfang/lets-play-capture-the-ether-lotteries-part-ii-478365775a34?source=rss-5d668b546d10------2</link>
            <guid isPermaLink="false">https://medium.com/p/478365775a34</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Forest Fang]]></dc:creator>
            <pubDate>Sun, 15 Apr 2018 07:24:00 GMT</pubDate>
            <atom:updated>2018-04-15T07:59:20.397Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Play — Capture the Ether : Lotteries (Part II)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vb4OZmcEooyqvZx9NZ1fvA.png" /></figure><p>This is the third installment of stories on my journey of <a href="https://capturetheether.com/">Capture the Ether</a>, a game where we hack Ethereum Solidity code for fun and learn about smart contract security. Read the <a href="https://medium.com/@saurfang/lets-play-capture-the-ether-warmup-68a5fc38e670">introduction post</a> for background, what to expect, and link to other sections.</p><h3>What is Capture the Ether?</h3><p>In <em>Capture the Ether</em>, we win points by completing challenges. Each challenge comes with a smart contract to deploy and objectives can be completed by exploiting the contract into a specific state. Challenges are grouped into categories that focus on specific areas of security vulnerabilities in smart contracts.</p><h3>Spoiler Alert</h3><p>We will cover <a href="https://capturetheether.com/challenges/lotteries/guess-the-new-number/">Guess the new number</a>, <a href="https://capturetheether.com/challenges/lotteries/predict-the-future/">Predict the future</a>, and <a href="https://capturetheether.com/challenges/lotteries/predict-the-block-hash/">Predict the block hash</a> challenges in this article. These challenges demonstrate <strong>it is difficult to source randomness from a deterministic programming model in EVM</strong>.</p><p><strong>I recommend you read, think about, attempt the problem on your own first.</strong> For each problem, I will discuss the high level approach followed by detailed solution.</p><h3>Guess the new number</h3><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fethfiddle.com%2FybIopBd_5u&amp;src=https%3A%2F%2Fethfiddle.com%2Fservices%2Fiframesnippet%2FybIopBd_5u&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=ethfiddle" width="300" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/499e58ae7cf418b85d2ea5e3949bbb7f/href">https://medium.com/media/499e58ae7cf418b85d2ea5e3949bbb7f/href</a></iframe><h4>Approach</h4><p>This time we need to know the current block timestamp before we send transaction.</p><p>This may seems impossible first, except that if we mine the blocks ourself, we can inject transaction with a timestamp that we will use in our current block header. This is related to <a href="https://blog.0xproject.com/front-running-griefing-and-the-perils-of-virtual-settlement-part-1-8554ab283e97?gi=4f4cdf27ea8b"><strong>miner front-running </strong></a>commonly found in decentralized exchange implementation. That is, miner might have mis-aligned incentive when transactions are public and the transaction has economic value. They can sway miners’ behaviors away from fair incentive provided by gas collected in the block. <strong>Therefore it is almost never a good idea to use block hash or timestamp as a source of randomness whether or not it could be programmatically exploited or not.</strong></p><p>On the other hand, there is a far easier way to exploit this contract by simply creating a relay contract that compute the answer itself before sending transaction to the GuessTheNewNumberChallenge contract. The reward Ether can then be passed back to your account as the original sender.</p><h4>Solution Details</h4><p>While it is perfectly feasible to write this relay contract in Remix, you will likely need to spend some moments debug this one as it has some hidden pitfalls if you haven’t called another contract from Solidity before.</p><p>We will introduce you to the <a href="http://truffleframework.com/"><strong>Truffle</strong></a><strong> framework which helps you to scaffold, organize, compile, test and deploy your </strong><a href="https://ethereum.stackexchange.com/questions/383/what-is-a-dapp"><strong>DApp</strong></a><strong> (Decentralized Application)</strong>. It excels at building web application that directly interacts with blockchain with or without a centralized server. Today we will only use it to compile and test our Solidity smart contract.</p><p>Truffle has excellent tutorials (e.g. your decentralized <a href="http://truffleframework.com/tutorials/pet-shop">Pet Shop</a>) and project starting templates called <a href="http://truffleframework.com/boxes/">boxes</a>. We will begin with a blank template instead:</p><pre>npm install -g truffle<br>mkdir capture-the-ether &amp;&amp; cd capture-the-ether<br>truffle init</pre><p>Next we will import the challenge contract code into contracts/GuessTheNewNumberChallenge.sol and add test skeleton in test/GuessTheNewNumberChallenge.test.js .<strong> I recommend using </strong><a href="http://truffleframework.com/tutorials/configuring-visual-studio-code"><strong>Visual Studio Code with Solidity plugin</strong></a><strong> as your IDE.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81fc5261fb70b998d105f480778fcd45/href">https://medium.com/media/81fc5261fb70b998d105f480778fcd45/href</a></iframe><p>We can enter <a href="http://truffleframework.com/docs/getting_started/console">Truffle development console</a> with truffle develop which spawns a development blockchain. You will be greeted with ten test accounts with 100 ether loaded in each account.</p><p>Now let’s run migrate --reset to compile our challenge contract, and test to give our unit test a try.</p><pre>truffle(develop)&gt; test<br>Using network &#39;develop&#39;.</pre><pre>Contract: GuessTheNewNumberChallenge<br>    1) should be completed<br>    &gt; No events were emitted</pre><pre>0 passing (91ms)<br>  1 failing</pre><pre>1) Contract: GuessTheNewNumberChallenge should be completed:<br>     AssertionError: Challenge has not been completed!<br>      at Context.it (test/GuessTheNewNumberChallenge.test.js:7:5)<br>      at &lt;anonymous&gt;<br>      at process._tickCallback (internal/process/next_tick.js:182:7)</pre><p>We see test fails as expected since isComplete is false in the beginning. 🎉<strong> I hope you enjoy the </strong><strong>async/await syntax after drowning in the callback hell from previous sessions.</strong></p><p>Next we will add the solver contract that will call the challenge contract and relay the computed guess.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b170d14b741157cd805272216e4d1ced/href">https://medium.com/media/b170d14b741157cd805272216e4d1ced/href</a></iframe><p>To start, we simply relay the isComplete function as a simple test. Running migrate and test should print the same failure message we saw before.</p><p>With that let’s implement the guess function and modify the test like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdedc27a32360559a50a8f34d5476268/href">https://medium.com/media/fdedc27a32360559a50a8f34d5476268/href</a></iframe><p>Running migrate and test , we got this daunting error:</p><pre>truffle(develop)&gt; test<br>Using network &#39;develop&#39;.</pre><pre>Contract: GuessTheNewNumberSolver<br>    1) should solve the challenge<br>    &gt; No events were emitted</pre><pre>0 passing (261ms)<br>  1 failing</pre><pre>1) Contract: GuessTheNewNumberSolver should solve the challenge:<br>     Error: VM Exception while processing transaction: revert<br>      at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)<br>      at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1<br>      at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-provider/wrapper.js:134:1</pre><p>What happened? revert happens when <a href="http://solidity.readthedocs.io/en/v0.4.21/control-structures.html#error-handling-assert-require-revert-and-exceptions">there is no safe way to continue execution</a> and all changes are reverted rendering whole transaction effect-less.</p><p>Below is an excellent tutorial debugging smart contract via stepping through the execution code. One thing to call out is <strong>truffle develop --log starts a development console without interactive prompt. This is intentional as </strong><strong>truffle develop --log is meant to be run side by side with </strong><strong>truffle develop .</strong></p><p><a href="http://truffleframework.com/tutorials/debugging-a-smart-contract">Debugging a smart contract | Truffle Suite</a></p><p>For our purpose, you should run truffle develop --log in a separate session, and as you run test in the original console, you should see transaction hash being logged:</p><pre>develop:testrpc eth_sendTransaction +7ms<br>  develop:testrpc  +115ms<br><strong>  develop:testrpc   Transaction: 0x71f23cf0b6e38b71c0ad1e3bd5bb6644cebf8d1688bf7cad06d511d642ff3a1e +0ms</strong><br>  develop:testrpc   Gas usage: 39241 +0ms<br>  develop:testrpc   Block Number: 320 +0ms<br>  develop:testrpc   Block Time: Sat Apr 14 2018 19:00:39 GMT-0700 (PDT) +1ms<br>  develop:testrpc   Runtime Error: revert +0ms<br>  develop:testrpc  +0ms<br>  develop:testrpc eth_getLogs +8ms</pre><p>We can use this hash in the development console to replay the transaction in debug mode: debug &lt;tx hash found in develop --log console&gt;</p><p>As we step into GuessTheNewNumberChallenge we found we made it through n == answer just fine, and returned back to GuessTheNewNumberSolver after msg.sender.transfer(2 ether); just before triggering <strong>revert</strong>.</p><p>If we experiment commenting out msg.sender.transfer(2 ether); , the transaction went through fine. The test still fails since the challenge contract didn’t empty its pocket even when guess is correct.</p><p>So what gives? 😕 The answer lies in <a href="http://solidity.readthedocs.io/en/v0.4.21/contracts.html#fallback-function">Fallback Function</a>:</p><blockquote>A contract can have exactly one unnamed function. This function cannot have arguments and cannot return anything. It is executed on a call to the contract if none of the other functions match the given function identifier (or if no data was supplied at all).</blockquote><blockquote>Furthermore, <strong>this function is executed whenever the contract receives plain Ether (without data)</strong>. Additionally, in order to receive Ether, the fallback function must be marked payable. If no such function exists, the contract cannot receive Ether through regular transactions.</blockquote><p>Now we think about it, we never specified what happened when the relay contract gets paid with 2 ether. You don’t want to lose your ether, do you? 🙄</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92cc9e630a546315b8b183d73c8be714/href">https://medium.com/media/92cc9e630a546315b8b183d73c8be714/href</a></iframe><p>We implement the fallback to send the ether back to us. Since we do not have access to the original msg.sender anymore, we need to remember the owner of the contract during deploy time with the constructor function.</p><p>🤞Does it work? Nope…we still get Error: VM Exception while processing transaction: revert . If we run debugger again, we found the error now stems from owner.transfer(msg.value); and if we comment out that line we are able to complete the challenge (and lose our 2 ethers 😢)</p><p>Maybe you are smarter than I was and read the full documentation before:</p><blockquote>In the worst case, <strong>the fallback function can only rely on 2300 gas being available</strong> (for example when send or transfer is used), leaving not much room to perform other operations except basic logging. The following operations will consume more gas than the 2300 gas stipend:</blockquote><blockquote>* Writing to storage</blockquote><blockquote>* Creating a contract</blockquote><blockquote>* Calling an external function which consumes a large amount of gas</blockquote><blockquote><strong>* Sending Ether</strong></blockquote><p>Fallback function in fact cannot send ether due to lack of gas. Therefore we need to add a withdraw function:</p><pre>function () public payable { }</pre><pre>function withdraw() public {</pre><pre>  require(msg.sender == owner);</pre><pre>  owner.transfer(address(this).balance);</pre><pre>}</pre><p>Now our test should happily pass:</p><pre>truffle(develop)&gt; test<br>Using network &#39;develop&#39;.</pre><pre>Compiling ./contracts/GuessTheNewNumberChallenge.sol...<br>Compiling ./contracts/GuessTheNewNumberSolver.sol...</pre><pre>Contract: GuessTheNewNumberSolver<br>    ✓ should solve the challenge (212ms)</pre><pre>1 passing (227ms)</pre><p><strong>A Word on Fallback Function</strong></p><p>Fallback function is a powerful feature for smart contract in Ethereum but it also comes with hidden complexity. Historically it has been misused by many contracts leading to massive loss of Ether such as the <a href="https://medium.com/@MyPaoG/explaining-the-dao-exploit-for-beginners-in-solidity-80ee84f0d470">DAO hack</a> and the <a href="https://medium.freecodecamp.org/a-hacker-stole-31m-of-ether-how-it-happened-and-what-it-means-for-ethereum-9e5dc29e33ce">Parity Multisig Wallet bug</a>.</p><p>Don’t be overly permissive in your smart contract code. <strong>The immutability of smart contract sometimes incentivizes developers away from being restrictive and at the same time make it impossible to fix any bugs when they surface.</strong> Developers have been experimenting with upgradable smart contracts using technique such as proxy contract. <a href="https://medium.com/level-k/flexible-upgradability-for-smart-contracts-9778d80d1638">[1]</a> <a href="https://medium.com/cardstack/upgradable-contracts-in-solidity-d5af87f0f913">[2]</a> <a href="https://blog.zeppelin.solutions/proxy-libraries-in-solidity-79fbe4b970fd">[3]</a></p><h4>Vulnerability Remediation</h4><p>It is possible to determine if an address is a contract address instead of a normal account by <a href="https://ethereum.stackexchange.com/questions/14015/using-evm-assembly-to-get-the-address-code-size/14016#14016">checking code size</a>. However it is debatable whether this is a good solution, namely this prevents smart contract interaction which is an outstanding feature of Ethereum smart contract.</p><h3>Predict the future</h3><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fethfiddle.com%2FobOLF0e3Q-&amp;src=https%3A%2F%2Fethfiddle.com%2Fservices%2Fiframesnippet%2FobOLF0e3Q-&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=ethfiddle" width="300" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/9791832e854f8cc904ef4ffd0e0213cd/href">https://medium.com/media/9791832e854f8cc904ef4ffd0e0213cd/href</a></iframe><h4>Approach</h4><p>The answer must be between 0 and 9.</p><p>guess is locked in in blocks before settle can be made.</p><p>By using a relay contract we can test if answer would be equal to settle .</p><p>In other words, the relay contract can avoid calling settle if the answer in the upcoming block is not the same as guess .</p><h4>Solution Details</h4><p>This looks to be a trivial extension of the last solution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/290b6a5bf186ac25f6c5b3ca6265acdb/href">https://medium.com/media/290b6a5bf186ac25f6c5b3ca6265acdb/href</a></iframe><p>We just need to make sure it was the relay contract calling lockInGuess so guesser validation can be satisfied at settle .</p><p><strong>If you find it tedious to keep trying your luck by authorizing Metamask transaction, you may consider exporting your private key and run an automated loop using web3.js instead.</strong></p><h3>Predict the block hash</h3><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fethfiddle.com%2FDnHtfnBh3_&amp;src=https%3A%2F%2Fethfiddle.com%2Fservices%2Fiframesnippet%2FDnHtfnBh3_&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=ethfiddle" width="300" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a7a6c362d2f0875b6bcc285b1b238ec/href">https://medium.com/media/5a7a6c362d2f0875b6bcc285b1b238ec/href</a></iframe><h4>Approach</h4><p>This one looks tricky since you need to know the result of block.blockhash(settlementBlockNumber); where settlementBlockNumber = block.number + 1</p><p>If you have been using Visual Studio Code with Solidity extension, you might have seen this <a href="https://github.com/duaraghav8/solium-plugin-security#list-of-rules">static analysis warning</a>: no-block-members (Discourage use of members ‘blockhash’ &amp; ‘timestamp’ (and alias ‘now’) of ‘block’ global variable)</p><p>There is a reason for that and there is plenty of <a href="http://solidity.readthedocs.io/en/v0.4.21/units-and-global-variables.html#block-and-transaction-properties">warnings</a> on the block.blockhash function itself.</p><p>In fact, block.blockhash becomes deterministic after certain conditions. If you haven’t figured it out yet, re-read the documentation again.</p><h4>Solution Details</h4><p>The secret lies in the implementation of block.blockhash :</p><blockquote>The block hashes are not available for all blocks for scalability reasons. You can only access the hashes of the most recent 256 blocks, all other values will be zero.</blockquote><p>So we simply need to wait for 256 blocks to settle with a guess of 0x . Let’s test this with Truffle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4fcf56777432345182ce3d2b6ea585e/href">https://medium.com/media/a4fcf56777432345182ce3d2b6ea585e/href</a></iframe><p>After a while, you should see the test passes! In real world, you can either check back on Etherscan to see how many block confirmation your lock in transaction has, or use web3.js to listen for new blocks event to wait for 256 blocks to pass.</p><h3>Conclusion</h3><p>In this post, you have learnt to write smart contract with Solidity and test with web3.js using the Truffle framework, reference and interact with another contract in Solidity, pitfalls of fallback function, and unreliability of block members as a source of randomness.</p><p>You can find most of the Solidity and web3.js test code at my Github.</p><p><a href="https://github.com/saurfang/capture-the-ether">saurfang/capture-the-ether</a></p><p>Next time, we will switch gears and look at the Math section to learn how to do math safely in Solidity and what can go wrong if we are not careful.</p><blockquote>Capture the Ether is brought to you by <a href="https://twitter.com/smarx">@smarx</a>, who blogs about smart contract development at <a href="https://programtheblockchain.com/">Program the Blockchain</a>.</blockquote><p>I am not affiliated with the game itself and the awesome company behind it. Views expressed are solely my own and do not express the views or opinions of any entity with which I have been, am now, and will be affiliated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=478365775a34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Play — Capture the Ether : Lotteries (Part I)]]></title>
            <link>https://medium.com/@saurfang/lets-play-capture-the-ether-lotteries-part-i-4e0b40687efd?source=rss-5d668b546d10------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e0b40687efd</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Forest Fang]]></dc:creator>
            <pubDate>Sat, 14 Apr 2018 23:23:10 GMT</pubDate>
            <atom:updated>2018-04-15T07:27:59.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Play — Capture the Ether : Lotteries (Part I)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vb4OZmcEooyqvZx9NZ1fvA.png" /></figure><p>This is the second installment of stories on my journey of <a href="https://capturetheether.com/">Capture the Ether</a>, a game where we hack Ethereum Solidity code for fun and learn about smart contract security. Read the <a href="https://medium.com/@saurfang/lets-play-capture-the-ether-warmup-68a5fc38e670">introduction post</a> for background, what to expect, and link to other sections.</p><h3>What is Capture the Ether?</h3><p>In <em>Capture the Ether</em>, we win points by completing challenges. Each challenge comes with a smart contract to deploy and objectives can be completed by exploiting the contract into a specific state. Challenges are grouped into categories that focus on specific areas of security vulnerabilities in smart contracts.</p><h3>Spoiler Alert</h3><p>We will cover <a href="https://capturetheether.com/challenges/lotteries/guess-the-number/"><em>Guess the number</em></a><em>, </em><a href="https://capturetheether.com/challenges/lotteries/guess-the-secret-number/"><em>Guess the secrete number</em></a><em>, and </em><a href="https://capturetheether.com/challenges/lotteries/guess-the-random-number/"><em>Guess the random number</em></a> challenges in this article. These challenges demonstrate <strong>it is difficult to store private information on a public blockchain or to source randomness from a deterministic programming model in EVM</strong>.</p><p><strong>I recommend you read, think about, attempt the problem on your own first.</strong> For each problem, I will discuss the high level approach followed by detailed solution.</p><h3>Guess the number</h3><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fethfiddle.com%2FovUCoW1Wpf&amp;src=https%3A%2F%2Fethfiddle.com%2Fservices%2Fiframesnippet%2FovUCoW1Wpf&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=ethfiddle" width="300" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/24260be92e94fc207e7c29299c563fed/href">https://medium.com/media/24260be92e94fc207e7c29299c563fed/href</a></iframe><h4>Approach</h4><p>We simply want n == answer == 42 therefore we just need to call guess(42) on the contract.</p><h4>Details</h4><p>You should already be a pro calling smart contraction function using transactions. The only difference this time is that we need to send ether along the function call because require(msg.value == 1 ether) .</p><h4>Web3.js</h4><p>To send ether in web3.js, simply add value in the transaction option:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79c5e49fc2eda816006a708b8d2cf6bf/href">https://medium.com/media/79c5e49fc2eda816006a708b8d2cf6bf/href</a></iframe><h4>Remix</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*dogi-zw2Fn3qd4f2-D3Peg.png" /></figure><p>To send transation with ether in Remix, use Value option on the top right.</p><p>You can choose units from the drop down menu from the right.</p><h3>Guess the secret number</h3><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fethfiddle.com%2FtILAYsEVWC&amp;src=https%3A%2F%2Fethfiddle.com%2Fservices%2Fiframesnippet%2FtILAYsEVWC&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=ethfiddle" width="300" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/886897f894bef9076ee7c0a4bbc1931c/href">https://medium.com/media/886897f894bef9076ee7c0a4bbc1931c/href</a></iframe><h4>Approach</h4><p>We would like to find the preimage that hashes into a specific hash using keccak256 , the <a href="https://ethereum.stackexchange.com/questions/550/which-cryptographic-hash-function-does-ethereum-use">hash function used by Ethereum</a>. Usually this would be very difficult because a good hash function like keccak256 has good <a href="https://en.wikipedia.org/wiki/Cryptographic_hash_function#Properties">preimage resistance</a>.</p><p>In this case, it is trivial because n has type <a href="http://solidity.readthedocs.io/en/v0.4.21/types.html#integers">uint8</a> and can only vary between 0 and 256 (2⁸). What remains is to iterate through all possible values by brute force.</p><h4>Details</h4><p>We can run through all possible values using either Solidity directly or via offline tools such as web3.js.</p><p><strong>Solidity</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*6TwZxbBNeu0LuCHE1dfJVw.png" /></figure><p>We can easily replicate the keccak256 check in a for loop as shown in the GuessTheSecretNumberSolver contract in the above fiddle. <strong>You can deploy the contract in EthFiddle which runs an in-browser test EVM that come with accounts loaded with Ether.</strong></p><p><em>Note EthFiddle provides a subset of the functionalities by Remix, where you can also choose built-in EVM from the environment. From hereafter we demonstrate code using EthFiddle as they can be beautifully embedded on Medium.</em></p><p>Because we wrote the function with public view modifiers, we can call it without gas. Shortly after, it should spit out the answer in the box below.</p><p><strong>Pay attention that you are using the correct type, in this case, </strong><strong>uint8 . Otherwise </strong><strong>keccak256 would produce different result</strong> <strong>as shown in the </strong><strong>keccak256Uint function. </strong>This is because keccak256 hashes <a href="http://solidity.readthedocs.io/en/v0.4.21/abi-spec.html#abi-packed-mode">(tightly packed) arguments</a>.</p><p><strong>Web3.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a84b175e65da84eab0d1d20bc86a0a52/href">https://medium.com/media/a84b175e65da84eab0d1d20bc86a0a52/href</a></iframe><p><a href="https://github.com/ethereum/wiki/wiki/JavaScript-API#web3sha3">web3.sha3</a> computes keccak256 hash from a string (optionally in hex.) In our case, <strong>it is important to pad hex representation of </strong><strong>uint8 to correct digits as shown in the last two lines.</strong></p><p>Web3.js 1.x will have <a href="http://web3js.readthedocs.io/en/1.0/web3-utils.html#soliditysha3">web3.utils.soliditySha3</a> that takes care of the type coercion for us.</p><h3>Guess the random number</h3><h4>Approach</h4><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fethfiddle.com%2FP-TJHojT5g&amp;src=https%3A%2F%2Fethfiddle.com%2Fservices%2Fiframesnippet%2FP-TJHojT5g&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=ethfiddle" width="300" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d721cc5cd48234cd74b89ca2d5207b2/href">https://medium.com/media/1d721cc5cd48234cd74b89ca2d5207b2/href</a></iframe><p>Two ways to solve this problem:</p><ol><li>Compute answer using heccak256 based on block hash of the previous block of contract deploy (block.number — 1) and timestamp of the contract deploy block.</li><li>Get answer value directly from EVM storage. <strong>Even though </strong><strong>answer is a private field in the contract, </strong>because all transaction need to be validated by all nodes, <strong>all fields are in fact publicly readable </strong>from an Ethereum node, which can be queried using web3.js.</li></ol><h4>Details</h4><p><strong>Calculate Answer from Hash</strong></p><p>We first need to find the transaction corresponding to contract creation. Unfortunately I cannot find straightforward API to convert contract address to transaction hash. You can look up this on Etherscan or from the result of your deployment transaction call in Metamask.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WDnblkMUZMzvhZa4-cQCg.png" /></figure><p>With that we can find the block and its timestamp as well as parent block hash. We compute the keccak256 hash as before and truncate the byte32 string to uint8 by taking the last two character and convert it back to integer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d71a81ffb58d0413b023aa5e91ef45f/href">https://medium.com/media/3d71a81ffb58d0413b023aa5e91ef45f/href</a></iframe><p><strong>Get Answer from EVM Storage</strong></p><p>All persistent contract variables are stored in contract storage and they follow a specific layout as can be found in this <a href="http://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html?highlight=storage%20layout#layout-of-state-variables-in-storage">documentation</a>. I refer you to this excellent article on how to read contract storage using web3.js.</p><p><a href="https://medium.com/aigang-network/how-to-read-ethereum-contract-storage-44252c8af925">How to read Ethereum contract storage</a></p><p>For the purpose of our exercise, there is only one field in the contract. Therefore we simply need to find the value at slot 0:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd2fa30a62031c77602471da89ec2134/href">https://medium.com/media/bd2fa30a62031c77602471da89ec2134/href</a></iframe><h3>Conclusion</h3><p>In this post, you have learnt to write Solidity code in EthFiddle to test various scenarios without spending gas, use web3.js to compute keccak256 hash and find block information from a transaction hash, and pry open EVM storage to peak private storage variable of a contract.</p><p>Next time, we will look at more challenges in the Lotteries section where we will discover more interesting security vulnerabilities in smart contract and how to indirectly interact with other smart contracts using a smart contract. We will also look at how to use <a href="http://truffleframework.com">Truffle framework</a> to write and test smart contract in a local simulated blockchain.</p><blockquote>Capture the Ether is brought to you by <a href="https://twitter.com/smarx">@smarx</a>, who blogs about smart contract development at <a href="https://programtheblockchain.com/">Program the Blockchain</a>.</blockquote><p>I am not affiliated with the game itself and the awesome company behind it. Views expressed are solely my own and do not express the views or opinions of any entity with which I have been, am now, and will be affiliated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e0b40687efd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Play — Capture the Ether : Warmup]]></title>
            <link>https://medium.com/coinmonks/lets-play-capture-the-ether-warmup-68a5fc38e670?source=rss-5d668b546d10------2</link>
            <guid isPermaLink="false">https://medium.com/p/68a5fc38e670</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[dapps]]></category>
            <dc:creator><![CDATA[Forest Fang]]></dc:creator>
            <pubDate>Sat, 14 Apr 2018 08:35:40 GMT</pubDate>
            <atom:updated>2018-05-16T10:48:00.996Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Play — Capture the Ether : Warmup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vb4OZmcEooyqvZx9NZ1fvA.png" /></figure><p>This is a series of stories on my journey of <a href="https://capturetheether.com/">Capture the Ether</a>, a game where we hack Ethereum Solidity code for fun and learn about smart contract security.</p><p><strong>Table of Contents</strong></p><ul><li>Lotteries: random number in smart contract. <a href="https://medium.com/@saurfang/lets-play-capture-the-ether-lotteries-part-i-4e0b40687efd">Part I</a>, <a href="https://medium.com/@saurfang/lets-play-capture-the-ether-lotteries-part-ii-478365775a34">Part II</a></li><li>Math: how to do math safely in Solidity.</li><li>Accounts: account ownership and security.</li><li>Miscellaneous: everything else.</li></ul><h3>What is Capture the Ether?</h3><p>In <em>Capture the Ether</em>, we win points by completing challenges. Each challenge comes with a smart contract to deploy and objectives can be completed by exploiting the contract into a specific state. Challenges are grouped into categories that focus on specific areas of security vulnerabilities in smart contracts.</p><h3>Why this Series?</h3><p>I have learnt my Solidity skill first through <a href="https://cryptozombies.io">CryptoZombies</a>, and written some smart contracts with <a href="http://truffleframework.com/">Truffle</a> framework in a few hackathons. As of this writing, I am halfway through the Lottery section and have found it to be an engaging educational resource.</p><p>I have not yet had trouble coming up with ideas how to tackle the challenge, but I had plenty <strong>painful moments figuring out the tools</strong> I need to implement my approach and <strong>debugging my smart contract</strong>.</p><p>In this series of articles, I will focus on <strong>practical smart contract programming and my hard learnt mistakes</strong>. I will lay out the<strong> tools and IDE/CLI setup, </strong>explain<strong> </strong>the<strong> key security insight</strong> of each problem,<strong> </strong>and<strong> </strong>show you how to<strong> implement them in practice</strong>. It will assume you have basic understanding of how Ethereum works and I highly recommend you go through <a href="https://cryptozombies.io">CryptoZombies</a> first to learn the basics of Solidity. In the interests of space, I will not explain concepts in details but will provide links as necessary.</p><p>Before we start, I should mention that <em>Capture the Ether</em> already provides an excellent <a href="https://capturetheether.com/resources">resources</a> to get you started. The <strong>Warmup</strong> challenges are also meant to prepare you with the tools you need. I will focus on the missing details that gave me troubles in my experience.</p><h3>Deploy a Contract</h3><p>As instructed, you first need <a href="https://metamask.io/">Metamask</a>, an in-browser Ethereum wallet. Once installed, you can follow the prompt to finish setup. Now we need to Switch to Ropsten Test Network. I will demo using beta version of Metamask in a Brave browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzvOfqGdHqzrwXAQCCVROw.png" /><figcaption>Metamask Chrome Extension Standalone Page — Select a network</figcaption></figure><p>The network can be chosen by clicking on the network selector on top right. Main Ethereum Network is the production network where Ethers and (ERC20) tokens have real value and can be traded and used to operate smart contract.</p><p>The other test networks are used to develop and test smart contracts. They run the identical <a href="https://github.com/pirapira/awesome-ethereum-virtual-machine">EVM</a> as in the main network but some use more efficient (and less secure) consensus algorithm such as <a href="https://github.com/kovan-testnet/proposal">PoA</a>. Ethers on test network can be similarly mined but <strong>faucets are also available to acquire free Ethers for testing</strong>. In <em>Capture the Ether</em>, you need <strong>a little more than two Ethers</strong> to play the game (you need two Ethers to complete smart contract interaction and then some more to pay the gas.)</p><p>Here are some faucets:</p><ol><li><a href="https://faucet.metamask.io">https://faucet.metamask.io</a> 1 Ether per account per day</li><li><a href="https://faucet.bitfwd.xyz/?ref=producthunt">https://faucet.bitfwd.xyz/</a> 1 Ether per account per day</li><li><a href="https://faucet.kyber.network/">https://faucet.kyber.network/</a> 1 Ether per account</li><li><a href="http://faucet.ropsten.be:3001/">http://faucet.ropsten.be:3001/</a> 1 Ether every drip (queue based)</li></ol><p>I recommend you <strong>get 3 Ethers first and come back for more only if you need them</strong> when you make mistakes in the challenges.</p><p>Ether in testnet does not have real value so be sure you are on test network when you play the game. You private key and all Ethereum addresses work just the same in miannet and testnet. <strong>Don’t send your mainnet Ether to a testnet account or you will lose them.</strong> <strong>To be foolproof, don’t share private key/seed/account between mainnet and testnet.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*G7qzfZWir2SkhcqAVTvIHA.png" /><figcaption>Metamask Dropdown — Confirm a transaction</figcaption></figure><p>With that, click Begin Challenge, and confirm. Your own copy of the below smart contract will be deployed. Click check solution again to complete the challenge.</p><pre>pragma solidity ^0.4.21;</pre><pre>contract DeployChallenge {       <br>  // This tells the CaptureTheFlag contract that the challenge is complete.</pre><pre>  function isComplete()<br>  public <br>  pure<br>  returns (bool) {<br>   return true;<br>  }<br>}</pre><p>Notice that Capture the Ether relies on calling isCompelete function to determine if you have achieved the objective. Furthermore, <strong>because you deployed a copy of this smart contract code with your Ethereum account, Capture the Ether can trustlessly link the accomplishment to your Ethereum address.</strong></p><h3>Call me</h3><p>This question asks us to call a function on a deployed contract, i.e. send a transaction to a smart contract address with payload that contains function interface and arguments. You can refer to <a href="http://ethdocs.org/en/latest/contracts-and-transactions/accessing-contracts-and-transactions.html#interacting-with-smart-contracts">interacting with smart contract</a> to learn the details of what happens under the hood.</p><p>The hard core way would be us figuring out the payload data, running this through CLI and communicating with a local node directly. Here I will demonstrate two easiest ways that interfaces with Metamask directly.</p><h4>Javascript Console with web3.js</h4><p>Web3.js is a Javascript library that communicate with Ethereum node through JSON-RPC interface. You can read more and find API documentation on its <a href="https://github.com/ethereum/wiki/wiki/JavaScript-API">Github</a> website.</p><p>Metmask injects web3.js to every running web page in your browser. This has the awesome effect that you can interact with Ethereum directly without worrying managing private keys and node connection. In fact, let’s give it a try by <strong>opening the Console via Command/Ctrl+Option+J</strong> and running the following lines:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32d79630e4af66d71e3191a203c23987/href">https://medium.com/media/32d79630e4af66d71e3191a203c23987/href</a></iframe><p>🎉 You should see your default Metamask address and its balance. You may find the syntax to be rather clunky as everything is asynchronous and callback based. The good news is that <strong>web3.js 1.x will return promises for async function so you can chain promise or use async/await syntax</strong>. (We will cover this in the next article when we write web3.js code in Truffle.) You can track <a href="https://github.com/MetaMask/metamask-extension/issues/3642">Metamask progress of web3.js 1.x support</a> at Github.</p><p>To interact with a contract, web3.js relies on<strong> </strong><a href="https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI"><strong>ABI</strong></a><strong> (application binary interface), which specifies what functions are available and what arguments are accepted for each function.</strong></p><p>The easiest way to get ABI from source code is by using a solidity compiler. Feel free to jump to the next subsection, which introduces an online IDE Remix, if you don’t care about the details of solidity compiler and web3.js.</p><p>We will use solc from the binary Solidity package on Mac and you can find <a href="http://solidity.readthedocs.io/en/v0.4.21/installing-solidity.html">many other compilers</a> in the documentation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fac563daf655142481ac9e840abe3376/href">https://medium.com/media/fac563daf655142481ac9e840abe3376/href</a></iframe><p>We can load this ABI with web3.js in JS console and issue a transaction to call callme function in the contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4adf081d8311182ace4e2163ba47d5ef/href">https://medium.com/media/4adf081d8311182ace4e2163ba47d5ef/href</a></iframe><p>Metamask should pop up asking you to authorize a transaction that is triggered by the last line. With that one confirmed, you can go ahead check your solution. 🎉+100 points.</p><h4>Remix</h4><p><a href="https://remix.ethereum.org/">Remix</a> is an in-browser IDE for Solidity. You can write, compile, and interact with smart contract with a friendly-ish GUI.</p><p>Let us create a new file by clicking the + button on the top left and name it CallMeChallenge.sol . We will then put the contract code in the editor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gb_yu4owFPxlJXgdqJ6Xng.png" /><figcaption>Remix in-browser Solidity IDE</figcaption></figure><ol><li>Create File</li><li>Copy and paste solidity code</li><li>Check Auto Compile which will compile your code whenever it is changed</li><li>The green box celebrates your code compiles with detected contract name: CallMeChallenge</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*nbuWmWf1xQzFiaWac0KXBQ.png" /></figure><p>Now we can interact with the contract on Ethereum blockchain:</p><ol><li>Click Run tab</li><li>Choose Injected Web3 and verify you are on Ropsten test network on the right. There are a few other environments available. Simply these are possible blockchain (providers) you can interact with. Injected Web3 means web3.js is injected into browser page, in this case, by Metamask.</li><li>Verify you are on the intended account and your balance is correctly reflected. If you created multiple accounts in Metamask, you will have those to choose from.</li><li>A list of Contract defined in the current file will be listed here. In this case, we only have CallMeChallenge</li><li>You can either Create a new contract or Load an existing contract that has been deployed. In this case, <strong>we enter the address of our deployed contract in the challenge</strong>.</li><li>An instance of contract should show up below. This is akin to what happened when we ran CallMeChallenge.at(&#39;&lt;address&gt;&#39;) above.</li><li>There are two buttons callme and isComplete which are the two public functions of the contract. <strong>Notice the different color</strong> because callme is a <strong>state modifying function</strong> that can only be called with a transaction where you will pay gas. On the other hand, isComplete is a <strong>read only function</strong> can be called without paying any gas. (Note you will still pay gas if calling a read only function within a transaction.)</li></ol><p>Go click isComplete , you should immediately see 0: bool: false on the right if you have yet completed the challenge. Now click callme and Metamask should ask to authorize a transaction. Transaction status will be updated in the console below. Once the transaction has been mined, you can click isComplete again, and now it should show 0: bool: true instead. Congratulation +100 points!</p><h3>Choose a nickname</h3><p>This one should be easy for you now that you know how to use Remix. The only tricky part is that now we need to call function with an argument.</p><p>Go ahead copy and paste the code into a new file. Load the contract from the address 0x71c46Ed333C35e4E6c62D32dc7C8F00D125b4fee. Fill in your preferred nick name to the right of setNickname function.</p><p><strong>You need to wrap </strong><strong>string/bytes argument with double quotes. Remix uses space to delimit arguments.</strong></p><p>Easiest 200 points in my life! 😬</p><p>For completeness, you can interact with this contract with web3.js as shown above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a1c5efc5c825b4445bcb57ff4ac6a89/href">https://medium.com/media/3a1c5efc5c825b4445bcb57ff4ac6a89/href</a></iframe><h3>Conclusion</h3><p>In this post, you have learnt to create your own Ethereum account on Ropsten test network with Metamask, use web3.js in Javascript console injected by Metamask, and call contracts using web3.js using code or Remix via GUI.</p><p>Next time, we will dive into the Lotteries section where we will discover common and interesting security vulnerabilities in smart contract. We will also look at how to use <a href="http://ethfiddle.com">EthFiddle</a> to write and test Solidity code in browser without paying any gas.</p><blockquote>Capture the Ether is brought to you by <a href="https://twitter.com/smarx">@smarx</a>, who blogs about smart contract development at <a href="https://programtheblockchain.com/">Program the Blockchain</a>.</blockquote><p>I am not affiliated with the game itself and the awesome company behind it. Views expressed are solely my own and do not express the views or opinions of any entity with which I have been, am now, and will be affiliated.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F41d817%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F41d817&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F41d817%252F%253Fenpose&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebbe4d33ac6b8f6af3724807b028c5eb/href">https://medium.com/media/ebbe4d33ac6b8f6af3724807b028c5eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68a5fc38e670" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/lets-play-capture-the-ether-warmup-68a5fc38e670">Let’s Play — Capture the Ether : Warmup</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[Ethereum Solidity: Memory vs Storage & Which to Use in Local Functions]]></title>
            <link>https://medium.com/coinmonks/ethereum-solidity-memory-vs-storage-which-to-use-in-local-functions-72b593c3703a?source=rss-5d668b546d10------2</link>
            <guid isPermaLink="false">https://medium.com/p/72b593c3703a</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Forest Fang]]></dc:creator>
            <pubDate>Sun, 18 Mar 2018 08:29:30 GMT</pubDate>
            <atom:updated>2022-06-24T18:29:44.799Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ethereum Solidity: Memory vs Storage &amp; When to Use Them</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4cy-ctwr3VNaoi68Dw8-g.png" /></figure><p>Someone asked me on <a href="https://github.com/saurfang/ipfs-multihash-on-solidity/issues/1">Github</a> whether we should use storage or memory keyword in the following simplified code snippet:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fethfiddle.com%2FNRXv7YK6Kn&amp;src=https%3A%2F%2Fethfiddle.com%2Fservices%2Fiframesnippet%2FNRXv7YK6Kn&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=ethfiddle" width="300" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/cabe7489144073bb6f965afbcab7657f/href">https://medium.com/media/cabe7489144073bb6f965afbcab7657f/href</a></iframe><p>For getUsingStorage and getUsingMemory, I tried both storage and memory and my unit tests were able to pass in both cases. So what’s the difference between storage and memory anyway and when should we use them?</p><blockquote><a href="https://coincodecap.com/category/blockchain-node-and-api">Discover and review best Ethereum development tools</a></blockquote><p>According to <a href="https://solidity.readthedocs.io/en/v0.4.21/types.html#reference-types">Solidity documentation</a>, these two keywords are used for Reference Types where</p><blockquote>Complex types, i.e. types which do not always fit into 256 bits have to be handled more carefully than the value-types we have already seen. Since copying them can be quite expensive, we have to think about whether we want them to be stored in <strong>memory</strong> (which is not persisting) or <strong>storage</strong>(where the state variables are held).</blockquote><blockquote>…</blockquote><blockquote>Every complex type, i.e. <em>arrays</em> and <em>structs</em>, has an additional annotation, the “data location”, about whether it is stored in memory or in storage.</blockquote><p>It is now important to look at <a href="http://solidity.readthedocs.io/en/v0.4.21/frequently-asked-questions.html#what-is-the-memory-keyword-what-does-it-do">where EVM (Ethereum Virtual Machine) stores data</a>:</p><blockquote>The Ethereum Virtual Machine has three areas where it can store items.</blockquote><blockquote>The first is “storage”, where all the contract state variables reside. Every contract has its own storage and it is persistent between function calls and quite expensive to use.</blockquote><blockquote>The second is “memory”, this is used to hold temporary values. It is erased between (external) function calls and is cheaper to use.</blockquote><blockquote>The third one is the stack, which is used to hold small local variables. It is almost free to use, but can only hold a limited amount of values.</blockquote><p>Most importantly,</p><blockquote>If you e.g. pass such variables in function calls, their data is not copied if it can stay in memory or stay in storage.</blockquote><p>This is where it gets confusing:</p><ol><li>The storage and memory keywords are used to reference data in storage and memory respectively.</li><li>Contract storage is pre-allocated during contract construction and cannot be created in function call. After all, it makes little sense to create new variable in storage in a function if it is to be persisted.</li><li>Memory cannot be allocated during contract construction but rather created in function execution. Contract <strong>state variable</strong> is always declared in storage. Again, it makes little sense to have state variable that cannot persist.</li><li>When assigning a memory referenced data to a storage referenced variable, we are copying data from memory to storage. <strong>No new storage is created.</strong></li><li>When assigning a storage reference data to a memory referenced variable, we are copying data from storage to memory. <strong>New memory is allocated.</strong></li><li>When a storage variable is created in function locally by look up, it simply reference data already allocated on Storage. <strong>No new storage is created.</strong></li></ol><p>To recap, refer back to the documentation:</p><blockquote>Forced data location:</blockquote><blockquote>* parameters (not return) of external functions: calldata</blockquote><blockquote>* state variables: storage</blockquote><blockquote>Default data location:</blockquote><blockquote>* parameters (also return) of functions: memory</blockquote><blockquote>* all other local variables: storage</blockquote><p>We can change data location only for parameters of functions and local variables in function. Whenever a storage reference is casted to memory, a copy is made, and further modification on the object does not propagate back to contract state. memory reference can only be “assigned” to storage reference if memory data can be copied to a pre-allocated state variable.</p><p>Back to our illustrative contract above, for getters:</p><pre>function getUsingStorage(uint _itemIdx)<br>public<br>// set to non-view to estimate gas<br>// view<br>returns (uint)<br>{<br>Item storage item = items[_itemIdx];<br>return item.units;<br>}</pre><pre>function getUsingMemory(uint _itemIdx)<br>public<br>// set to non-view to estimate gas<br>// view<br>returns (uint)<br>{<br>Item memory item = items[_itemIdx];<br>return item.units;<br>}</pre><p>Both functions return the same result, except in the getUsingMemory a new variable is created and resulting in more gas used:</p><pre>// getUsingStorage<br>&quot;gasUsed&quot;: 21849</pre><pre>// getUsingMemory<br>&quot;gasUsed&quot;: 22149,</pre><p>On the other hand, for setters:</p><pre>function addItemUsingStorage(uint _itemIdx, uint _units)<br>public<br>{<br>Item storage item = items[_itemIdx];<br>item.units += _units;<br>}<br></pre><pre>function addItemUsingMemory(uint _itemIdx, uint _units)<br>public<br>// set to non-view to estimate gas<br>// view<br>{<br>Item memory item = items[_itemIdx];<br>item.units += _units;<br>}</pre><p>Only addItemUsingStorage modified the state variable (consuming more gas):</p><pre>// addItemUsingStorage<br>// `units` changes in `items`<br>&quot;gasUsed&quot;: 27053,</pre><pre>// addItemUsingMemory<br>// `units` does not change in `items`<br>&quot;gasUsed&quot;: 22287,</pre><p>So to close, the takeaways are:</p><ol><li>memory and storage specifies which data location the variable refers to</li><li>storage cannot be newly created in a function. Any storage referenced variable in a function always refers a piece of data pre-allocated on the contract storage (state variable). Any mutation persists after function call.</li><li>memory can only be newly created in a function. It can either be newly instantiated complex types like array/struct (e.g. via new int[...]) or copied from a storage referenced variable.</li><li>As references are passed internally through function parameters, remember they default to memory and if the variable was on storage it would create a copy and any modification would not persist.</li></ol><p>References:</p><ul><li><a href="https://stackoverflow.com/questions/33839154/in-ethereum-solidity-what-is-the-purpose-of-the-memory-keyword">In Ethereum Solidity, what is the purpose of the &quot;memory&quot; keyword?</a></li><li><a href="https://ethereum.stackexchange.com/questions/1701/what-does-the-keyword-memory-do-exactly">What does the keyword &quot;memory&quot; do exactly?</a></li><li><a href="https://medium.com/loom-network/ethereum-solidity-memory-vs-storage-how-to-initialize-an-array-inside-a-struct-184baf6aa2eb">Ethereum Solidity: Memory vs Storage &amp; How to initialize an array inside a struct</a></li></ul><blockquote>Join Coinmonks<a href="https://t.me/coincodecap"> Telegram Channel</a> and<a href="https://www.youtube.com/c/coinmonks/videos"> Youtube Channel</a> get daily <a href="http://coincodecap.com/">Crypto News</a></blockquote><h4>Also, Read</h4><ul><li><a href="http://Top 4 Telegram Channels for Crypto Traders">Crypto Telegram Signals</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading Bot</a></li><li><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">Copy Trading</a> | <a href="https://medium.com/coinmonks/crypto-tax-software-ed4b4810e338">Crypto Tax Software</a></li><li><a href="https://coincodecap.com/grid-trading">Grid Trading</a> | <a href="https://medium.com/coinmonks/the-best-cryptocurrency-hardware-wallets-of-2020-e28b1c124069">Crypto Hardware Wallet</a></li><li><a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Best Crypto Exchange in India</a></li><li><a href="https://medium.com/coinmonks/best-crypto-apis-for-developers-5efe3a597a9f">Best Crypto APIs</a> for Developers</li><li>Best <a href="https://medium.com/coinmonks/top-5-crypto-lending-platforms-in-2020-that-you-need-to-know-a1b675cec3fa">Crypto Lending Platform</a></li><li>An ultimate guide to <a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a></li><li><a href="https://coincodecap.com/best-vpns-for-crypto-trading">Best VPNs for Crypto Trading</a></li><li><a href="https://coincodecap.com/blockchain-analytics">Best Crypto Analytics or On-Chain Data</a> | <a href="https://coincodecap.com/bexplus-review">Bexplus Review</a></li><li><a href="https://coincodecap.com/nft-marketplaces">10 Biggest NFT MarketPlaces to Mint a Collection</a></li><li><a href="https://coincodecap.com/ascendex-staking">AscendEx Staking</a> |<a href="https://coincodecap.com/bot-ocean-review"> Bot Ocean Review</a> |<a href="https://coincodecap.com/bitcoin-wallets-india"> Best Bitcoin Wallets</a></li><li><a href="https://coincodecap.com/bitget-review">Bitget Review</a> |<a href="https://coincodecap.com/gemini-vs-blockfi"> Gemini vs BlockFi</a> |<a href="https://coincodecap.com/okex-futures-trading"> OKEx Futures Trading</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72b593c3703a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/ethereum-solidity-memory-vs-storage-which-to-use-in-local-functions-72b593c3703a">Ethereum Solidity: Memory vs Storage &amp; Which to Use in Local Functions</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>
    </channel>
</rss>