<?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 Mike Calvanese on Medium]]></title>
        <description><![CDATA[Stories by Mike Calvanese on Medium]]></description>
        <link>https://medium.com/@mikecalvanese?source=rss-90ab7d8b6ec5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q7Nifn1CQ8WxRKdqX0_Sew.jpeg</url>
            <title>Stories by Mike Calvanese on Medium</title>
            <link>https://medium.com/@mikecalvanese?source=rss-90ab7d8b6ec5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:24:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mikecalvanese/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[Flexible Upgradability for Smart Contracts]]></title>
            <link>https://medium.com/level-k/flexible-upgradability-for-smart-contracts-9778d80d1638?source=rss-90ab7d8b6ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9778d80d1638</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Mike Calvanese]]></dc:creator>
            <pubDate>Sat, 10 Mar 2018 15:30:21 GMT</pubDate>
            <atom:updated>2018-03-10T15:30:21.299Z</atom:updated>
            <content:encoded><![CDATA[<p>The immutable nature of Ethereum smart contracts is incredibly powerful. It allows us to build applications that are completely tamper-proof, untouchable by any individual, corporation, or government. Every participant is subject to the same set of rules, and these rules will never change.</p><p>But ultimately, these rules are created by humans. As humans, we are prone to the occasional mistake. It is impossible for us to see the whole picture from day one and build flawless systems that have no need for adaptability or improvement.</p><p>In order to balance immutability and flexibility, we need mechanisms for upgrading decentralized apps (dapps) after they are deployed. In this article, we will describe how this can be done today using some simple but powerful patterns.</p><p>While we will be describing the mechanisms for upgradability, we will not discuss the process for how an upgrade is triggered. An assumption can be made that upgrades will be executed by an “owner”. This owner could be an individually held address, a multi-sig contract, or a complex decentralized autonomous organization (DAO).</p><h4>Existing Patterns</h4><p>The Zeppelin Solutions and Aragon teams have designed some very useful patterns for upgradability. We’ve borrowed code from <a href="https://blog.zeppelin.solutions/proxy-libraries-in-solidity-79fbe4b970fd">Proxy Libraries in Solidity</a> and <a href="https://blog.zeppelinos.org/smart-contract-upgradeability-using-eternal-storage/">Smart Contract Upgradability Using Eternal Storage</a>.</p><h4>Upgradable Dapp Toolkit</h4><p>At <a href="http://levelk.io/">Level K</a>, we are applying these patterns to our (work in progress) <a href="https://github.com/levelkdev/upgradable-dapp-toolkit">Upgradable Dapp Toolkit</a>. This toolkit contains some core contracts that help enable upgradability for any dapp.</p><h4>Example Code</h4><p>If you want to stop reading and just look at code, go for it! All code for this post is here: <a href="https://github.com/levelkdev/upgradability-blog-post">github.com/levelkdev/upgradability-blog-post</a></p><h3>How to Make an Upgradable Token</h3><p>We’ll assume you have some knowledge of ERC20 tokens and the code that makes them work. If not, take a look at <a href="https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/token/ERC20">Zeppelin’s ERC20 contract code</a> to get a better understanding.</p><p>Let’s say we want to deploy a new token called ShrimpCoin<em>. </em>One can only guess what this token might be used for.</p><p>Here’s an architecture diagram to show what upgrading ShrimpCoin from a standard token to a “mintable” token might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zeIiC8hCdo6h4qlMSmMp5w.png" /></figure><p>All of this will be explained in detail, so read on!</p><h4>Proxy and Delegate Contracts</h4><p>You’ll notice that ShrimpCoin<em> </em>is a Proxy<em> </em>contract. This means that when a transaction (transfer() for example) is sent and ShrimpCoin<em> </em>does not know about the function specified in the transaction, it will proxy the transaction to what we’ll refer to as a “delegate” contract.</p><p>This is done using the native EVM code, <a href="http://solidity.readthedocs.io/en/develop/introduction-to-smart-contracts.html#delegatecall-callcode-and-libraries">delegatecall</a><em>. </em>From the solidity docs, a contract using delegatecall…</p><blockquote>…can dynamically load code from a different address at runtime. Storage, current address and balance still refer to the calling contract, only the code is taken from the called address.</blockquote><p>Put simply, this means that ShrimpCoin takes on all the functionality of our delegate contract, TokenDelegate. In order to upgrade the functionality of ShrimpCoin, we just need to tell the proxy to use a new delegate (MintableTokenDelegate in our example).</p><p>The code for the Proxy contract is slightly intimidating (there’s some EVM assembly code in here):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c37268c2e2583cdccc91cb1bf329bd60/href">https://medium.com/media/c37268c2e2583cdccc91cb1bf329bd60/href</a></iframe><p>Take a look at the fallback function function() payable public {…, which is a catch-all for transactions with unknown functional signatures. Within this function, the assembly code is where thedelegatecall happens. This could be done in plain old solidity for functions that don’t have a return value. However, delegatecall only returns a single value to indicate whether it succeeded or failed. This block of assembly gets the actual return value of the proxied transaction and returns it.</p><p>The Proxy contract is an Ownable, allowing some predetermined owner to execute upgradeTo() and upgrade the contract to use any delegate contract.</p><h4>Proxy Delegate State</h4><p>When a proxy contract uses a delegate contract’s functionality, state modifications will happen on the proxy contract. This means that the two contracts need to define the same storage memory. The order that storage is defined in memory needs to match between the two contracts.</p><p>Here’s an example to illustrate this concept. Assume that Thing is set up to use functionality from ThingDelegate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e14e9f7e09565d0fac7d0e72ed7ef1c/href">https://medium.com/media/0e14e9f7e09565d0fac7d0e72ed7ef1c/href</a></iframe><p>A few interesting things going on here…</p><p>Although the storage memory matches (both contracts define a uint256), the variable names (num and n) do not match. Even though these variables have different names, they will still compile to bytecode with matching storage memory. As a result, when Thing proxies a call to incrementNum() on ThingDelegate, this will still increment num on Thing state.</p><p>Also, additional storage and state is defined here (string name = &quot;Thing&quot;;). This storage won’t be manipulated by ThingDelegate. The order of memory matters here. If name was defined above num, then incrementNum() would try to add 1 to a string.</p><p>Something that we love about this pattern is that ThingDelegate does not need to know about Thing. Once ThingDelegate is deployed, any contract can use it as a delegate, thus ThingDelegate is publicly consumable. In fact, any deployed contract can be used as a delegate. It does not need to be defined as such.</p><h4>ShrimpCoin and TokenDelegate</h4><p>Let’s look at the slightly more complex ShrimpCoin and TokenDelegate, along with some storage helpers, StorageConsumer and StorageStateful:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a7c1628f3cafd19332678165e743155/href">https://medium.com/media/2a7c1628f3cafd19332678165e743155/href</a></iframe><p>This follows the same pattern as the Thing example. But the common state here is the address of a KeyValueStorage contract (explained in the next section).</p><p>It’s important to note that ShrimpCoin extends StorageConsumer before extending DetailedToken. If these were swapped, TokenDelegate would try to use string name; instead of KeyValueStorage _storage; for that getUint() operation. This would cause the transaction to revert.</p><h4>Key Value Storage</h4><p>The proxy delegate pattern is super useful for upgrading functionality, but what if we want to add something to state that wasn’t defined on the original contract? That’s where the “Eternal Storage” pattern comes in. This pattern was originally described in <a href="https://blog.colony.io/writing-upgradeable-contracts-in-solidity-6743f0eecc88">Writing Updatable Contracts in Solidity</a>.</p><p>Here is a simplified KeyValueStorage contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca1f4ea1b579ca2da47fd6745f35930e/href">https://medium.com/media/ca1f4ea1b579ca2da47fd6745f35930e/href</a></iframe><p>This contract defines three mappings of mappings. These will be used to store values of type uint256, bool, and address. The highest level key for these mappings will be msg.sender, which is the address of a smart contract that is executing a write or read using the set/get functions.</p><p>Logically, this key/value storage is structured like this:</p><pre>_uintStorage<br>   &lt;shrimp_coin_address&gt;<br>      &quot;totalSupply&quot;: 1000<br>   &lt;clam_token_address&gt;<br>      &quot;totalSupply&quot;: 2000</pre><pre>_boolStorage<br>   &lt;shrimp_coin_address&gt;<br>      &quot;isPaused&quot;: true<br>   &lt;clam_token_address&gt;<br>      &quot;isPaused&quot;: false</pre><p>In our example, the ShrimpCoin contract address will be msg.sender, while the key could be something like &quot;totalSupply&quot;.</p><p>Since we’re keying off of msg.sender, all key/value pairs are scoped to the sender contract. A contract cannot manipulate another contract’s storage values. This means that after KeyValueStorage is deployed, it is open for any contract to use.</p><h4>Getting and Setting Key/Value Pairs</h4><p>We can use the getters and setters provided by KeyValueStorage to read or manipulate state values.</p><p>This code would set totalSupply to 1000 for the calling contract:</p><pre>_storage.setUint(&quot;totalSupply&quot;, 1000);</pre><p>We can also set more complex values, such as mappings. We can create a hashed key value using keccak256() in order to set a balance of amount for balanceHolder within a balances mapping:</p><pre>_storage.setUint(keccak256(&quot;balances&quot;, balanceHolder), amount);</pre><p>These low-level storage functions are much more verbose than the usual balances[address] = amount; syntax, so it will make sense to wrap them in some higher level functions. Look at how this is done in TokenDelegate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8577c9ec0ef396bc1d11524c2de4adb6/href">https://medium.com/media/8577c9ec0ef396bc1d11524c2de4adb6/href</a></iframe><p>Internal functions like getBalance() make the balance storage easier to work with. This functionality could be further refactored into a library to be shared across multiple delegate contracts.</p><h4>Upgrading to a Mintable Token</h4><p>Let’s say we deploy ShrimpCoin with a proxy pointer to TokenDelegate (we’ll call this V1). The V1 implementation is limited because TokenDelegate doesn’t provide a mechanism for initial creation, or “minting” of tokens.</p><p>The owner address of ShrimpCoin can call upgradeTo() to point the proxy at an instance of MintableTokenDelegate (we’ll call this V2).</p><p>The V2 MintableTokenDelegate contract provides some additional functions for minting, which act on a totally new set of storage keys:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/570c5793237e4126ff562194193f1655/href">https://medium.com/media/570c5793237e4126ff562194193f1655/href</a></iframe><p>It also takes on all the functionality of the V1 TokenDelegate, so contracts like ShrimpCoin that are proxying to it won’t lose any of their original functionality.</p><h3>Future Projections</h3><p>We’ve presented a simple example of a token upgrade, but this approach can also be applied to more complex scenarios. One use case that we’re excited about at <a href="http://www.levelk.io/">Level K</a> is an upgradable <a href="https://medium.com/@ilovebagels/token-curated-registries-1-0-61a232f8dac7">Token Curated Registr</a>y.</p><p>These patterns open up some really cool opportunities to make and deploy re-usable delegates for common functionality, which could be leveraged by a potentially massive and diverse set of dapps.</p><p>A few advantages of using the combined proxy delegate and key/value storage upgradability pattern:</p><ul><li>Gives total flexibility to upgrade both functionality and storage</li><li>Encourages the creation and deployment of standard contracts that encapsulate common functionality</li><li>Leveraging pre-deployed smart contracts as delegates (which will someday be thoroughly battle tested) is less error prone.</li><li>Re-use of pre-deployed contracts means simpler audits and reduced deployment gas costs.</li></ul><p>And some disadvantages:</p><ul><li>The upgrade “owner” has full control, meaning full trust. In order to design a truly trustless contract that is also upgradable, the “owner” must itself be a trustless contract.</li><li>Syntax for interacting with key/value storage is more verbose than standard solidity state variable operations.</li><li>A flaw in a standardized and shared contract could lead to widespread damage across all dapps that consume the contract.</li></ul><p>We’re excited to hear how other developers are using these patterns. The <a href="https://medium.com/rocket-pool/upgradable-solidity-contract-design-54789205276d">Rocket Pool</a> project is doing some awesome things with upgradability. We’d love to hear about others!</p><p>If you found this post helpful please let us know! Send some love to contact@levelk.io</p><p>Thanks for reading :-)</p><p>References:</p><ul><li><a href="https://github.com/mikec/smart-contract-upgradability">Full ShrimpCoin Example</a></li><li><a href="https://github.com/levelkdev/upgradable-dapp-toolkit">Level K’s Upgradable Dapp Toolkit (work in progress)</a></li><li><a href="https://blog.zeppelin.solutions/proxy-libraries-in-solidity-79fbe4b970fd">Zeppelin Solutions and Aragon: Proxy Libraries in Solidity</a></li><li><a href="https://blog.zeppelinos.org/smart-contract-upgradeability-using-eternal-storage/">Smart Contract Upgradability using Eternal Storage</a></li><li><a href="https://medium.com/rocket-pool/upgradable-solidity-contract-design-54789205276d">Rocket Pool: Upgradable Solidity Contract Design</a></li><li><a href="https://blog.colony.io/writing-upgradeable-contracts-in-solidity-6743f0eecc88">Colony: Writing Upgradable Contracts in Solidity</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9778d80d1638" width="1" height="1" alt=""><hr><p><a href="https://medium.com/level-k/flexible-upgradability-for-smart-contracts-9778d80d1638">Flexible Upgradability for Smart Contracts</a> was originally published in <a href="https://medium.com/level-k">Level K</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Smart Contracts with Truffle]]></title>
            <link>https://medium.com/level-k/testing-smart-contracts-with-truffle-7849b3d9961?source=rss-90ab7d8b6ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7849b3d9961</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[truffle]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Mike Calvanese]]></dc:creator>
            <pubDate>Tue, 25 Jul 2017 22:36:32 GMT</pubDate>
            <atom:updated>2017-07-25T22:36:32.847Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve started building DApps on Ethereum, you’re probably using the <a href="http://truffleframework.com/">Truffle Framework</a>. Truffle provides many features to make your life as a smart contract developer easier. In this post, I’ll focus on truffle test and describe my experience writing tests for a very basic smart contract.</p><h3>Getting Started</h3><p>Before reading this, you should have some familiarity with developing Ethereum smart contracts and <a href="https://solidity.readthedocs.io/">Solidity</a>. If not, I recommend reading:</p><ul><li><a href="https://medium.com/@ConsenSys/a-101-noob-intro-to-programming-smart-contracts-on-ethereum-695d15c1dab4">A 101 Noob Intro to Programming Smart Contracts on Ethereum</a></li><li><a href="https://medium.com/@mvmurthy/ethereum-for-web-developers-890be23d1d0c">Ethereum for Web Developers</a></li><li><a href="https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2">Part 1</a>, <a href="https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-2-30b3d335aa1f">Part 2</a>, and <a href="https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-3-331c2712c9df">Part 3</a> of the DApp tutorial by <a href="https://medium.com/u/14d83a8fab8c">Mahesh Murthy</a>.</li></ul><p>I reference my <a href="https://github.com/cryptocrew/solidity-testing-example">example project</a> a few times in this post. This project contains some helpful patterns that you can use to test your contracts. I would also recommend looking at the tests in <a href="https://github.com/OpenZeppelin/zeppelin-solidity">zeppelin-solidity</a>. These are cleanly written and contain some useful reusable patterns.</p><p>You’ll also want to be familiar with <a href="https://github.com/ethereumjs/testrpc">testrpc</a>, since this is the environment you’ll most often run tests on.</p><h3>Truffle Testing Basics</h3><p>Tests in a Truffle project can be written in <a href="http://truffleframework.com/docs/getting_started/javascript-tests">Javascript</a> or <a href="http://truffleframework.com/docs/getting_started/solidity-tests">Solidity</a>. While creating the example project, I was able to implement all of my test cases in Javascript. I’d recommend starting with Javascript tests if you’re coming from a JS background. So far, I’ve been able to cover all of my test cases with JS.</p><p>Running truffle test executes all tests in your truffle project. This does the following:</p><ol><li>Compiles your contracts</li><li>Runs migrations to deploy the contracts to the network</li><li>Runs tests against the contracts deployed on the network</li></ol><p>Keep in mind that you can run truffle test against testrpc, a testnet, or even the main net (although that would be quite expensive). The recommended approach is to run against testrpc during development, and run against a testnet before deploying to main net. The primary advantages of running against testrpc are speed and the ability to run tests on a clean environment.</p><h3>Avoiding Interactions</h3><p>I ran into some problems with unwanted interactions between my tests. These were happening for me for a few reasons:</p><p>First, the examples in the Truffle docs use MyContract.deployed() to test against the contract instance deployed by truffle test. This presents a problem - if the state of MyContract.deployed() is modified by a test, this will affect subsequent tests. I ended up running MyContract.new() before every test instead, so each test is executed with a clean contract state. By doing this, I was able to execute single tests or change the order of tests without having to worry about getting different results.</p><p>Another problem I had was related to testrpc account balances. When testrpc starts up, it is seeded with 10 accounts. Each one has a balance of 100 ETH. I had a few tests that involved these accounts paying ETH to my contract. With testrpc running in the background, and after many runs of my test suite, these accounts were depleted and my tests started failing. One obvious way to solve this is to write tests with smaller transactions. I opted instead to add an <a href="https://github.com/cryptocrew/solidity-testing-example/blob/74630d9fe4e7783e9bd38b3662da7294376259b9/package.json#L6">npm script</a> to run testrpc, run my test suite, and kill testrpc after the test suite completes:</p><pre>(testrpc &gt; /dev/null &amp; truffle test) &amp;&amp; kill -9 $(lsof -ti :8545)</pre><p>OpenZeppelin uses a similar technique, implemented in <a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.2.0/scripts/test.sh">this script</a></p><h3>Wrangling Your Promise Chains</h3><p>Every call or transaction you execute from <a href="https://github.com/ethereum/web3.js/">web3.js</a> or truffle is asynchronous. Truffle uses promises. web3.js uses callbacks. Either way, you’re going to be writing a ton of asynchronous code.</p><p>I can’t stress enough how much <a href="https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9">async/await</a> will help. You’ll have to upgrade to Node 7.6 or higher. It may be the best decision of your life. Here’s an example, before using async/await:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5dd4d148990dda81c4cb8176d34ed3a/href">https://medium.com/media/b5dd4d148990dda81c4cb8176d34ed3a/href</a></iframe><p>Using async/await, this becomes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f7681e8fd9b5a1fcb9b93cfdfe195cc/href">https://medium.com/media/3f7681e8fd9b5a1fcb9b93cfdfe195cc/href</a></iframe><p>With async/await you’re going to have a much easier time abstracting test helpers (see <a href="https://github.com/cryptocrew/solidity-testing-example/blob/74630d9fe4e7783e9bd38b3662da7294376259b9/test/helpers.js">these examples</a>). Your code will be less error prone, more readable, and more concise.</p><h3>Debugging</h3><p>At the time when I’m writing this, there’s no debugger for Ethereum smart contracts. This might feel like a bit of a hack, but I found it useful to write a helper function to output the state of my contract. The output logger for the ThresholdPool contract looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6766980dd904cd09f2b574973d801b63/href">https://medium.com/media/6766980dd904cd09f2b574973d801b63/href</a></iframe><p>(<a href="https://github.com/cryptocrew/solidity-testing-example/blob/74630d9fe4e7783e9bd38b3662da7294376259b9/test/thresholdPool.js#L361">here it is in the example project</a>)</p><p>Within your tests, you can execute the state logger before or after making modifications to contract state. Since we’re only reading data here and not modifying contract state, this should not affect the test results or account balances.</p><h3>Mock Contract Pattern</h3><p>Truffle and testrpc don’t provide any mechanism for mocking <a href="http://solidity.readthedocs.io/en/develop/units-and-global-variables.html">globally available variable</a> values. You can accomplish this by implementing a mock contract. In the following example, I use a mock contract to mock current time, provided by the now variable in Solidity. The same pattern can be applied in order to mock any value in your contracts.</p><p>First, I added a currentTime() function to my <a href="https://github.com/cryptocrew/solidity-testing-example/blob/74630d9fe4e7783e9bd38b3662da7294376259b9/contracts/ThresholdPool.sol">ThresholdPool contract</a> and have it return now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8563eb63a2e9afe6851e644eb66d333b/href">https://medium.com/media/8563eb63a2e9afe6851e644eb66d333b/href</a></iframe><p>currentTime() is used throughout ThresholdPool.sol to obtain the value of now. I override this in my mock contract, ThresholdPoolMock.sol, so that it returns a different value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56c5d4ffaeac70e1d51072e8dda781f3/href">https://medium.com/media/56c5d4ffaeac70e1d51072e8dda781f3/href</a></iframe><p>Since ThresholdPoolMock extends ThresholdPool, I can now run all of my tests against ThresholdPoolMock. The mock contract lets me set the return value of currentTime() to any value when deploying my contract. I added another function, changeTime(), which lets me change the return value of currentTime() after the contract is deployed. Now I can run a transaction, call changeTime() to simulate passage of time, then run another transaction and test the result. <a href="https://github.com/cryptocrew/solidity-testing-example/blob/74630d9fe4e7783e9bd38b3662da7294376259b9/test/thresholdPool.js#L298">Here’s an example</a>.</p><p><em>*Note that you can also update time on </em>testrpc<em> using </em>evm_increaseTime<em>, see </em><a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.2.0/test/helpers/increaseTime.js"><em>this example</em></a><em>.</em></p><h3>That’s It!</h3><p>Hopefully this helps you get started with your tests. Building a test suite while developing new smart contracts is an absolute necessity. Using truffle console or a similar client to test manually is useful for debugging, but not a replacement for test coverage. Since there’s real money at stake, security and stability of your solidity code is incredibly important. I encourage you to leverage well tested contracts from well established libraries whenever possible. But when you choose to build contracts from scratch, make sure the code you deploy is well tested!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7849b3d9961" width="1" height="1" alt=""><hr><p><a href="https://medium.com/level-k/testing-smart-contracts-with-truffle-7849b3d9961">Testing Smart Contracts with Truffle</a> was originally published in <a href="https://medium.com/level-k">Level K</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sazerac: Data-driven Testing for JavaScript]]></title>
            <link>https://medium.com/hackernoon/sazerac-data-driven-testing-for-javascript-e3408ac29d8c?source=rss-90ab7d8b6ec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3408ac29d8c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[jasmine]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mike Calvanese]]></dc:creator>
            <pubDate>Thu, 09 Feb 2017 21:43:16 GMT</pubDate>
            <atom:updated>2019-05-07T06:25:52.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ni9hKbXBf0EVJHYfIEjsmg.png" /></figure><p>I recently built <a href="https://github.com/mikec/sazerac"><strong>Sazerac</strong></a> to address a problem that I often run into when writing <a href="https://hackernoon.com/tagged/javascript">JavaScript</a> tests. I’ve found that in order to create a test suite that is comprehensive, maintainable, and doesn’t have an insane amount of repeated code, I end up using a <a href="https://booker.codes/data-driven-tests-in-javascript-using-mocha/"><strong>data-driven</strong></a> approach. Using this approach at <a href="http://www.rocketinsights.com/"><strong>Rocket Insights</strong></a><strong> </strong>helps us deliver test code that is both useful in catching regressions, and is also easy to read and comprehend.</p><blockquote>“Data-driven” tests are boiled down to a set of given inputs and expected outputs.</blockquote><p>Encapsulating your application code into <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976"><strong>pure functions</strong></a> will help facilitate this input/output testing style, and is generally a good practice to follow.</p><p>While the latest JS stacks (like <a href="https://facebook.github.io/react/"><strong>React</strong></a> + <a href="http://redux.js.org/"><strong>Redux</strong></a>) encourage a pure functional approach, the most widely used testing frameworks (<a href="https://jasmine.github.io/"><strong>Jasmine</strong></a>, <a href="https://mochajs.org/"><strong>Mocha</strong></a>, and <a href="https://facebook.github.io/jest/"><strong>Jest</strong></a>) aren’t <a href="https://hackernoon.com/tagged/designed">designed</a> with this approach in mind. They often assume that you’ll be testing code with side-effects. Think code “spying”, and (to a certain extent) mocking. These features were created for testing impure functions, but there’s nothing to use specifically for testing pure functions.</p><p>I feel strongly about the need for a testing framework with the data-driven approach at its core. Building that framework would be a big undertaking, so I chose a lighter option. I designed <a href="https://github.com/mikec/sazerac">Sazerac</a> as a helper library that works with Jasmine, Mocha, and Jest.</p><p>I might consider turning <a href="https://github.com/mikec/sazerac">Sazerac</a> into a standalone framework, but I’d like to see if people find it useful first.</p><h3>Getting Down to It</h3><p>Let’s look at some code.</p><p>This pure function isPrime() returns true or false depending on whether the given parameter num is a prime number.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dc7308bd2c9c2dd36eebe8464197626/href">https://medium.com/media/3dc7308bd2c9c2dd36eebe8464197626/href</a></iframe><p>Here are some tests for isPrime()<em>, </em>given the numbers 1, 2, 3, and 4.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0005233fd298a2f78a5253e6e8e4d07e/href">https://medium.com/media/0005233fd298a2f78a5253e6e8e4d07e/href</a></iframe><p>That’s a lot of code to write. If I wanted to add more test cases, I’d have to do some copy and paste. This just doesn’t feel right.</p><p>Here are the same tests, using <a href="https://github.com/mikec/sazerac">Sazerac</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a905d2b6077c0f2f82b358da387a560f/href">https://medium.com/media/a905d2b6077c0f2f82b358da387a560f/href</a></iframe><p><a href="https://github.com/mikec/sazerac"><strong>Sazerac</strong></a><strong> will use these test cases to run </strong><strong>describe and </strong><strong>it functions that work with Jasmine, Mocha, Jest.</strong></p><p>The describe/it messages are set based on given input and expected output, so test reports are super consistent:</p><pre>isPrime()<br>  when given 1<br>    ✓ should return true<br>  when given 2<br>    ✓ should return true<br>  when given 3<br>    ✓ should return true<br>  when given 4<br>    ✓ should return false</pre><h3>In The Real World</h3><p>Things are usually more complicated.</p><p>Your code isn’t always as simple as the isPrime() function. Take this React component, for example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98e4709a994daa1a7f88ffa3240b74b8/href">https://medium.com/media/98e4709a994daa1a7f88ffa3240b74b8/href</a></iframe><p>This component expects a product object with 3 props, title, price, and inventory. If any of those props are missing, it renders an error message and an error class at the root element. If all the props have values, it renders a success message and no error class.</p><p>I’m going to use <a href="http://airbnb.io/enzyme/"><strong>Enzyme</strong></a> (awesome for testing React components) to help test this. In my spec file, I’ll create a function to mount the component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec9066d2a36863e50d6a392a7d07ce68/href">https://medium.com/media/ec9066d2a36863e50d6a392a7d07ce68/href</a></iframe><p>This function’s expected return value is complex, so the .expect() method that was used for isPrime()<em> </em>can’t be used here. I’ll use Sazerac’s .assert()<em> </em>method instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50c0ff814060d955b668b5a99c7bc1ee/href">https://medium.com/media/50c0ff814060d955b668b5a99c7bc1ee/href</a></iframe><p>In this example, the p object is the return value of ProductComponent() given {}. The test above will pass if the product element (at the root of the component) has the class error.</p><p><strong>More expectations can be added using additional </strong><strong>.assert() calls on the same test case.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11914c34eaec510e7142a1d1d8d9c568/href">https://medium.com/media/11914c34eaec510e7142a1d1d8d9c568/href</a></iframe><p>Each .assert() call runs a new test for ProductComponent() with the given input, {}. In this example, these 3 tests are run:</p><pre>ProductComponent()<br>  when given {}<br>    ✓ should render `error` class<br>    ✓ should display error message<br>    ✓ should not display success message</pre><h3>And It Gets Better</h3><p>We just tested for the “empty” object case, but what about other cases that might result in a similar state? For example, if title, price, or inventory<em> </em>is missing, we would expect the component to render with the same error state.</p><p><strong>Sazerac’s </strong><strong>forCases() method lets you group test cases that share the same expectations.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6de5fda6ccd8b329df90ad6ff61c913c/href">https://medium.com/media/6de5fda6ccd8b329df90ad6ff61c913c/href</a></iframe><p>Resulting in the following tests:</p><pre>ProductComponent()<br>  when given {}<br>    ✓ should render `error` class<br>    ✓ should display error message<br>    ✓ should not display success message<br>  when given {&quot;price&quot;:&quot;1.11&quot;,&quot;inventory&quot;:&quot;111&quot;}<br>    ✓ should render `error` class<br>    ✓ should display error message<br>    ✓ should not display success message<br>  when given {&quot;title&quot;:&quot;p1&quot;,&quot;inventory&quot;:&quot;111&quot;}<br>    ✓ should render `error` class<br>    ✓ should display error message<br>    ✓ should not display success message<br>  when given {&quot;title&quot;:&quot;p1&quot;,&quot;price&quot;:&quot;1.11&quot;}<br>    ✓ should render `error` class<br>    ✓ should display error message<br>    ✓ should not display success message</pre><p>This ends up being much more concise than the equivalent tests written with describe, it, beforeEach, etc. It also makes it super easy to add new cases, or to update existing ones as needed.</p><h3>Try It Out</h3><p>I’d recommend taking a few of your existing tests and refactoring them to use <a href="https://github.com/mikec/sazerac">Sazerac</a>. My hope is that it will reduce the complexity and increase readability of your tests.</p><p>If you have feedback, get in touch with me on twitter <a href="https://twitter.com/MikeCalvanese">@MikeCalvanese</a></p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3408ac29d8c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/sazerac-data-driven-testing-for-javascript-e3408ac29d8c">Sazerac: Data-driven Testing for JavaScript</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>